Skip to content

feat(domain): verify handlers that sleep, race, time out and run fibers - #3743

Open
sam-goodwin wants to merge 70 commits into
mainfrom
t3/domain-prove-virtual-time
Open

sam-goodwin wants to merge 70 commits into
mainfrom
t3/domain-prove-virtual-time

Conversation

@sam-goodwin

@sam-goodwin sam-goodwin commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

A handler that sleeps, sets a time limit, races two effects or starts a fiber is now proved, for every duration an input can give:

Send: Effect.fn(function* (_dispatch, command) {
  const won = yield* Effect.race(
    Effect.as(Effect.sleep(command.fast * 2), "fast"),
    Effect.as(Effect.sleep(command.slow * 2), "slow"),
  ).pipe(Effect.timeoutOption(command.limit * 2 + 1));
  return [new Sent({ by: Option.getOrElse(won, () => "nobody") })];
}),
transitions: {
  // Proved: the fast courier takes at most 20 milliseconds and the slow one at least 40.
  TheSlowCourierNeverWins: ({ events }) => events.every((event) => event.by !== "slow"),
  // Broken, with a counterexample: a limit shorter than the fast courier leaves no answer.
  SomeoneAlwaysAnswers: ({ events }) => events.every((event) => event.by !== "nobody"),
},

The prover does not model these. It hands the library the handler's effects and lets the library run them, on time that passes only when no fiber can run. What a race, a time limit, an interrupt or a finalizer does is then what the deployed handler does, by being the same code. Supported this way:

Effect.sleep(d); Effect.delay(effect, d); Effect.yieldNow;
Effect.timeout(effect, d); Effect.timeoutOption(effect, d); Effect.timeoutOrElse(effect, options);
Effect.race(a, b); Effect.raceFirst(a, b); Effect.raceAll(all); Effect.raceAllFirst(all);
Effect.forkChild(effect); Effect.forkDetach(effect); Effect.forkScoped(effect);
Fiber.join(fiber); Fiber.await(fiber); Fiber.interrupt(fiber); Fiber.joinAll(all); Fiber.interruptAll(all);
Effect.all(effects, { concurrency: 2 }); Effect.forEach(items, f, { concurrency: "unbounded" });
Effect.zip(a, b, { concurrent: true });
Effect.onExit(effect, f); Effect.onInterrupt(effect, f); Effect.uninterruptible(effect);
Effect.scoped(effect); Effect.acquireRelease(acquire, release); Effect.addFinalizer(f);
Effect.retry(effect, Schedule.exponential("1 second")); // spaced, fixed, fibonacci, windowed, max, min, concat, upTo, …
Deferred.await(done); Queue.take(line); permits.withPermit(effect); gate.await; // across fibers
SubscriptionRef.changes(cell); // its value now, then each one it is given
Stream.tick("1 second"); Stream.fromQueue(line); Stream.merge(a, b); Stream.debounce(stream, d);
Stream.mapEffect(stream, f, { concurrency: 2 }); Stream.flatMap(stream, f, { concurrency: 2 });
Stream.timeout(stream, d); Stream.groupedWithin(stream, n, d); Stream.haltWhen(stream, effect); // …
PubSub.publish(hub, a); PubSub.take(subscription); Stream.fromPubSub(hub);
FiberSet.run(set, effect); FiberHandle.run(handle, effect);
Effect.tx(effect); Effect.txRetry; TxRef.update(cell, f); TxQueue.take(line); // transactions
Cache.get(prices, "tea"); FiberMap.run(jobs, "one", effect); Pool.get(pool); // by a key the code writes
TxDeferred.await(done); TxSemaphore.withPermit(permits, effect); TxPubSub.publish(hub, a);
TxSubscriptionRef.changes(cell); TxReentrantLock.withWriteLock(lock, effect);
PartitionedSemaphore.withPermit(slots, "x", effect); ScopedCache.get(files, "tea");
Stream.broadcast(stream, options); Stream.share(stream, options);
TxChunk.append(held, a); Effect.request(GetPrice({ item }), prices); // batched by the resolver
BigDecimal.format(BigDecimal.floor(amount, 2)); // a decimal an input holds, once it is rounded

The same holds for what a stream is made of, for a scope the code holds, and for random numbers a seed decides:

Channel.fromIterable([a, b]).pipe(Channel.mapEffect(check), Channel.runCollect); // and the rest of Channel
const pull = yield* Channel.toPull(channel); Pull.catchDone(pull, f); Take.toPull(take);
Stream.fromChannel(channel); Stream.toChannel(stream); Stream.pipeThroughChannel(stream, channel);
TxHashMap.set(stock, key, n); TxHashSet.add(seen, key); TxPriorityQueue.take(line); // a key may be one an input decides
class GetPrice extends Request.TaggedClass("GetPrice")<{ readonly item: number }, number> {}
const scope = yield* Scope.make(); Scope.addFinalizer(scope, f); Scope.close(scope, Exit.void);
ScopedRef.set(ref, acquire); RcRef.get(ref); RcMap.get(map, "tea"); Resource.refresh(resource);
Random.nextIntBetween(1, 10).pipe(Random.withSeed("seed")); // the library's own draw
Effect.retry(effect, Schedule.jittered(schedule)).pipe(Random.withSeed("seed"));

More of the language and of plain values is read too:

try {
  if (grams > 100) throw new Error("too heavy"); // caught: a failure of a yielded effect is not, as in the real handler
} catch (thrown) {
  return [];
} finally {
  count++;
}
outer: for (const parcel of parcels) for (const item of parcel) if (item < 0) continue outer;
a ** 2; (a, b); a == b; 6 & 3; // powers, the comma, == between two of a kind, bits of numbers the code writes
items.toSorted(byWeight); items.with(0, a); items.lastIndexOf(a); items.reduceRight(f, 0);
Object.assign(target, more); Object.fromEntries(pairs); Object.hasOwn(made, "n"); Math.round(a / 2);

class Counter {
  count = 0;
  constructor(readonly step: number) {} // fields, a constructor, methods, this, super, static, #private, get and set
  add() {
    this.count += this.step;
    return this;
  }
}
enum Kind { Good, Gift = 5 } // and a namespace, exported or not
const seen = new Map([[a, "first"]]); new Set(items); // found by ===, kept in the order things were put in
while (count < a) count++; // a number of turns an input decides, up to 64
made.sort(byWeight); made.splice(1, 2); made.pop(); // an array the code made, changed where it stands
String(a); Number("12"); Boolean(a); Array.from(items, f); JSON.stringify({ n: a }); structuredClone(made);
items[a]; a.toString(); text[0]; text.charCodeAt(0); /a+/.test("caat"); thrown instanceof Error; delete made.n;
Math.pow(a, 2); Math.sign(a); Metric.update(orders, a); Hash.string("s");
function* each() { yield a; yield* [1, 2]; } for (const n of each()) total += n; // a generator, gone over
Effect.provide(priced, Layer.merge(Layer.succeed(Rate, { percent: a }), Layer.effect(Fee, fee))); // services, layers, contexts
Effect.retry(effect, { times: command.attempts }); Stream.take(stream, command.count); // a count an input holds between 0 and 64
Graph.directed((mutable) => { Graph.addNode(mutable, "A"); }); HashRing.get(ring, "key"); // of values the code writes
Stream.throttle(stream, { cost: (chunk) => chunk.length, units: 1, duration: "1 second" });
Effect.catchCause(effect, f); Effect.matchCause(effect, cases); Effect.try(() => parse(text)); Effect.forever(effect);
Effect.cached(effect); Effect.sandbox(effect); Effect.firstSuccessOf(effects); Effect.serviceOption(Rate); // and thirty more
Stream.flatten(streams); Stream.switchMap(stream, f); Stream.scanEffect(stream, initial, f); Stream.ensuring(stream, effect); // and fifty more
Queue.collect(queue); Deferred.done(done, exit); PubSub.takeBetween(subscription, 1, 2); Console.table(rows);
DateTime.startOf(noon, "day"); Match.when(Match.string, f); Ref.updateSome(ref, f);

Schema.is(Ticket)(input); // a schema that only checks: the value passes where the prover's formula holds
Schema.decodeUnknownOption(Ticket)(input); // gives the value back, less the fields the schema does not name
Combiner.max(Order.Number).combine(a, b); Number.ReducerSum.combineAll(items); Struct.makeReducer(parts);
MutableList.append(list, a); MutableList.take(list);

Optics, sinks, channels and filters are the library's own, composed as it composes them:

Optic.id().key("items").forEach((each) => each.compose(Optic.some())); // a traversal: a Lens, a Prism, an Optional, as the library puts them together
Optic.modifyAll(order, items, (n) => n + 1); Optic.getResult(order, Optic.id().at("n")); Optic.makeLens(get, replace);
Stream.transduce(stream, Sink.take(3)); Stream.peel(stream, Sink.take(1)); Sink.flatMap(Sink.take(1), (first) => Sink.take(2));
Sink.make()(Stream.map((n) => n * 2), Stream.runSum); Sink.fromTransform((upstream) => Effect.map(upstream, (chunk) => [chunk.length]));
Channel.transformPull(channel, (pull) => Effect.succeed(Effect.map(pull, f))); Channel.fromTransform(f); Channel.combine(a, b, s, f);
Stream.combine(left, right, () => true, (s, pullLeft, pullRight) => Effect.map(s ? pullLeft : pullRight, (n) => [n, !s]));
Effect.filterMap(items, (n) => (n > 2 ? Result.succeed(n) : Result.fail(n))); Effect.catchFilter(effect, filter, f);
Effect.catchReason(effect, "Call", "Slow", (reason) => recover(reason)); Stream.catchReasons(stream, "Call", cases);
Effect.validate(items, f); Effect.callback((resume) => resume(effect)); Effect.uninterruptibleMask((restore) => restore(effect));
Channel.provideService(channel, Rate, rate); Sink.provideContext(sink, context); Effect.setContext(effect, context);
Match.fn((x, y) => x - y).pipe(Match.when(positive, f), Match.orElse(g)); Match.instanceOf(Odd); Match.literals(handlers);
Layer.catchCause(layer, f); Layer.flatMap(layer, f); Layer.build(layer); Context.pick(Rate)(context);
Clock.clockWith((clock) => clock.currentTimeMillis); RequestResolver.grouped(resolver, key); RequestResolver.fromEffectTagged()(fns);

Aggregate.predict runs a handler on the same clock, so a prediction of one that waits is made at once:

Dispatch.predict(state, new Send({ id, fast: 5, slow: 20, limit: 40 }), { now });
// { _tag: "Accepted", events: [Sent { by: "fast" }] }, without waiting 10 milliseconds

Still reported, each with its reason:

yield* Deferred.await(done); // waits for a Deferred that nothing completes: the handler would never end
Effect.race(Effect.sleep(10), Effect.sleep(10)); // two waits end at the same moment
Effect.repeat(effect, Schedule.spaced("1 second")); // runs an effect again more than 100 times, with Effect.repeat
Random.next; // draws a random number with no seed: no two runs draw the same
Channel.never.pipe(Channel.haltWhen(effect), Channel.runDrain); // waits for a channel that gives nothing more and does not end
Schema.decodeUnknownSync(Schema.NumberFromString)("1"); // a schema that changes the value it reads

A handler that waits again and again without end is now reported (waits more than 10000 times: the handler would never end). This is what a stream's own time limit does in a handler: Stream.timeout works out its deadline from the clock, and a handler's clock stays at the time the command is handled at.

The report's assumptions gain one line: code between two waits takes no time, so a time limit never stops a computation that does not wait.

A path no input takes is no longer reported when the prover stops on it.

Code the library runs at once (a Stream.partitionQueue filter, an Effect.callback register function, a cache's timeToLive) takes both sides of a branch an input decides. A side no input takes is dropped when its path is checked. Before, such a branch asked the solver from inside a synchronous run and left the question running.

Effect.timed, Sink.timed and Sink.withDuration measure with the machine's clock, not the handler's, so they are reported.

A policy's handler that waits is followed by the search of the model too. A test now pins each line of a report that the docs and the skill quote to a message the prover says.

@sam-goodwin sam-goodwin added the deploy-website Deploy the website preview for this PR label Nov 24, 2026
@alchemy-version-bot

alchemy-version-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Website Preview Deployed

URL: https://pr-3743-alchemy-website-preview.testing-2b2.workers.dev

Built from commit 5915225.


This comment updates automatically with each push.

@alchemy-version-bot

alchemy-version-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Install the packages built from this commit:

alchemy

pnpm install https://pkg.alchemy.run/alchemy/pr:3743:5915225
@alchemy.run (15)
pnpm install https://pkg.alchemy.run/@alchemy.run/acme/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/hetzner/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/railway/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/fly/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/cloudflare/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/gcp/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/aws/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/domain/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/kubernetes/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/docker/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/redis/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/sql/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/cloudflare-runtime/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/frontend-frameworks/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/node-utils/pr:3743:5915225
Transitive Dependencies (14)
pnpm install https://pkg.alchemy.run/@distilled.cloud/aws/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/acme/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/core/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/s3/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/hetzner/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/railway/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/fly-io/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/aws4signer/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/cloudflare/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/iceberg/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/gcp/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/effect-cluster/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@alchemy.run/rivet/pr:3743:5915225
pnpm install https://pkg.alchemy.run/@distilled.cloud/rivet/pr:3743:5915225

Published Nov 25, 2026, 3:21 AM UTC. Expires Dec 2, 2026, 3:21 AM UTC, extended while this pull request is open.

…e, and the report's lines pinned to the docs
… and the stream forms of filters and reasons
…on, Optic.get and the library's errors made by the code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deploy-website Deploy the website preview for this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant