From df0b1717e2b973631a2788557360636636cd1a06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:25:49 +0000 Subject: [PATCH 01/11] Make a timer that cannot start one failure mode --- ai-docs/src/37_new-host/index.md | 6 ++-- packages/effect-machine/src/Machine.ts | 21 +++++++------- .../src/internal/machine/clusterTimer.ts | 4 +-- .../src/internal/machine/clusterWork.ts | 5 ++-- .../src/internal/machine/invocation.ts | 2 +- .../internal/machine/invocationResolution.ts | 20 ++++--------- .../src/internal/machine/step.ts | 4 +-- .../test/conformance/matrix.txt | 2 +- .../test/conformance/scenarios/timers.ts | 8 ++--- .../test/conformance/support/hosts/step.ts | 5 +--- .../test/internal/machine/clusterWork.test.ts | 14 ++++----- .../internal/machine/invocationHost.test.ts | 9 +++--- .../internal/machine/invocationStart.test.ts | 10 +++---- .../machine/support/stepDifferential.ts | 4 +-- .../test/machine/MachineStep.test.ts | 2 +- .../test/machine/MachineStepWork.test.ts | 29 +++++++++---------- .../unstable/cluster/ClusterMachine.test.ts | 2 +- 17 files changed, 63 insertions(+), 84 deletions(-) diff --git a/ai-docs/src/37_new-host/index.md b/ai-docs/src/37_new-host/index.md index f5b536a2..71d44806 100644 --- a/ai-docs/src/37_new-host/index.md +++ b/ai-docs/src/37_new-host/index.md @@ -53,9 +53,9 @@ most once and returns an `Exit`: - `Effect`: `work.effect()`, then run it and settle its `Exit`. - `Timer`: `work.duration()` holds how long to wait, then settle with - `Exit.void`. When the input names no duration, the inner `Exit` fails: settle - with it at once, as a timer of zero duration ends. `work.effect()` is the same - timer as an Effect, for a host whose timers wait on fibers. + `Exit.void`. It fails, like every accessor, when the timer cannot start, + also when its input names no duration. `work.effect()` is the same timer as + an Effect, for a host whose timers wait on fibers. - `Stream`: `work.stream()`. Report each element with `element`, pull the next element after that step, and settle with the end of the stream. - `Logic`: `work.logic()`. Run `initial` and `run` with contexts of the host, diff --git a/packages/effect-machine/src/Machine.ts b/packages/effect-machine/src/Machine.ts index dabac8e4..aa427bd2 100644 --- a/packages/effect-machine/src/Machine.ts +++ b/packages/effect-machine/src/Machine.ts @@ -7992,17 +7992,16 @@ export declare namespace MachineStep { * * **Details** * - * `duration` evaluates how long the timer waits, at most once. Its outer - * `Exit` follows the rule of every kind of work: a failure means that the - * timer could not start. The inner `Exit` is how the timer ends: wait for - * the duration it holds, or, when the input of the timer names no duration, - * end at once with its failure, as a timer of zero duration does. A host - * that keeps timers of its own, or stores a due time before it commits a - * step, reads `duration` in the step that enters the state, and settles the - * timer with the inner failure when it would have fallen due. + * `duration` evaluates how long the timer waits, at most once. It follows + * the rule of every kind of work: a failure means that the timer could not + * start, whether its input mapper or source threw, or its input names no + * duration. A host that keeps timers of its own, or stores a due time + * before it commits a step, reads `duration` in the step that enters the + * state, and settles the timer with that failure where it would have + * started. * - * `effect` is the timer as an Effect that sleeps for the duration, or fails - * as the timer fails, for a host whose timers wait on fibers. + * `effect` is the timer as an Effect that sleeps for the duration, for a + * host whose timers wait on fibers. It fails as `duration` fails. * * @category models * @since 0.48.0 @@ -8011,7 +8010,7 @@ export declare namespace MachineStep { readonly _tag: "Timer" /** Evaluates how long the timer waits, at most once. */ - readonly duration: () => Exit.Exit> + readonly duration: () => Exit.Exit /** Evaluates the timer as an Effect that waits for its duration. */ readonly effect: () => Exit.Exit> diff --git a/packages/effect-machine/src/internal/machine/clusterTimer.ts b/packages/effect-machine/src/internal/machine/clusterTimer.ts index bea786d8..af03753b 100644 --- a/packages/effect-machine/src/internal/machine/clusterTimer.ts +++ b/packages/effect-machine/src/internal/machine/clusterTimer.ts @@ -34,8 +34,8 @@ export const schedule = ( for (const work of running) { if (work._tag !== "Timer" || ClusterProgress.get(scheduled, work) !== undefined) continue const duration = work.duration() - if (Exit.isSuccess(duration) && Exit.isSuccess(duration.value)) { - scheduled = ClusterProgress.wait(scheduled, work, dueAt(now, duration.value.value)) + if (Exit.isSuccess(duration)) { + scheduled = ClusterProgress.wait(scheduled, work, dueAt(now, duration.value)) } } return scheduled diff --git a/packages/effect-machine/src/internal/machine/clusterWork.ts b/packages/effect-machine/src/internal/machine/clusterWork.ts index a514895a..bf272f4e 100644 --- a/packages/effect-machine/src/internal/machine/clusterWork.ts +++ b/packages/effect-machine/src/internal/machine/clusterWork.ts @@ -218,9 +218,8 @@ const construct = ( // The duration was read before the state was stored. A failure of that // is reported here, where the local runtime would have read it. const duration = work.duration() - if (Exit.isFailure(duration)) return duration - return Exit.isFailure(duration.value) - ? Exit.succeed(Effect.failCause(duration.value.cause)) + return Exit.isFailure(duration) + ? Exit.failCause(duration.cause) : Exit.die(new Error(`Timer "${work.id}" of state "${work.path}" has no due time`)) } case "Child": diff --git a/packages/effect-machine/src/internal/machine/invocation.ts b/packages/effect-machine/src/internal/machine/invocation.ts index 1204dc2e..c88f9716 100644 --- a/packages/effect-machine/src/internal/machine/invocation.ts +++ b/packages/effect-machine/src/internal/machine/invocation.ts @@ -45,7 +45,7 @@ const delay = ( duration: ReturnType ): Runtime.ProcessLogic => ({ initial: () => Effect.void, - run: () => Effect.flatMap(duration, Effect.sleep) + run: () => Effect.sleep(duration) }) const streamLogic = ( diff --git a/packages/effect-machine/src/internal/machine/invocationResolution.ts b/packages/effect-machine/src/internal/machine/invocationResolution.ts index e1f8d84d..a04f97c0 100644 --- a/packages/effect-machine/src/internal/machine/invocationResolution.ts +++ b/packages/effect-machine/src/internal/machine/invocationResolution.ts @@ -30,7 +30,6 @@ import * as Duration from "effect/Duration" import type * as Effect from "effect/Effect" -import * as Exit from "effect/Exit" import type * as Stream from "effect/Stream" import type { ChildMachine, ChildOwner, Logic, Machine, MachineTarget } from "../../Machine.js" import * as CapturedInvocation from "./capturedInvocation.js" @@ -73,15 +72,15 @@ export interface EffectInvocation extends NamedBase { * A timer completes with `undefined` once its duration has elapsed. * * `duration` is lazy because a parameterized timer runs its input mapper and - * source function. A throw belongs to the host's startup boundary. An input that - * does not name a duration is the failed `Exit`, which the host reports as the - * timer's own outcome. + * source function. It throws when the timer cannot start: when either throws, + * and when the input names no duration. A throw belongs to the host's startup + * boundary, so a timer that cannot start fails in one way. * * @internal */ export interface TimerInvocation extends NamedBase { readonly _tag: "Timer" - readonly duration: () => Exit.Exit + readonly duration: () => Duration.Duration } /** @internal */ @@ -164,14 +163,6 @@ const outcomeChannels = (definition: CapturedInvocation.CapturedInvocation): Out (definition.onSnapshot === undefined ? 0 : 8) ]! -const toDuration = (input: Duration.Input): Exit.Exit => { - try { - return Exit.succeed(Duration.fromInputUnsafe(input)) - } catch (error) { - return Exit.die(error) - } -} - type CapturedChild = Extract // A child without input does not depend on its entry context, so neither @@ -207,7 +198,8 @@ const resolveDefinition = ( id, sourceName, channels, - duration: () => toDuration(typeof definition.after === "function" ? definition.after(context) : definition.after) + duration: () => + Duration.fromInputUnsafe(typeof definition.after === "function" ? definition.after(context) : definition.after) } } if ("stream" in definition) { diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index 7974ec1c..3bf827f9 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -114,7 +114,7 @@ export type Work = } | WorkBase & { readonly _tag: "Timer" - readonly duration: () => Exit.Exit> + readonly duration: () => Exit.Exit readonly effect: () => Exit.Exit> } | WorkBase & { @@ -541,7 +541,7 @@ const build = ( _tag: "Timer", source: invocation.sourceName, duration, - effect: () => Exit.map(duration(), (wait) => Effect.flatMap(wait, Effect.sleep)) + effect: () => Exit.map(duration(), Effect.sleep) } } case "Stream": diff --git a/packages/effect-machine/test/conformance/matrix.txt b/packages/effect-machine/test/conformance/matrix.txt index 0bdb2886..a7545139 100644 --- a/packages/effect-machine/test/conformance/matrix.txt +++ b/packages/effect-machine/test/conformance/matrix.txt @@ -68,7 +68,7 @@ fires a timer that stays once, until its state is entered again fires again and again in a state that its completion enters again | runs | runs | runs | runs | runs fails when the completion of a timer cannot be applied | runs | runs | runs | runs | runs fails when the duration of a timer throws, in the state that owns it | runs | runs | runs | runs | runs -fails when the input of a timer names no duration, as the end of the timer | runs | runs | runs | runs | runs +fails when the input of a timer names no duration, in the state that owns it | runs | runs | runs | runs | runs evaluates a duration in order with the other invocations of its state | runs | runs | runs | differs | runs never fires a timer of infinite duration | runs | runs | runs | runs | runs counts the timer of its initial state from its start | runs | runs | runs | differs | runs diff --git a/packages/effect-machine/test/conformance/scenarios/timers.ts b/packages/effect-machine/test/conformance/scenarios/timers.ts index df021f6b..422b6f49 100644 --- a/packages/effect-machine/test/conformance/scenarios/timers.ts +++ b/packages/effect-machine/test/conformance/scenarios/timers.ts @@ -423,13 +423,13 @@ const unevaluable = (name: string, duration: () => Duration.Input, failure: stri }) const unnamed: Scenario = { - name: "fails when the input of a timer names no duration, as the end of the timer", + name: "fails when the input of a timer names no duration, in the state that owns it", machine: (fixture) => Machine.make({ root, events: Events, effects: { first: fixture.work("first"), last: fixture.work("last") }, - // A string that names no duration, which only the timer itself reads. + // A string that names no duration, so the timer cannot start. timers: { wait: (input: string) => input as Duration.Input } }).handle({ initial: { target: "Idle" }, @@ -447,8 +447,8 @@ const unnamed: Scenario = { start, steps: [ send(wait(10), { - happens: [waiting(10), started("first"), started("last")], - stopped: ["first", "last"], + happens: [waiting(10), started("first")], + stopped: ["first"], outcome: failed("Error: Invalid Input: soon") }), send({ _tag: "Note" }, { answers: ["Ended"] }) diff --git a/packages/effect-machine/test/conformance/support/hosts/step.ts b/packages/effect-machine/test/conformance/support/hosts/step.ts index 421a3fe5..960ee141 100644 --- a/packages/effect-machine/test/conformance/support/hosts/step.ts +++ b/packages/effect-machine/test/conformance/support/hosts/step.ts @@ -505,10 +505,7 @@ export const stepHost: Host = { case "Timer": { const duration = work.duration() if (Exit.isFailure(duration)) return cannotStart(runner, work, duration) - const wait = duration.value - // A duration that its input does not name ends the timer at once, as one of zero duration does. - if (Exit.isFailure(wait)) return fork(runner, work, wait) - const millis = Duration.toMillis(wait.value) + const millis = Duration.toMillis(duration.value) if (millis <= 0) return fork(runner, work, Effect.void) return Effect.sync(() => { runner.running.set(work, { stopped: false }) diff --git a/packages/effect-machine/test/internal/machine/clusterWork.test.ts b/packages/effect-machine/test/internal/machine/clusterWork.test.ts index b4ebb154..79144f21 100644 --- a/packages/effect-machine/test/internal/machine/clusterWork.test.ts +++ b/packages/effect-machine/test/internal/machine/clusterWork.test.ts @@ -247,18 +247,16 @@ describe("ClusterWork", () => { it.effect("without a due time fail where they would have started", () => Effect.gen(function*() { const { ended, work } = yield* makeTimed - // A duration that its input does not name ends the timer, next to the others. + // A duration that its input does not name ends the start. const named = timers(["first", "invalid", "last"], (id) => id === "invalid" ? "soon" as never : 0) - assert.strictEqual(yield* work.start(named, waiting({ first: 0, last: 0 })), undefined) + const unnamed = yield* work.start(named, waiting({ first: 0, last: 0 })) + assert.strictEqual(unnamed?.work, named[1]) + assert.isTrue(unnamed !== undefined && Exit.isFailure(unnamed.exit) && Exit.hasDies(unnamed.exit)) yield* settle - assert.deepStrictEqual(ended.map(([id, exit]) => [id, Exit.hasDies(exit)]), [ - ["first", false], - ["invalid", true], - ["last", false] - ]) + assert.deepStrictEqual(ended.map(([id]) => id), ["first"]) yield* work.stopAll ended.length = 0 - // A duration that cannot be computed ends the start. + // So does a duration that cannot be computed. const error = new Error("no duration") const thrown = timers(["first", "throws", "last"], (id) => id === "throws" ? diff --git a/packages/effect-machine/test/internal/machine/invocationHost.test.ts b/packages/effect-machine/test/internal/machine/invocationHost.test.ts index 83a73d84..3df84e34 100644 --- a/packages/effect-machine/test/internal/machine/invocationHost.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationHost.test.ts @@ -282,13 +282,12 @@ describe("resolved invocations", () => { assert.strictEqual(withoutInput.input, undefined) }) - it("separates a throwing timer source from an input that names no duration", () => { + it("throws from a timer that cannot start: a throwing source, or an input that names no duration", () => { const { calls, invocations: started } = makeHost() - assert.deepStrictEqual(find(started, "Timer", "fixed").duration(), Exit.succeed(Duration.seconds(2))) - assert.deepStrictEqual(find(started, "Timer", "mapped").duration(), Exit.succeed(Duration.millis(5))) + assert.deepStrictEqual(find(started, "Timer", "fixed").duration(), Duration.seconds(2)) + assert.deepStrictEqual(find(started, "Timer", "mapped").duration(), Duration.millis(5)) assert.deepStrictEqual(calls, ["timer input", "timer source"]) assert.throws(() => find(started, "Timer", "throwing").duration(), "timer source") - const invalid = find(started, "Timer", "invalid").duration() - assert.isTrue(Exit.hasDies(invalid)) + assert.throws(() => find(started, "Timer", "invalid").duration()) }) }) diff --git a/packages/effect-machine/test/internal/machine/invocationStart.test.ts b/packages/effect-machine/test/internal/machine/invocationStart.test.ts index b14f2bbc..13bbb52d 100644 --- a/packages/effect-machine/test/internal/machine/invocationStart.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationStart.test.ts @@ -58,16 +58,16 @@ describe("local timer invocations", () => { assert.strictEqual((Cause.squash(snapshot.cause) as Error).message, "timer source") }).pipe(Effect.scoped)) - it.effect("reports an input that names no duration as the timer's outcome in a later turn", () => + it.effect("cannot start a timer whose input names no duration, in the turn that enters its state", () => Effect.gen(function*() { const steps: Array = [] const ref = yield* openWithRuntimeStrategy(makeMachine(steps, (seconds) => `${seconds} seconds`), strategy) Effect.runSync(ref.send({ _tag: "Go" })) assert.deepStrictEqual(steps, ["first started", "timer mapped"]) - assert.strictEqual(status(ref), "active") - const cause = yield* Effect.flip(Effect.sandbox(ref.join)) - assert.isTrue(Cause.hasDies(cause)) - assert.strictEqual(status(ref), "failed") + const snapshot = Effect.runSync(ref.snapshot) + if (snapshot.status !== "failed") throw new Error(`Unexpected ${snapshot.status}`) + assert.strictEqual(snapshot.state.state.path, "Working") + assert.isTrue(Cause.hasDies(snapshot.cause)) }).pipe(Effect.scoped)) }) } diff --git a/packages/effect-machine/test/internal/machine/support/stepDifferential.ts b/packages/effect-machine/test/internal/machine/support/stepDifferential.ts index b9aec874..6a2d521b 100644 --- a/packages/effect-machine/test/internal/machine/support/stepDifferential.ts +++ b/packages/effect-machine/test/internal/machine/support/stepDifferential.ts @@ -164,9 +164,7 @@ const track = (variant: Variant, step: Step.Step, now: number): void => { const duration = work.duration() variant.due.set( work, - Exit.isSuccess(duration) && Exit.isSuccess(duration.value) - ? now + Duration.toMillis(duration.value.value) - : now + Exit.isSuccess(duration) ? now + Duration.toMillis(duration.value) : now ) } } diff --git a/packages/effect-machine/test/machine/MachineStep.test.ts b/packages/effect-machine/test/machine/MachineStep.test.ts index 9dc455e6..d7a34b6a 100644 --- a/packages/effect-machine/test/machine/MachineStep.test.ts +++ b/packages/effect-machine/test/machine/MachineStep.test.ts @@ -131,7 +131,7 @@ describe("Machine.toStep", () => { const waiting = success(step.send(success(step.start()).state, Events.Wait())) const timer = only(waiting.start) if (timer._tag !== "Timer") throw new Error(`Unexpected ${timer._tag}`) - assert.deepStrictEqual(timer.duration(), Exit.succeed(Exit.succeed(Duration.seconds(90)))) + assert.deepStrictEqual(timer.duration(), Exit.succeed(Duration.seconds(90))) assert.strictEqual(leafOf(step.settle(waiting.state, timer, Exit.void)), "TimedOut") }) diff --git a/packages/effect-machine/test/machine/MachineStepWork.test.ts b/packages/effect-machine/test/machine/MachineStepWork.test.ts index 1c627195..5a4ef5d9 100644 --- a/packages/effect-machine/test/machine/MachineStepWork.test.ts +++ b/packages/effect-machine/test/machine/MachineStepWork.test.ts @@ -78,7 +78,7 @@ describe("Machine.toStep work", () => { load.effect() load.effect() assert.deepStrictEqual(calls, ["map load", "load a"]) - assert.deepStrictEqual(wait.duration(), Exit.succeed(Exit.succeed(Duration.seconds(5)))) + assert.deepStrictEqual(wait.duration(), Exit.succeed(Duration.seconds(5))) wait.effect() wait.duration() feed.stream() @@ -114,21 +114,18 @@ describe("Machine.toStep work", () => { assert.strictEqual((failureOf(failed.exit) as Error).message, "no duration") }) - it.effect("ends a timer whose input names no duration with that failure, as its own end", () => - Effect.gen(function*() { - const step = Machine.toStep(machine(() => "soon" as Duration.Input), { self }) - const started = success(step.start()) - const timer = only(started.start) - if (timer._tag !== "Timer") throw new Error(timer._tag) - // The timer starts: its wait is what fails. - const wait = success(timer.duration()) - assert.isTrue(Exit.isFailure(wait)) - const exit = yield* Effect.exit(success(timer.effect())) - assert.isTrue(Exit.isFailure(exit) && Exit.hasDies(exit)) - const failed = step.settle(started.state, timer, wait) - assert.isTrue(failed.exit !== undefined && Exit.hasDies(failed.exit)) - assert.strictEqual(leafOf(failed), "Waiting") - })) + it("cannot start a timer whose input names no duration, as one whose duration throws", () => { + const step = Machine.toStep(machine(() => "soon" as Duration.Input), { self }) + const started = success(step.start()) + const timer = only(started.start) + if (timer._tag !== "Timer") throw new Error(timer._tag) + const duration = timer.duration() + assert.isTrue(Exit.isFailure(duration) && Exit.hasDies(duration)) + assert.isTrue(Exit.isFailure(timer.effect())) + const failed = step.settle(started.state, timer, duration) + assert.isTrue(failed.exit !== undefined && Exit.hasDies(failed.exit)) + assert.strictEqual(leafOf(failed), "Waiting") + }) }) }) diff --git a/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts b/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts index fd306dcf..2cb5cb82 100644 --- a/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts +++ b/packages/effect-machine/test/unstable/cluster/ClusterMachine.test.ts @@ -4039,7 +4039,7 @@ describe("ClusterMachine", () => { }, "names no duration": { duration: () => "soon" as Duration.Input, - order: ["duration", "first", "third"] + order: ["duration", "first"] } } for (const [name, { duration, order }] of Object.entries(durations)) { From 1e8ca6b8db92c10639a7a9323f0bfd6f304e4d96 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:56:28 +0000 Subject: [PATCH 02/11] Reject a refused event at send of LocalMachine, and document one rule for a transition that throws send of a local reference decodes the event and rejects one that the schema refuses with MachineSchemaDecodeError, and the machine keeps running. Deliveries from work, children, parents and commands are decoded as they enter the mailbox and fail the machine as before. The drains plan decoded events, so nothing is decoded twice. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .changeset/local-rejects-refused-events.md | 9 ++ LLMS.md | 14 +- ai-docs/src/10_modeling/index.md | 8 ++ packages/effect-machine/src/LocalMachine.ts | 12 +- packages/effect-machine/src/Machine.ts | 37 ++++- .../src/internal/machine/process.ts | 15 +- .../src/internal/machine/runtimeCompiled.ts | 114 +++++++++++---- .../src/internal/machine/runtimeGeneric.ts | 97 ++++++++++--- .../src/internal/machine/runtimeProtocol.ts | 133 ++++++++++++++++-- .../src/internal/testing/machine/runtime.ts | 20 ++- .../src/unstable/cluster/ClusterMachine.ts | 7 +- .../src/unstable/reactivity/AtomMachine.ts | 14 +- .../test/conformance/differences.ts | 40 +----- .../test/conformance/matrix.txt | 2 +- .../test/conformance/scenarios/transitions.ts | 9 +- .../test/conformance/support/hosts/atom.ts | 2 +- .../test/conformance/support/hosts/local.ts | 22 ++- .../test/conformance/support/hosts/step.ts | 10 +- .../internal/machine/invocationHost.test.ts | 2 +- .../internal/machine/invocationStart.test.ts | 2 - .../machine/strategyDifferential.test.ts | 7 +- .../test/machine/Machine.test.ts | 31 ++-- .../effect-machine/test/testing/Probe.test.ts | 20 ++- .../test/testing/Runtime.test.ts | 58 ++++++-- .../typetest/machine/MachineStep.tst.ts | 2 +- .../typetest/machine/Readiness.tst.ts | 8 +- 26 files changed, 518 insertions(+), 177 deletions(-) create mode 100644 .changeset/local-rejects-refused-events.md diff --git a/.changeset/local-rejects-refused-events.md b/.changeset/local-rejects-refused-events.md new file mode 100644 index 00000000..958f4c90 --- /dev/null +++ b/.changeset/local-rejects-refused-events.md @@ -0,0 +1,9 @@ +--- +"@typeonce/effect-machine": minor +--- + +`send` of a `LocalMachine` reference now rejects an event that the schema of the machine refuses with `MachineSchemaDecodeError`, and the machine keeps running, as `Machine.toStep` and `ClusterMachine` already do. `MachineTarget.send` and `MachineRef.send` add `MachineSchemaDecodeError` to their error channel, and so do the `send` atoms of `AtomMachine` and a rejected `MachineTest` send. An event that another machine, a child, or work delivers is not checked at its `send`: a refused one still fails the machine that plans it. + +A timer that cannot start now has one failure mode: `Machine.MachineStep.Work.Timer.duration()` returns an `Exit`, which fails when the input mapper or the source throws and when the input names no duration. Every host settles the timer with that failure where it would have started. + +A transition that throws follows one documented rule on every host: the error goes to the sender when one waits for the event to be processed, and otherwise the machine fails. Each host keeps its behaviour. diff --git a/LLMS.md b/LLMS.md index 45afb4b3..a09d135f 100644 --- a/LLMS.md +++ b/LLMS.md @@ -478,6 +478,14 @@ Do not read the clock, generate randomness, call a service, or await work while choosing a transition. Receive such values in an event or produce them through state-owned work first. +A transition that throws follows one rule on every host: the error goes to the +sender when one waits for the event to be processed, and otherwise the machine +fails with it. `send` of `LocalMachine` returns before the event is processed, +so the machine fails; a `ClusterMachine` client waits, so it is rejected and the +machine goes on. An event that its schema refuses is different: every host +rejects it at `send`, `LocalMachine` with `MachineSchemaDecodeError` and +`ClusterMachine` as `InvalidEvent`, and the machine keeps running. + `resolve` is checked against `branches` in both directions, and each `select` call takes the values of the path it is given. An agent can edit this one transition without reading anything else: a missing entry, an entry that is never @@ -1918,9 +1926,9 @@ most once and returns an `Exit`: - `Effect`: `work.effect()`, then run it and settle its `Exit`. - `Timer`: `work.duration()` holds how long to wait, then settle with - `Exit.void`. When the input names no duration, the inner `Exit` fails: settle - with it at once, as a timer of zero duration ends. `work.effect()` is the same - timer as an Effect, for a host whose timers wait on fibers. + `Exit.void`. It fails, like every accessor, when the timer cannot start, + also when its input names no duration. `work.effect()` is the same timer as + an Effect, for a host whose timers wait on fibers. - `Stream`: `work.stream()`. Report each element with `element`, pull the next element after that step, and settle with the end of the stream. - `Logic`: `work.logic()`. Run `initial` and `run` with contexts of the host, diff --git a/ai-docs/src/10_modeling/index.md b/ai-docs/src/10_modeling/index.md index 34f83309..357e54b4 100644 --- a/ai-docs/src/10_modeling/index.md +++ b/ai-docs/src/10_modeling/index.md @@ -470,6 +470,14 @@ Do not read the clock, generate randomness, call a service, or await work while choosing a transition. Receive such values in an event or produce them through state-owned work first. +A transition that throws follows one rule on every host: the error goes to the +sender when one waits for the event to be processed, and otherwise the machine +fails with it. `send` of `LocalMachine` returns before the event is processed, +so the machine fails; a `ClusterMachine` client waits, so it is rejected and the +machine goes on. An event that its schema refuses is different: every host +rejects it at `send`, `LocalMachine` with `MachineSchemaDecodeError` and +`ClusterMachine` as `InvalidEvent`, and the machine keeps running. + `resolve` is checked against `branches` in both directions, and each `select` call takes the values of the path it is given. An agent can edit this one transition without reading anything else: a missing entry, an entry that is never diff --git a/packages/effect-machine/src/LocalMachine.ts b/packages/effect-machine/src/LocalMachine.ts index 5b0bd7de..f041f043 100644 --- a/packages/effect-machine/src/LocalMachine.ts +++ b/packages/effect-machine/src/LocalMachine.ts @@ -422,9 +422,15 @@ export const prepare: < * The delivery order above belongs to references of local machines. The * `Machine.MachineRef` contract promises only delivery. * - * Transition failures are reported through the runtime snapshot, `changes`, and - * `join` rather than being returned by `send`. Sending after the machine reaches - * any terminal state fails immediately with `StoppedError`. + * `send` rejects an event that the schema of the machine refuses with + * `MachineSchemaDecodeError`, and the machine keeps running. Sending after the + * machine reaches any terminal state fails immediately with `StoppedError`. + * + * A transition that throws fails the machine: no sender waits for its event, + * so the failure is reported through the runtime snapshot, `changes`, and + * `join`, by the rule that `Machine.MachineRef` states for `send`. An event that another machine, a child or + * work delivers is not checked at `send`: one that the schema refuses fails the + * machine when it is planned. * * **Example** (Starting a machine in a scope) * diff --git a/packages/effect-machine/src/Machine.ts b/packages/effect-machine/src/Machine.ts index aa427bd2..28c01b2a 100644 --- a/packages/effect-machine/src/Machine.ts +++ b/packages/effect-machine/src/Machine.ts @@ -632,8 +632,12 @@ export interface MachineTarget { /** Unique identity of the running target. */ readonly sessionId: string - /** Accepts an event for delivery, or fails with `StoppedError` once the target has terminated. */ - readonly send: (event: Event) => Effect.Effect + /** + * Accepts an event for delivery. Fails with `StoppedError` once the target has + * terminated, and with `MachineSchemaDecodeError` when the target rejects an + * event that its schema refuses. + */ + readonly send: (event: Event) => Effect.Effect } /** @@ -1319,8 +1323,19 @@ export interface MachineRef - /** Accepts an event for delivery. When the machine processes it is up to its host. */ - readonly send: (event: Event) => Effect.Effect + /** + * Accepts an event for delivery. When the machine processes it is up to its + * host. An event that the schema of the machine refuses is rejected with + * `MachineSchemaDecodeError`, and the machine keeps running; once the machine + * has ended, `send` fails with `StoppedError`. + * + * A transition that throws follows one rule on every host: the error goes to + * the sender when one waits for the event to be processed, and otherwise the + * machine fails with it. A `send` of `LocalMachine` returns before its event + * is processed, so the machine fails; a `ClusterMachine` client waits, so it + * is rejected and the machine goes on. + */ + readonly send: (event: Event) => Effect.Effect /** * Returns the current directly owned child for a typed descriptor. @@ -1450,9 +1465,17 @@ export declare namespace Logic { /** Starts a child process owned by this process. */ readonly spawn: Spawn - /** Sends an event to a machine target or typed parent-local child address. */ + /** + * Sends an event to a machine target or typed parent-local child address. + * An endpoint, such as `parent`, takes every event, and a machine target + * can reject one that its schema refuses. + */ readonly sendTo: { - (target: MachineTarget, event: TargetEvent): Effect.Effect + (target: Endpoint, event: TargetEvent): Effect.Effect + ( + target: MachineTarget, + event: TargetEvent + ): Effect.Effect
>( id: Address, event: ChildAddress.Event
@@ -8304,7 +8327,7 @@ type UnsupportedCapability = R extends MachineRuntime * that has one, and the `children` that its work acts on. * * `send` rejects an event that does not match its schema, and keeps the - * machine. `LocalMachine` takes such an event and fails the machine. + * machine, as `send` of every host does. * * **Gotchas** * diff --git a/packages/effect-machine/src/internal/machine/process.ts b/packages/effect-machine/src/internal/machine/process.ts index 75017d81..0f12b8c6 100644 --- a/packages/effect-machine/src/internal/machine/process.ts +++ b/packages/effect-machine/src/internal/machine/process.ts @@ -14,7 +14,9 @@ import * as ExecutionPlan from "./executionPlan.js" import { type CapturedStateConfig, toImpl } from "./implementation.js" import * as Invocation from "./invocation.js" import * as InvocationChanges from "./invocationChanges.js" +import * as InvocationEvent from "./invocationEvent.js" import * as internalPlanner from "./planner.js" +import { decodeEventSync } from "./protocol.js" import * as ProcessRuntime from "./runtime.js" import * as internalRuntimeProtocol from "./runtimeProtocol.js" import * as Serialization from "./serialization.js" @@ -179,8 +181,9 @@ const makeChildlessCompiledDrain = ( const before = context.state() let planned + if (event instanceof internalRuntimeProtocol.RefusedEvent) return failPlanning(event.error) try { - planned = executionPlan.plan( + planned = executionPlan.planDecoded( context.executionState ?? executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, before)), event, @@ -297,8 +300,9 @@ const makeInvokingCompiledDrain = ( const before = current let planned + if (event instanceof internalRuntimeProtocol.RefusedEvent) return failPlanning(event.error) try { - planned = executionPlan.plan( + planned = executionPlan.planDecoded( configuration ?? executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, current)), event, @@ -481,6 +485,7 @@ const makeProcessLogic = ( execution: { _tag: "Compiled", childless: !hasInvokes, + decodeEvent: (event) => InvocationEvent.isInvocationEvent(event) ? event : decodeEventSync(machine, event), ...(entry._tag === "Initial" ? { initial: makeInitial } : {}), ...(makeCompiledInitial === undefined ? {} : { initialSync: makeCompiledInitial }), drain: hasInvokes @@ -529,9 +534,10 @@ const makeProcessLogic = ( const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) const event = acknowledged ? message.event : message const before = current + if (event instanceof internalRuntimeProtocol.RefusedEvent) return yield* failPlanning(event.error) let planned try { - planned = internalPlanner.planConfiguration( + planned = internalPlanner.planDecodedConfiguration( machine, Configuration.withMachineReferences( configuration ?? Configuration.normalizeConfigurationSync(machine, current), @@ -637,9 +643,10 @@ const makeProcessLogic = ( const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) const event = acknowledged ? message.event : message const before = current + if (event instanceof internalRuntimeProtocol.RefusedEvent) return yield* failPlanning(event.error) let planned try { - planned = internalPlanner.planConfiguration( + planned = internalPlanner.planDecodedConfiguration( machine, Configuration.withMachineReferences( configuration ?? Configuration.normalizeConfigurationSync(machine, current), diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 50a5a517..8c6cc10c 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -13,7 +13,7 @@ import * as Stream from "effect/Stream" import type * as Take from "effect/Take" import type { Inspection } from "../../LocalMachine.js" import { type ChildSelector } from "./childRegistry.js" -import { StoppedError } from "./errors.js" +import { type MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" import { classifyOutcome } from "./observation.js" import { @@ -27,6 +27,9 @@ import { type CompiledProcessContext, type CompiledProcessExecution, type CompiledProcessInitial, + decodeDelivered, + decodeSent, + deliverEvent, type EmissionRuntime, EmissionsClosed, failAcknowledgedMessage, @@ -54,6 +57,7 @@ import { type ProcessRuntime, publishInspectedSent, type RuntimeSnapshot, + sendEndpoint, sendMachineTarget, snapshotObserver, type StartInternalOptions, @@ -84,18 +88,31 @@ class CompiledProcess implements MachineRef { readonly id: string readonly sessionId: string readonly inspectionSubject?: Inspection.Subject - readonly send: (event: unknown) => Effect.Effect + readonly send: (event: unknown) => Effect.Effect sendInspected( event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined ): Effect.Effect { - return this.offerEvent(event, source, causedBy) + return this.deliver(event, source, causedBy) + } + [deliverEvent]( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { + return this.deliver(event, source, causedBy) } [acknowledgedSend]( event: unknown ): Effect.Effect, unknown | StoppedError> { - return this.sendAcknowledgedEffect(event) + return Effect.suspend(() => { + if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) + const decoded = decodeSent(this.execution.decodeEvent, event) + return decoded._tag === "Rejected" + ? Effect.fail(decoded.error) + : this.sendAcknowledgedEffect(decoded.event, event) + }) } [snapshotObserver](observer: () => void): () => void { const observers = this.snapshotObservers ??= new Set() @@ -155,14 +172,14 @@ class CompiledProcess implements MachineRef { if (options.programInvocation !== undefined) this.programInvocation = { ...options.programInvocation, sessionId } } this.externalEmissions = options.emissions - this.send = inspector === undefined - ? (event) => this.offerMessage(event) - : (event) => this.offerEvent(event, undefined, undefined) + this.send = (event) => this.sendPublic(event) + // The endpoint is what the work, the children and the parent of this + // machine send to: it delivers, so a refused event fails this machine. this.address = { id: this.id, sessionId, stop: Effect.suspend(() => this.stopFromProcess()), - send: this.send, + send: (event) => this.deliver(event, undefined, undefined), ...(inspector === undefined ? undefined : { @@ -171,7 +188,7 @@ class CompiledProcess implements MachineRef { event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined - ) => this.offerEvent(event, source, causedBy) + ) => this.deliver(event, source, causedBy) }) } } @@ -248,7 +265,7 @@ class CompiledProcess implements MachineRef { this.address, this.options.runtime, this.services, - (event) => this.sendAcknowledgedEffect(event) + (event) => this.sendAcknowledgedEffect(decodeDelivered(this.execution.decodeEvent, event), event) ) } const parent = this.options.parent @@ -256,7 +273,7 @@ class CompiledProcess implements MachineRef { ? noParentSend : this.inspector === undefined ? parent.send - : (event: unknown) => sendMachineTarget(parent, event, this.inspectionSubject, this.causation())) + : (event: unknown) => sendEndpoint(parent, event, this.inspectionSubject, this.causation())) this.processScope = { self: this.address, parent, @@ -266,14 +283,14 @@ class CompiledProcess implements MachineRef { sendTo: ((target: unknown, event: unknown) => isMachineTarget(target) ? this.inspector === undefined - ? target.send(event) + ? sendMachineTarget(target, event, undefined, undefined) : sendMachineTarget(target, event, this.inspectionSubject, this.causation()) : this.childRuntime.sendTo( target as ChildSelector, event, this.inspectionSubject, this.causation() - )), + )) as ProcessInitialContext["sendTo"], stopChild: this.childRuntime.stop, failCause: (cause: Cause.Cause) => this.failCause(cause), inspectInitial: this.inspector === undefined @@ -330,7 +347,7 @@ class CompiledProcess implements MachineRef { self.address, self.options.runtime, self.services, - (event) => self.sendAcknowledgedEffect(event) + (event) => self.sendAcknowledgedEffect(decodeDelivered(self.execution.decodeEvent, event), event) ) } const parent = self.options.parent @@ -338,7 +355,7 @@ class CompiledProcess implements MachineRef { ? noParentSend : self.inspector === undefined ? parent.send - : (event: unknown) => sendMachineTarget(parent, event, self.inspectionSubject, self.causation())) + : (event: unknown) => sendEndpoint(parent, event, self.inspectionSubject, self.causation())) self.processScope = { self: self.address, parent, @@ -348,14 +365,14 @@ class CompiledProcess implements MachineRef { sendTo: ((target: unknown, event: unknown) => isMachineTarget(target) ? self.inspector === undefined - ? target.send(event) + ? sendMachineTarget(target, event, undefined, undefined) : sendMachineTarget(target, event, self.inspectionSubject, self.causation()) : self.childRuntime.sendTo( target as ChildSelector, event, self.inspectionSubject, self.causation() - )), + )) as ProcessInitialContext["sendTo"], stopChild: self.childRuntime.stop, failCause: (cause: Cause.Cause) => self.failCause(cause), inspectInitial: self.inspector === undefined @@ -536,13 +553,43 @@ class CompiledProcess implements MachineRef { ) } + /** + * A public `send`: an event that the schema refuses is rejected, and the + * machine keeps running. A machine that has ended rejects first. + */ + private sendPublic(event: unknown): Effect.Effect { + if (this.inspector === undefined) return this.offerMessage(event, "Sent") + return Effect.suspend((): Effect.Effect => { + if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) + const decoded = decodeSent(this.execution.decodeEvent, event) + return decoded._tag === "Rejected" + ? Effect.fail(decoded.error) + : this.offerEvent(decoded.event, undefined, undefined, undefined, event) + }) + } + + /** A delivery from work, a child, a parent or a command of another machine. */ + private deliver( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { + if (this.inspector === undefined) { + return this.offerMessage(event, "Delivered") as Effect.Effect + } + return Effect.suspend(() => + this.offerEvent(decodeDelivered(this.execution.decodeEvent, event), source, causedBy, undefined, event) + ) + } + private sendAcknowledgedEffect( - event: unknown + event: unknown, + sent: unknown = event ): Effect.Effect, unknown | StoppedError> { return Effect.uninterruptibleMask((restore) => Deferred.make, unknown>().pipe( Effect.flatMap((deferred) => - this.offerEvent(event, undefined, undefined, deferred).pipe( + this.offerEvent(event, undefined, undefined, deferred, sent).pipe( Effect.andThen(restore(Deferred.await(deferred))) ) ) @@ -554,7 +601,8 @@ class CompiledProcess implements MachineRef { event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined, - deferred?: Deferred.Deferred, unknown> + deferred: Deferred.Deferred, unknown> | undefined, + sent: unknown ): Effect.Effect { return Effect.suspend(() => { const inspector = this.inspector @@ -566,21 +614,39 @@ class CompiledProcess implements MachineRef { event, source, causedBy, - deferred + deferred, + sent ) : deferred === undefined ? event : { [AcknowledgedMessageTypeId]: true as const, event, deferred } - return this.offerMessage(message) + return this.offerMessage(message) as Effect.Effect }) } - private offerMessage(message: ProcessMessage): Effect.Effect { + /** + * Offers a message. Without an inspector, `send` and a delivery offer the + * event as it was sent, and it is decoded here, once the machine is known to + * run: `"Sent"` rejects a refused event, and `"Delivered"` lets the drain + * fail the machine with it. + */ + private offerMessage( + offered: ProcessMessage, + decoding: "Decoded" | "Sent" | "Delivered" = "Decoded" + ): Effect.Effect { return Effect.uninterruptible( - Effect.withFiber((fiber) => { + Effect.withFiber((fiber): Effect.Effect => { if (this.mailbox.closed || this.lifecycle !== "Active") { return Effect.fail(new StoppedError()) } + let message = offered + if (decoding === "Sent") { + const decoded = decodeSent(this.execution.decodeEvent, offered) + if (decoded._tag === "Rejected") return Effect.fail(decoded.error) + message = decoded.event + } else if (decoding === "Delivered") { + message = decodeDelivered(this.execution.decodeEvent, offered) + } const inspector = this.inspector const subject = this.inspectionSubject if (inspector !== undefined && subject !== undefined) publishInspectedSent(inspector, subject, message) diff --git a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts b/packages/effect-machine/src/internal/machine/runtimeGeneric.ts index 73181877..52c90f57 100644 --- a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts +++ b/packages/effect-machine/src/internal/machine/runtimeGeneric.ts @@ -12,7 +12,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef" import type * as Take from "effect/Take" import type { Inspection } from "../../LocalMachine.js" import { type ChildSelector } from "./childRegistry.js" -import { StoppedError } from "./errors.js" +import { type MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" import { classifyOutcome } from "./observation.js" import { @@ -21,6 +21,10 @@ import { acknowledgedSend, childlessRuntime, closeProcessMailbox, + decodeDelivered, + decodeSent, + type Deliverable, + deliverEvent, executionIsChildless, failAcknowledgedMessage, type InspectedOffer, @@ -48,6 +52,7 @@ import { publishInspectedSent, receiveProcessMailbox, type RuntimeSnapshot, + sendEndpoint, sendMachineTarget, type StartInternalOptions, type StartProcess, @@ -107,20 +112,57 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( Effect.suspend(() => offerProcessMailbox(mailbox, message, onAccepted) ? Effect.void : Effect.fail(new StoppedError()) ) - const offerInspected: InspectedOffer | undefined = inspector === undefined ? undefined : ( - event, - source, - causedBy, - deferred?: Deferred.Deferred, unknown> - ) => + // A machine decodes an event as it enters the mailbox; other logic takes + // its events as they are. + const decodeEvent = logic.execution?._tag === "Compiled" ? logic.execution.decodeEvent : undefined + const offerEvent = ( + event: Event, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined, + deferred: Deferred.Deferred, unknown> | undefined, + sent: unknown + ): Effect.Effect => Effect.suspend(() => { + if (inspector === undefined) { + return offerDirect( + deferred === undefined ? event : { [AcknowledgedMessageTypeId]: true as const, event, deferred } + ) + } const message: ProcessMessage = inspector.isActive() - ? makeInspectedMessage(inspector, subject!, event, source, causedBy, deferred) + ? makeInspectedMessage(inspector, subject!, event, source, causedBy, deferred, sent) : deferred === undefined ? event : { [AcknowledgedMessageTypeId]: true as const, event, deferred } return offerDirect(message, () => publishInspectedSent(inspector, subject!, message)) }) + // A delivery from work, a child, a parent or a command of another machine: + // a refused event fails this machine when it is planned. + const deliver = ( + event: Event, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect => + Effect.suspend(() => + offerEvent( + decodeEvent === undefined ? event : decodeDelivered(decodeEvent, event) as Event, + source, + causedBy, + undefined, + event + ) + ) + // A public `send` rejects an event that the schema refuses, and the machine + // keeps running. A machine that has ended rejects first. + const sendPublic = (event: Event): Effect.Effect => + Effect.suspend((): Effect.Effect => { + if (decodeEvent === undefined) return deliver(event, undefined, undefined) + if (mailbox.closed) return Effect.fail(new StoppedError()) + const decoded = decodeSent(decodeEvent, event) + return decoded._tag === "Rejected" + ? Effect.fail(decoded.error) + : offerEvent(decoded.event as Event, undefined, undefined, undefined, event) + }) + const offerInspected: InspectedOffer | undefined = inspector === undefined ? undefined : deliver const sendAcknowledged: | ((event: Event) => Effect.Effect, Error | StoppedError>) | undefined = logic.execution?._tag !== "Compiled" @@ -129,9 +171,13 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( Effect.uninterruptibleMask((restore) => Deferred.make, unknown>().pipe( Effect.flatMap((deferred) => { - const offered = inspector === undefined - ? offerDirect({ [AcknowledgedMessageTypeId]: true as const, event, deferred }) - : offerInspected!(event, undefined, undefined, deferred) + const offered = offerEvent( + decodeEvent === undefined ? event : decodeDelivered(decodeEvent, event) as Event, + undefined, + undefined, + deferred, + event + ) return offered.pipe(Effect.andThen(restore(Deferred.await(deferred)))) }), Effect.map((delivery) => delivery as AcknowledgedDelivery) @@ -151,9 +197,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( ? requestStop : requestStop.pipe(Effect.andThen(Effect.never)) ), - send: inspector === undefined - ? (event) => offerDirect(event) - : (event) => offerInspected!(event, undefined, undefined), + send: (event) => deliver(event, undefined, undefined), ...(inspector === undefined ? undefined : { inspectionSubject: subject!, sendInspected: offerInspected! }) @@ -211,7 +255,7 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( ? noParentSend : inspector === undefined ? parent.send - : (event) => sendMachineTarget(parent, event, subject, currentCausation())) + : (event) => sendEndpoint(parent, event, subject, currentCausation())) const emit = inspector === undefined ? emissions.emit : (event: unknown) => @@ -229,11 +273,15 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( ) const sendToTarget: ProcessInitialContext["sendTo"] = inspector === undefined ? ((target: unknown, event: unknown) => - isMachineTarget(target) ? target.send(event) : sendTo(target as ChildSelector, event)) + isMachineTarget(target) + ? sendMachineTarget(target, event, undefined, undefined) + : sendTo(target as ChildSelector, event)) as ProcessInitialContext["sendTo"] : ((target: unknown, event: unknown) => isMachineTarget(target) ? sendMachineTarget(target, event, subject, currentCausation()) - : sendTo(target as ChildSelector, event, subject, currentCausation())) + : sendTo(target as ChildSelector, event, subject, currentCausation())) as ProcessInitialContext< + Event + >["sendTo"] const scope: ProcessInitialContext = { self, @@ -710,8 +758,19 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( emissions: emissions.stream as Stream.Stream, join: Deferred.await(done), stop, - send: self.send, - ...(sendAcknowledged === undefined ? undefined : { [acknowledgedSend]: sendAcknowledged }), + send: sendPublic, + [deliverEvent]: deliver as Deliverable[typeof deliverEvent], + ...(sendAcknowledged === undefined ? undefined : { + [acknowledgedSend]: (event: Event) => + Effect.suspend( + (): Effect.Effect, Error | StoppedError | MachineSchemaDecodeError> => { + if (decodeEvent === undefined) return sendAcknowledged(event) + if (mailbox.closed) return Effect.fail(new StoppedError()) + const decoded = decodeSent(decodeEvent, event) + return decoded._tag === "Rejected" ? Effect.fail(decoded.error) : sendAcknowledged(event) + } + ) + }), child: getChild, childChanges } diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 6487a902..0d67f697 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -34,7 +34,7 @@ import { takeChildObservations, unregisterChild } from "./childRegistry.js" -import { ChildAlreadyExistsError, StoppedError } from "./errors.js" +import { ChildAlreadyExistsError, MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" import type * as InvocationEvent from "./invocationEvent.js" import { InvocationGenerations } from "./invocationGeneration.js" @@ -65,6 +65,82 @@ export interface SnapshotObservable { export const isSnapshotObservable = (value: unknown): value is SnapshotObservable => typeof value === "object" && value !== null && snapshotObserver in value +/** + * Delivery between the machines of one runtime. A public `send` rejects an + * event that the schema of the machine refuses; a delivery takes it, and the + * machine fails with that error when the event is planned, as a public event + * that a command, a parent or a child sends always has. + * + * @internal + */ +export const deliverEvent: unique symbol = Symbol.for("effect/Machine/deliverEvent") + +/** @internal */ +export interface Deliverable { + readonly [deliverEvent]: ( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ) => Effect.Effect +} + +/** + * The event of a delivery that the schema of the machine refused, or whose + * decoding threw. Planning it fails the machine with `error`. + * + * @internal + */ +export class RefusedEvent { + constructor(readonly error: unknown) {} +} + +/** + * Decodes an event that enters a mailbox. An invocation event is the host's + * own and is not decoded. + * + * @internal + */ +export type EventDecoder = (event: unknown) => unknown + +/** + * Decodes an event that a public `send` offers: a refused event is rejected + * with its `MachineSchemaDecodeError`, and any other throw is a defect of the + * machine, which fails when it plans the returned `RefusedEvent`. + * + * @internal + */ +export const decodeSent = ( + decode: EventDecoder | undefined, + event: unknown +): { readonly _tag: "Decoded"; readonly event: unknown } | { + readonly _tag: "Rejected" + readonly error: MachineSchemaDecodeError +} => { + if (decode === undefined) return { _tag: "Decoded", event } + try { + return { _tag: "Decoded", event: decode(event) } + } catch (error) { + return error instanceof MachineSchemaDecodeError + ? { _tag: "Rejected", error } + : { _tag: "Decoded", event: new RefusedEvent(error) } + } +} + +/** + * Decodes an event that a delivery offers. A refused event becomes a + * `RefusedEvent`, so the machine fails when it plans it. + * + * @internal + */ +export const decodeDelivered = (decode: EventDecoder | undefined, event: unknown): unknown => { + if (decode === undefined) return event + try { + return decode(event) + } catch (error) { + return new RefusedEvent(error) + } +} + /** @internal */ export const acknowledgedSend: unique symbol = Symbol.for("effect/Machine/acknowledgedSend") @@ -166,9 +242,11 @@ export interface MachineRef["sendInspected"] + /** @internal */ + readonly [deliverEvent]?: Deliverable[typeof deliverEvent] readonly [acknowledgedSend]?: ( event: Event - ) => Effect.Effect, Error | StoppedError> + ) => Effect.Effect, Error | StoppedError | MachineSchemaDecodeError> readonly child: (child: any) => Effect.Effect> readonly childChanges: (child: any) => Stream.Stream> } @@ -209,11 +287,34 @@ export const sendMachineTarget = ( event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined -): Effect.Effect => - "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function" +): Effect.Effect => + deliverEvent in target + ? (target as unknown as Deliverable)[deliverEvent](event, source, causedBy) + : "inspectionSubject" in target && "sendInspected" in target && typeof target.sendInspected === "function" ? target.sendInspected(event, source, causedBy) : target.send(event) +/** Sends to an endpoint of this runtime, which delivers. */ +export const sendEndpoint = ( + endpoint: ProcessEndpoint, + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined +): Effect.Effect => + endpoint.sendInspected === undefined ? endpoint.send(event) : endpoint.sendInspected(event, source, causedBy) + +/** Delivers to a child, which this runtime started and which always delivers. */ +const deliverToChild = ( + ref: MachineRef, + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined +): Effect.Effect => { + return ref[deliverEvent] === undefined + ? Effect.die(new Error("A child of a local machine cannot take deliveries")) + : ref[deliverEvent](event, source, causedBy) +} + export interface ProcessInitialContext { readonly self: ProcessEndpoint readonly parent: ProcessEndpoint | undefined @@ -221,7 +322,11 @@ export interface ProcessInitialContext { readonly sendParent: (event: unknown) => Effect.Effect readonly emit: (event: unknown) => Effect.Effect readonly sendTo: { - (target: MachineTarget, event: TargetEvent): Effect.Effect + (target: ProcessEndpoint, event: TargetEvent): Effect.Effect + ( + target: MachineTarget, + event: TargetEvent + ): Effect.Effect (child: ChildSelector, event: unknown): Effect.Effect } readonly stopChild: (child: ChildSelector) => Effect.Effect @@ -338,6 +443,12 @@ export interface CompiledProcessExecution< > { readonly _tag: "Compiled" readonly childless: boolean + /** + * Decodes a public event as it enters the mailbox, so the drain plans it + * without decoding it again. An invocation event passes unchanged. Without + * it, the process takes events as they are. + */ + readonly decodeEvent?: EventDecoder readonly initial?: ( scope: ProcessInitialContext ) => Effect.Effect, InitialError, Requirements> @@ -616,15 +727,17 @@ export const makeInspectedMessage = ( event: Event, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined, - deferred?: Deferred.Deferred, unknown> + deferred?: Deferred.Deferred, unknown>, + sent: unknown = event ): AcknowledgedMessage => { const deliveryId = inspection.nextDeliveryId() const macrostepId = inspection.nextMacrostepId() + // Inspection reports the event as it was sent, before decoding. const inspected: InspectedDelivery = { deliveryId, macrostepId, source, - event, + event: sent, causedBy, complete: (delivery) => { const microsteps = InspectionRuntime.microsteps(delivery.plan) @@ -634,7 +747,7 @@ export const makeInspectedMessage = ( macrostepId, deliveryId, source, - event, + event: sent, before: { status: "active", state: delivery.before }, after: { status: "active", state: delivery.after }, handled: microsteps.some((microstep) => microstep.transitions.length > 0), @@ -829,7 +942,7 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR ...this.self, send: (event) => options.sendParent(isCurrent, event), sendInspected: (event, source, causedBy) => - isCurrent() ? sendMachineTarget(this.self, event, source, causedBy) : Effect.void, + isCurrent() ? sendEndpoint(this.self, event, source, causedBy) : Effect.void, ...(this.sendAcknowledged === undefined ? undefined : { @@ -1136,7 +1249,7 @@ export const makeChildRuntimeSync = ( } const entry = registry.children.get(id) return entry !== undefined && matchesChild(entry, child) - ? sendMachineTarget(entry.ref, event, source, causedBy) + ? deliverToChild(entry.ref, event, source, causedBy) : Effect.void }) } diff --git a/packages/effect-machine/src/internal/testing/machine/runtime.ts b/packages/effect-machine/src/internal/testing/machine/runtime.ts index a16ea31c..f34acd11 100644 --- a/packages/effect-machine/src/internal/testing/machine/runtime.ts +++ b/packages/effect-machine/src/internal/testing/machine/runtime.ts @@ -96,7 +96,7 @@ export const checkpointCommand = (label?: string): RuntimeCommand */ export type RuntimeCommandResult = | { readonly _tag: "SendAccepted" } - | { readonly _tag: "SendRejected"; readonly error: Machine.StoppedError } + | { readonly _tag: "SendRejected"; readonly error: Machine.StoppedError | Machine.MachineSchemaDecodeError } | { readonly _tag: "ClockAdvanced" } | { readonly _tag: "Stopped" } | { readonly _tag: "Checkpoint" } @@ -188,7 +188,7 @@ export interface CausalRuntimeModelStep { */ export type CausalRuntimeCommandResult = | { readonly _tag: "SendProcessed"; readonly step: ProbeStep } - | { readonly _tag: "SendRejected"; readonly error: Machine.StoppedError } + | { readonly _tag: "SendRejected"; readonly error: Machine.StoppedError | Machine.MachineSchemaDecodeError } | { readonly _tag: "ClockAdvanced" } | { readonly _tag: "Stopped" } | { readonly _tag: "Checkpoint" } @@ -712,8 +712,18 @@ const executeCausalCommand = ( switch (command._tag) { case "Send": return Effect.matchEffect(probe.sendAndAwait(command.event), { - onFailure: (error) => - error instanceof Machine.StoppedError + onFailure: (error): Effect.Effect, Error> => + // A refused event is rejected before it is sent, so the machine + // still runs; a processing failure has ended it. + error instanceof Machine.MachineSchemaDecodeError + ? probe.ref.snapshot.pipe( + Effect.flatMap((snapshot) => + snapshot.status === "active" + ? Effect.succeed({ _tag: "SendRejected", error } as const) + : Effect.fail(error as Error) + ) + ) + : error instanceof Machine.StoppedError ? probe.ref.snapshot.pipe( Effect.flatMap((snapshot) => snapshot.status === "stopped" @@ -721,7 +731,7 @@ const executeCausalCommand = ( : Effect.fail(error as Error) ) ) - : Effect.fail(error as Error), + : Effect.fail(error), onSuccess: (step) => Effect.succeed({ _tag: "SendProcessed", step } as const) }) case "Advance": diff --git a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts index b91153aa..90d14dd8 100644 --- a/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts +++ b/packages/effect-machine/src/unstable/cluster/ClusterMachine.ts @@ -817,9 +817,10 @@ export interface Target extends Machine.MachineTarget { * * An event that its schema refuses is rejected as `InvalidEvent` before it is * sent, and the machine never sees it. A request that the machine rejects fails - * with the same {@link Rejected}, carrying its reason. A local machine instead - * fails when it is sent an event that its schema refuses, because a local - * `send` does not wait for the step. + * with the same {@link Rejected}, carrying its reason. A transition that throws + * is such a rejection, because the client waits for the step: by the rule that + * `Machine.MachineRef` states for `send`, the error goes to the sender, and the + * machine goes on. * * `snapshot`, `changes`, and `join` read the machine from {@link Storage}, which * is the truth, and never ask the entity. A read works from any process that diff --git a/packages/effect-machine/src/unstable/reactivity/AtomMachine.ts b/packages/effect-machine/src/unstable/reactivity/AtomMachine.ts index d9c3ba55..eb8dd290 100644 --- a/packages/effect-machine/src/unstable/reactivity/AtomMachine.ts +++ b/packages/effect-machine/src/unstable/reactivity/AtomMachine.ts @@ -98,12 +98,13 @@ export interface MachineAtom, + AsyncResult.AsyncResult, Event > @@ -289,12 +290,17 @@ export interface ChildMachineAtom, + AsyncResult.AsyncResult< + void, + StartError | ChildNotActiveError | Machine.StoppedError | Machine.MachineSchemaDecodeError + >, Machine.ChildMachine.Event > /** diff --git a/packages/effect-machine/test/conformance/differences.ts b/packages/effect-machine/test/conformance/differences.ts index 316e0fcd..75270b30 100644 --- a/packages/effect-machine/test/conformance/differences.ts +++ b/packages/effect-machine/test/conformance/differences.ts @@ -27,9 +27,9 @@ const rejectsTheEvent = { hosts: cluster, because: "The sender waits for a reply, so the step is rolled back and the sender is told.", documentedIn: { - file: clusterDocs, - text: "Rejected Cluster machine request. Transaction-participating durable storage leaves the previous " + - "checkpoint in place and suppresses emitted events." + file: "src/Machine.ts", + text: "A transition that throws follows one rule on every host: the error goes to the sender when one waits for " + + "the event to be processed, and otherwise the machine fails with it." } } as const @@ -44,9 +44,6 @@ const rejected = (scenario: string): Difference => ({ } }) -const step = ["Machine.toStep"] -const machineDocs = "src/Machine.ts" - const resumesAWait = { kind: "Deliberate", hosts: cluster, @@ -185,36 +182,5 @@ export const differences: ReadonlyArray = [ restart: { happens: [], outcome: failed("Error: broken") }, "load succeeds": { happens: [] } } - }, - { - kind: "Deliberate", - hosts: cluster, - scenario: "refuses the payload of an event that its schema refuses", - differs: "The client rejects the event before it sends it, and the machine goes on.", - because: "The sender waits for a reply, so it is told, and the machine never sees the event.", - documentedIn: { - file: clusterDocs, - text: "An event that its schema refuses is rejected as `InvalidEvent` before it is sent, and the machine never " + - "sees it." - }, - steps: { - "an invalid payload": { answers: ["Rejected"], outcome: running }, - "an event after it": { answers: ["Accepted"], happens: [{ Count: { length: 5 } }] } - } - }, - { - kind: "Deliberate", - hosts: step, - scenario: "refuses the payload of an event that its schema refuses", - differs: "Rejects the event and keeps the machine, instead of failing it.", - because: "The caller of a step holds the state it stepped from, so a refused event leaves it as it was.", - documentedIn: { - file: machineDocs, - text: "`send` rejects an event that does not match its schema, and keeps the machine." - }, - steps: { - "an invalid payload": { answers: ["Rejected"], outcome: running }, - "an event after it": { answers: ["Accepted"], happens: [{ Count: { length: 5 } }] } - } } ] diff --git a/packages/effect-machine/test/conformance/matrix.txt b/packages/effect-machine/test/conformance/matrix.txt index a7545139..a7818a90 100644 --- a/packages/effect-machine/test/conformance/matrix.txt +++ b/packages/effect-machine/test/conformance/matrix.txt @@ -16,7 +16,7 @@ plans raised events in the step that raises them, in order emits the events of every kind of transition, in order | runs | runs | runs | runs | runs ends in a final state with its output, and takes no event after it | runs | runs | runs | differs | runs ends at once when its initial state is final | runs | runs | runs | differs | runs -refuses the payload of an event that its schema refuses | runs | runs | runs | differs | differs +refuses the payload of an event that its schema refuses | runs | runs | runs | runs | runs a transition throws | runs | runs | runs | differs | runs a step never settles | runs | runs | runs | differs | runs a transition leads to a state that its schema refuses | runs | runs | runs | differs | runs diff --git a/packages/effect-machine/test/conformance/scenarios/transitions.ts b/packages/effect-machine/test/conformance/scenarios/transitions.ts index 4acee91f..20354c02 100644 --- a/packages/effect-machine/test/conformance/scenarios/transitions.ts +++ b/packages/effect-machine/test/conformance/scenarios/transitions.ts @@ -848,13 +848,8 @@ const eventPayload: Scenario = { start: { happens: [{ Count: { length: 0 } }] }, steps: [ named("a valid payload", send({ _tag: "Set", value: "ok" }, { happens: [{ Count: { length: 2 } }] })), - named( - "an invalid payload", - send({ _tag: "Set", value: "" }, { - outcome: failed("MachineSchemaDecodeError: {\"boundary\":\"event\",\"event\":\"Set\"}") - }) - ), - named("an event after it", send({ _tag: "Set", value: "later" }, { answers: ["Ended"] })) + named("an invalid payload", send({ _tag: "Set", value: "" }, { answers: ["Rejected"] })), + named("an event after it", send({ _tag: "Set", value: "later" }, { happens: [{ Count: { length: 5 } }] })) ] } diff --git a/packages/effect-machine/test/conformance/support/hosts/atom.ts b/packages/effect-machine/test/conformance/support/hosts/atom.ts index 06bdb769..e701f064 100644 --- a/packages/effect-machine/test/conformance/support/hosts/atom.ts +++ b/packages/effect-machine/test/conformance/support/hosts/atom.ts @@ -74,7 +74,7 @@ export const atomHost: Host = { registry.set(bridge.send, event) return Effect.map( Effect.exit(AtomRegistry.getResult(registry, bridge.send, { suspendOnWaiting: true })), - (exit): Answer => answerOf(exit as Exit.Exit) + (exit): Answer => answerOf(exit as Exit.Exit) ) }), outcome: Effect.sync(outcome), diff --git a/packages/effect-machine/test/conformance/support/hosts/local.ts b/packages/effect-machine/test/conformance/support/hosts/local.ts index d8a7557a..9f414fdc 100644 --- a/packages/effect-machine/test/conformance/support/hosts/local.ts +++ b/packages/effect-machine/test/conformance/support/hosts/local.ts @@ -1,4 +1,4 @@ -import { Effect, Exit, Fiber, Scope, Stream } from "effect" +import { Effect, Exit, Fiber, Option, Scope, Stream } from "effect" import { Machine } from "../../../../src/index.js" import type { Answer, Capabilities, Host, Outcome } from "../host.js" import { decode, encode, fiberScheduling, renderFailure } from "../host.js" @@ -14,7 +14,7 @@ export const capabilities: Capabilities = { restart: true, stop: true, emissions: true, - rejection: false, + rejection: true, initialState: "AtStart" } @@ -31,9 +31,21 @@ export const outcomeOf = (snapshot: Machine.RuntimeSnapshot): Answer => - Exit.isSuccess(exit) ? "Accepted" : "Ended" +/** + * `send` of a local machine rejects an event that its schema refuses, and + * fails for a machine that has ended. A machine atom whose start failed + * fails its writes with that failure, which can refuse a state instead. + */ +export const answerOf = ( + exit: Exit.Exit +): Answer => + Exit.isSuccess(exit) + ? "Accepted" + : Exit.findErrorOption(exit).pipe( + Option.exists((error) => error._tag === "MachineSchemaDecodeError" && error.boundary === "event") + ) + ? "Rejected" + : "Ended" /** * A host over the references of `LocalMachine`. It restarts from the encoded diff --git a/packages/effect-machine/test/conformance/support/hosts/step.ts b/packages/effect-machine/test/conformance/support/hosts/step.ts index 960ee141..ba05eac7 100644 --- a/packages/effect-machine/test/conformance/support/hosts/step.ts +++ b/packages/effect-machine/test/conformance/support/hosts/step.ts @@ -198,7 +198,7 @@ export const stepHost: Host = { const refOf = ( id: string, sessionId: string, - send: (event: unknown) => Effect.Effect, + send: (event: unknown) => Effect.Effect, stop: Effect.Effect, snapshot: () => unknown, done: Deferred.Deferred @@ -339,14 +339,16 @@ export const stepHost: Host = { id: owner.self.id, sessionId: owner.self.sessionId, stop: notOffered("stop of an owner by its process logic"), - send: (event) => !stopped && owned.current() ? owner.self.send(event) : Effect.void + send: (event) => !stopped && owned.current() ? Effect.orDie(owner.self.send(event)) : Effect.void } const initialContext: Machine.Logic.InitialContext = { self: endpoint, parent, spawn: () => notOffered("children of process logic"), - sendTo: (target: Machine.MachineTarget | string, event: unknown) => - typeof target === "string" ? notOffered("children of process logic") : target.send(event), + sendTo: ((target: Machine.MachineTarget | string, event: unknown) => + typeof target === "string" + ? notOffered("children of process logic") + : target.send(event)) as Machine.Logic.InitialContext["sendTo"], stopChild: () => notOffered("children of process logic") } const setState = (next: unknown) => diff --git a/packages/effect-machine/test/internal/machine/invocationHost.test.ts b/packages/effect-machine/test/internal/machine/invocationHost.test.ts index 3df84e34..f5ab7239 100644 --- a/packages/effect-machine/test/internal/machine/invocationHost.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationHost.test.ts @@ -1,5 +1,5 @@ import { assert, describe, it } from "@effect/vitest" -import { Duration, Effect, Exit, Schema, Stream } from "effect" +import { Duration, Effect, Schema, Stream } from "effect" import { Machine } from "../../../src/index.js" import * as Configuration from "../../../src/internal/machine/configuration.js" import * as InvocationChanges from "../../../src/internal/machine/invocationChanges.js" diff --git a/packages/effect-machine/test/internal/machine/invocationStart.test.ts b/packages/effect-machine/test/internal/machine/invocationStart.test.ts index 13bbb52d..0bdf9172 100644 --- a/packages/effect-machine/test/internal/machine/invocationStart.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationStart.test.ts @@ -36,8 +36,6 @@ const makeMachine = (steps: Array, duration: (seconds: number) => Durati } }) -const status = (ref: Machine.MachineRef) => Effect.runSync(ref.snapshot).status - describe("local timer invocations", () => { for (const strategy of ["generic", "compiled"] as const) { describe(`${strategy} runtime`, () => { diff --git a/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts b/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts index a56163ae..3da97b37 100644 --- a/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts +++ b/packages/effect-machine/test/internal/machine/strategyDifferential.test.ts @@ -813,11 +813,14 @@ describe("machine planner and runtime strategies", () => { assert.strictEqual(snapshot.state.state.value.value, 2, `${strategy} decoded the construction`) yield* ref.stop const invalidRef = yield* openWithRuntimeStrategy(machine, strategy) - yield* invalidRef.send(events.Set({ value: "" })) - const error = yield* Effect.flip(invalidRef.join) + const error = yield* Effect.flip(invalidRef.send(events.Set({ value: "" }))) assert.instanceOf(error, Machine.MachineSchemaDecodeError) assert.strictEqual(error.boundary, "event") assert.strictEqual(error.event, "Set") + const kept = yield* invalidRef.snapshot + assert.strictEqual(kept.status, "active", `${strategy} kept the machine`) + assert.strictEqual(kept.state.state.value.value, 0) + yield* invalidRef.stop } }) as Effect.Effect) it.effect("publishes and validates emitted events in generic and compiled managed runtimes", () => diff --git a/packages/effect-machine/test/machine/Machine.test.ts b/packages/effect-machine/test/machine/Machine.test.ts index bfbde8fe..422d710a 100644 --- a/packages/effect-machine/test/machine/Machine.test.ts +++ b/packages/effect-machine/test/machine/Machine.test.ts @@ -1016,7 +1016,7 @@ describe("Machine", () => { value: { _tag: "DeferredEventState", value: "alpha" } }) })) - it.effect("reports deferred constructor failures through the running machine", () => + it.effect("rejects deferred constructor failures at send and keeps the machine", () => Effect.gen(function*() { const Event = Schema.TaggedUnion({ Submit: { value: Schema.NonEmptyString } @@ -1058,10 +1058,12 @@ describe("Machine", () => { assert.strictEqual(accessorError.event, "Submit") assert.isTrue(Cause.isCause(accessorError.cause)) const actor = yield* LocalMachine.start(machine) - const snapshot = yield* sendAndWaitForSnapshot(actor, construction!, (snapshot) => snapshot.status === "failed") - const error = yield* Effect.flip(actor.join) + const error = yield* Effect.flip(actor.send(construction!)) assertMachineSchemaDecodeError(error, "event", { event: "Submit" }) - assert.strictEqual(snapshot.status, "failed") + const sentAccessorError = yield* Effect.flip(actor.send(accessorFailure)) + assert.instanceOf(sentAccessorError, Machine.MachineSchemaDecodeError) + assert.strictEqual(sentAccessorError.boundary, "event") + assert.strictEqual((yield* actor.snapshot).status, "active") })) it.effect("plans inline Effect and timer outcomes", () => Effect.gen(function*() { @@ -1777,7 +1779,7 @@ describe("Machine", () => { }, unsafeTagged({ _tag: "NonEmptySubmit", value: "" }))) assertMachineSchemaDecodeError(canError, "event", { event: "NonEmptySubmit" }) })) - it.effect("surfaces sent event decode failures through the machine lifecycle", () => + it.effect("rejects a sent event that its schema refuses, and keeps the machine", () => Effect.gen(function*() { const states = Machine.state({ states: { NonEmptyIdle } }) const machine = Machine.make({ @@ -1798,22 +1800,11 @@ describe("Machine", () => { } }) const actor = yield* LocalMachine.start(machine) - const snapshot = yield* sendAndWaitForSnapshot( - actor, - unsafeTagged({ _tag: "NonEmptySubmit", value: "" }), - (snapshot) => snapshot.status === "failed" - ) - const error = yield* Effect.flip(actor.join) + const error = yield* Effect.flip(actor.send(unsafeTagged({ _tag: "NonEmptySubmit", value: "" }))) assertMachineSchemaDecodeError(error, "event", { event: "NonEmptySubmit" }) - assert.strictEqual(snapshot.status, "failed") - if (snapshot.status === "failed") { - const reason = snapshot.cause.reasons[0] - assert.ok(reason !== undefined) - assert.strictEqual(Cause.isFailReason(reason), true) - if (Cause.isFailReason(reason)) { - assertMachineSchemaDecodeError(reason.error, "event", { event: "NonEmptySubmit" }) - } - } + assert.strictEqual((yield* actor.snapshot).status, "active") + yield* actor.send(new NonEmptySubmit({ value: "ok" })) + assert.strictEqual((yield* actor.snapshot).status, "active") })) it.effect("decodes transition target values before accepting them", () => Effect.gen(function*() { diff --git a/packages/effect-machine/test/testing/Probe.test.ts b/packages/effect-machine/test/testing/Probe.test.ts index eb96b992..f7b36370 100644 --- a/packages/effect-machine/test/testing/Probe.test.ts +++ b/packages/effect-machine/test/testing/Probe.test.ts @@ -179,7 +179,7 @@ describe("MachineTest probe", () => { assert.strictEqual(starts, 1) yield* ref.stop })) - it.effect("reports a processing failure to the exact acknowledged send", () => + it.effect("rejects an event that its schema refuses at the acknowledged send", () => Effect.gen(function*() { const ref = yield* LocalMachine.start(machine) const probe = yield* MachineTest.probe(machine, ref) @@ -187,6 +187,24 @@ describe("MachineTest probe", () => { probe.sendAndAwait({ _tag: "Increment", amount: "invalid" } as unknown as Increment) ) assert.instanceOf(error, Machine.MachineSchemaDecodeError) + assert.strictEqual(error.boundary, "event") + const snapshot = yield* ref.snapshot + assert.strictEqual(snapshot.status, "active") + })) + it.effect("reports a processing failure to the exact acknowledged send", () => + Effect.gen(function*() { + const corrupting = Machine.make({ + root: states, + events: Machine.eventsFromSchemas(Increment) + }).handle({ + initial: { target: "Counter", decoded: true, data: new Counter({ count: 0 }) }, + states: { Counter: { on: { Increment: { target: "Counter", data: () => ({ count: "invalid" as never }) } } } } + }) + const ref = yield* LocalMachine.start(corrupting) + const probe = yield* MachineTest.probe(corrupting, ref) + const error = yield* Effect.flip(probe.sendAndAwait(new Increment({ amount: 1 }))) + assert.instanceOf(error, Machine.MachineSchemaDecodeError) + assert.strictEqual(error.boundary, "state") const snapshot = yield* ref.snapshot assert.strictEqual(snapshot.status, "failed") })) diff --git a/packages/effect-machine/test/testing/Runtime.test.ts b/packages/effect-machine/test/testing/Runtime.test.ts index 6f637c74..825c7590 100644 --- a/packages/effect-machine/test/testing/Runtime.test.ts +++ b/packages/effect-machine/test/testing/Runtime.test.ts @@ -800,22 +800,33 @@ describe("MachineTest causal runtime commands", () => { })) it.effect("attributes processing failures to the exact causal command and prefix", () => Effect.gen(function*() { - const ref = yield* LocalMachine.start(causalMachine) - const probe = yield* MachineTest.probe(causalMachine, ref) + // The second Add leaves a state that its schema refuses, which fails the + // machine while it processes the command. + const corrupting = Machine.make({ + root: CounterStates, + events: Machine.eventsFromSchemas(Add) + }).handle({ + initial: { target: "Counter", decoded: true, data: new Counter({ count: 0 }) }, + states: { + Counter: { + on: { + Add: { + target: "Counter", + data: ({ event, state }) => ({ count: event.amount === 2 ? "invalid" as never : state.count + 1 }) + } + } + } + } + }) + const ref = yield* LocalMachine.start(corrupting) + const probe = yield* MachineTest.probe(corrupting, ref) const commands = [ MachineTest.sendCommand(new Add({ amount: 1 })), - MachineTest.sendCommand({ _tag: "Add", amount: "invalid" } as unknown as Add) + MachineTest.sendCommand(new Add({ amount: 2 })) ] const failure = yield* MachineTest.runCausalCommands(probe, commands, { initialModel: 0, - transition: (count, command) => - Effect.succeed({ - model: count + (command._tag === "Send" && command.event._tag === "Add" && - typeof command.event.amount === "number" - ? command.event.amount - : 0), - expected: undefined - }), + transition: (count) => Effect.succeed({ model: count + 1, expected: undefined }), assert: () => Effect.void }).pipe(Effect.flip) assert.strictEqual(failure.phase, "execution") @@ -832,6 +843,31 @@ describe("MachineTest causal runtime commands", () => { const snapshot = yield* ref.snapshot assert.strictEqual(snapshot.status, "failed") })) + it.effect("records an event that its schema refuses as a rejected causal send", () => + Effect.gen(function*() { + const ref = yield* LocalMachine.start(causalMachine) + const probe = yield* MachineTest.probe(causalMachine, ref) + const transcript = yield* MachineTest.runCausalCommands(probe, [ + MachineTest.sendCommand({ _tag: "Add", amount: "invalid" } as unknown as Add), + MachineTest.sendCommand(new Add({ amount: 1 })) + ], { + initialModel: 0, + transition: (count, command) => + Effect.succeed({ + model: count + + (command._tag === "Send" && command.event._tag === "Add" && typeof command.event.amount === "number" + ? 1 + : 0), + expected: undefined + }), + assert: () => Effect.void + }) + const rejected = transcript.records[0]?.actual.result + assert.strictEqual(rejected?._tag, "SendRejected") + if (rejected?._tag === "SendRejected") assert.instanceOf(rejected.error, Machine.MachineSchemaDecodeError) + assert.strictEqual(transcript.records[1]?.actual.result._tag, "SendProcessed") + assert.strictEqual((yield* ref.snapshot).status, "active") + })) it.effect("does not confuse a processing StoppedError with mailbox rejection", () => Effect.gen(function*() { const ref = yield* LocalMachine.start(causalMachine) diff --git a/packages/effect-machine/typetest/machine/MachineStep.tst.ts b/packages/effect-machine/typetest/machine/MachineStep.tst.ts index d21f8c03..f7d60322 100644 --- a/packages/effect-machine/typetest/machine/MachineStep.tst.ts +++ b/packages/effect-machine/typetest/machine/MachineStep.tst.ts @@ -88,7 +88,7 @@ describe("Machine.toStep", () => { () => Exit.Exit> >() expect["duration"]>().type.toBe< - () => Exit.Exit> + () => Exit.Exit >() expect["effect"]>().type.toBe< () => Exit.Exit> diff --git a/packages/effect-machine/typetest/machine/Readiness.tst.ts b/packages/effect-machine/typetest/machine/Readiness.tst.ts index 4cc6422d..05b0e3e1 100644 --- a/packages/effect-machine/typetest/machine/Readiness.tst.ts +++ b/packages/effect-machine/typetest/machine/Readiness.tst.ts @@ -281,10 +281,14 @@ describe("executable machine readiness", () => { expect(makeBoundAtom).type.toBeCallableWith() expect["next"]>().type.toBe>() expect["send"]>().type.toBe< - (event: Machine.Machine.EventInput) => Effect.Effect + ( + event: Machine.Machine.EventInput + ) => Effect.Effect >() expect["send"]>().type.toBe< - (event: Machine.Machine.EventInput) => Effect.Effect + ( + event: Machine.Machine.EventInput + ) => Effect.Effect >() expect>().type.toBe>() expect>().type.toBe< From 16c4a84ecf3c1ae23a283eca8270652ae4b3618d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:10:17 +0000 Subject: [PATCH 03/11] Keep the endpoint of a compiled process free of closures The endpoint delivers through prototype methods, the event decoder is shared per machine, and logic that neither decodes nor is inspected offers directly, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/process.ts | 15 ++++- .../src/internal/machine/runtimeCompiled.ts | 57 +++++++++++------- .../src/internal/machine/runtimeGeneric.ts | 58 +++++++++---------- .../src/internal/machine/runtimeProtocol.ts | 12 ++-- 4 files changed, 85 insertions(+), 57 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/process.ts b/packages/effect-machine/src/internal/machine/process.ts index 0f12b8c6..e1ec92b5 100644 --- a/packages/effect-machine/src/internal/machine/process.ts +++ b/packages/effect-machine/src/internal/machine/process.ts @@ -421,6 +421,19 @@ const initialResult = ( ? { state: planned.state, done: true, output: planned.output } : { state: planned.state, done: false, output: undefined } +const eventDecoders = new WeakMap() + +// One decoder per machine, so a started process holds no closure of its own +// for it. An invocation event is the runtime's own and is not decoded. +const eventDecoderOf = (machine: Machine.Any): internalRuntimeProtocol.EventDecoder => { + let decoder = eventDecoders.get(machine) + if (decoder === undefined) { + decoder = (event) => InvocationEvent.isInvocationEvent(event) ? event : decodeEventSync(machine, event) + eventDecoders.set(machine, decoder) + } + return decoder +} + // Process logic executes erased machine definitions. The public `LocalMachine` // module owns the typed contract that specializes this boundary. const makeProcessLogic = ( @@ -485,7 +498,7 @@ const makeProcessLogic = ( execution: { _tag: "Compiled", childless: !hasInvokes, - decodeEvent: (event) => InvocationEvent.isInvocationEvent(event) ? event : decodeEventSync(machine, event), + decodeEvent: eventDecoderOf(machine), ...(entry._tag === "Initial" ? { initial: makeInitial } : {}), ...(makeCompiledInitial === undefined ? {} : { initialSync: makeCompiledInitial }), drain: hasInvokes diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 8c6cc10c..5d3b2ea3 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -76,6 +76,36 @@ type CompiledCompletion = type CompiledLifecycle = "Active" | "TerminationRequested" | "Completed" type CompiledRunState = "Initializing" | "Idle" | "Draining" +/** + * The endpoint of a compiled process: what its work, its children and its + * parent send to. It delivers, so a refused event fails the machine when it is + * planned. `send` and `sendInspected` live on the prototype, so an endpoint + * costs no closure; an endpoint copied by spreading keeps only its fields and + * replaces both. + */ +class CompiledAddress implements ProcessEndpoint { + readonly id: string + readonly sessionId: string + declare readonly inspectionSubject?: Inspection.Subject + constructor(private readonly process: CompiledProcess, readonly stop: Effect.Effect) { + this.id = process.id + this.sessionId = process.sessionId + if (process.inspectionSubject !== undefined) { + ;(this as { inspectionSubject?: Inspection.Subject }).inspectionSubject = process.inspectionSubject + } + } + send(event: unknown): Effect.Effect { + return this.process.deliver(event, undefined, undefined) + } + sendInspected( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { + return this.process.deliver(event, source, causedBy) + } +} + /** * Compact runtime for compiled statecharts. * @@ -127,7 +157,7 @@ class CompiledProcess implements MachineRef { index: 0, closed: false } - private readonly address: ProcessEndpoint + private readonly address: CompiledAddress private childRuntime: ChildRuntime = childlessRuntime private processScope!: ProcessInitialContext private processContext: ProcessRunContext | undefined @@ -173,24 +203,7 @@ class CompiledProcess implements MachineRef { } this.externalEmissions = options.emissions this.send = (event) => this.sendPublic(event) - // The endpoint is what the work, the children and the parent of this - // machine send to: it delivers, so a refused event fails this machine. - this.address = { - id: this.id, - sessionId, - stop: Effect.suspend(() => this.stopFromProcess()), - send: (event) => this.deliver(event, undefined, undefined), - ...(inspector === undefined - ? undefined - : { - inspectionSubject: this.inspectionSubject!, - sendInspected: ( - event: unknown, - source: Inspection.Subject | undefined, - causedBy: Inspection.Causation | undefined - ) => this.deliver(event, source, causedBy) - }) - } + this.address = new CompiledAddress(this, Effect.suspend(() => this.stopFromProcess())) } private get inspector(): InspectionRuntime.Runtime | undefined { @@ -272,7 +285,7 @@ class CompiledProcess implements MachineRef { const sendParent = this.options.sendParent ?? (parent === undefined ? noParentSend : this.inspector === undefined - ? parent.send + ? (event: unknown) => parent.send(event) : (event: unknown) => sendEndpoint(parent, event, this.inspectionSubject, this.causation())) this.processScope = { self: this.address, @@ -354,7 +367,7 @@ class CompiledProcess implements MachineRef { const sendParent = self.options.sendParent ?? (parent === undefined ? noParentSend : self.inspector === undefined - ? parent.send + ? (event: unknown) => parent.send(event) : (event: unknown) => sendEndpoint(parent, event, self.inspectionSubject, self.causation())) self.processScope = { self: self.address, @@ -569,7 +582,7 @@ class CompiledProcess implements MachineRef { } /** A delivery from work, a child, a parent or a command of another machine. */ - private deliver( + deliver( event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined diff --git a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts b/packages/effect-machine/src/internal/machine/runtimeGeneric.ts index 52c90f57..4124b2fb 100644 --- a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts +++ b/packages/effect-machine/src/internal/machine/runtimeGeneric.ts @@ -113,9 +113,11 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( offerProcessMailbox(mailbox, message, onAccepted) ? Effect.void : Effect.fail(new StoppedError()) ) // A machine decodes an event as it enters the mailbox; other logic takes - // its events as they are. + // its events as they are. Logic that neither decodes nor is inspected + // offers directly, without the closures below. const decodeEvent = logic.execution?._tag === "Compiled" ? logic.execution.decodeEvent : undefined - const offerEvent = ( + const direct = inspector === undefined && decodeEvent === undefined + const offerEvent = direct ? undefined! : ( event: Event, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined, @@ -137,31 +139,27 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( }) // A delivery from work, a child, a parent or a command of another machine: // a refused event fails this machine when it is planned. - const deliver = ( - event: Event, - source: Inspection.Subject | undefined, - causedBy: Inspection.Causation | undefined - ): Effect.Effect => - Effect.suspend(() => - offerEvent( - decodeEvent === undefined ? event : decodeDelivered(decodeEvent, event) as Event, - source, - causedBy, - undefined, - event + const deliver: InspectedOffer = direct + ? undefined! + : decodeEvent === undefined + ? (event, source, causedBy) => offerEvent(event, source, causedBy, undefined, event) + : (event, source, causedBy) => + Effect.suspend(() => + offerEvent(decodeDelivered(decodeEvent, event) as Event, source, causedBy, undefined, event) ) - ) - // A public `send` rejects an event that the schema refuses, and the machine - // keeps running. A machine that has ended rejects first. - const sendPublic = (event: Event): Effect.Effect => - Effect.suspend((): Effect.Effect => { - if (decodeEvent === undefined) return deliver(event, undefined, undefined) - if (mailbox.closed) return Effect.fail(new StoppedError()) - const decoded = decodeSent(decodeEvent, event) - return decoded._tag === "Rejected" - ? Effect.fail(decoded.error) - : offerEvent(decoded.event as Event, undefined, undefined, undefined, event) - }) + // A public `send` of a machine rejects an event that the schema refuses, + // and the machine keeps running. A machine that has ended rejects first. + const sendPublic: ((event: Event) => Effect.Effect) | undefined = + decodeEvent === undefined ? + undefined : + (event) => + Effect.suspend((): Effect.Effect => { + if (mailbox.closed) return Effect.fail(new StoppedError()) + const decoded = decodeSent(decodeEvent, event) + return decoded._tag === "Rejected" + ? Effect.fail(decoded.error) + : offerEvent(decoded.event as Event, undefined, undefined, undefined, event) + }) const offerInspected: InspectedOffer | undefined = inspector === undefined ? undefined : deliver const sendAcknowledged: | ((event: Event) => Effect.Effect, Error | StoppedError>) @@ -197,7 +195,9 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( ? requestStop : requestStop.pipe(Effect.andThen(Effect.never)) ), - send: (event) => deliver(event, undefined, undefined), + send: direct + ? (event) => offerDirect(event) + : (event) => deliver(event, undefined, undefined), ...(inspector === undefined ? undefined : { inspectionSubject: subject!, sendInspected: offerInspected! }) @@ -758,8 +758,8 @@ export const startGenericInternal: StartProcess = Effect.fnUntraced( emissions: emissions.stream as Stream.Stream, join: Deferred.await(done), stop, - send: sendPublic, - [deliverEvent]: deliver as Deliverable[typeof deliverEvent], + send: sendPublic ?? self.send, + ...(decodeEvent === undefined ? undefined : { [deliverEvent]: deliver as Deliverable[typeof deliverEvent] }), ...(sendAcknowledged === undefined ? undefined : { [acknowledgedSend]: (event: Event) => Effect.suspend( diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 0d67f697..5ea8f872 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -303,17 +303,19 @@ export const sendEndpoint = ( ): Effect.Effect => endpoint.sendInspected === undefined ? endpoint.send(event) : endpoint.sendInspected(event, source, causedBy) -/** Delivers to a child, which this runtime started and which always delivers. */ +/** + * Delivers to a child, which this runtime started: a machine takes the + * delivery, and other logic decodes nothing, so its `send` rejects nothing. + */ const deliverToChild = ( ref: MachineRef, event: unknown, source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined -): Effect.Effect => { - return ref[deliverEvent] === undefined - ? Effect.die(new Error("A child of a local machine cannot take deliveries")) +): Effect.Effect => + ref[deliverEvent] === undefined + ? sendMachineTarget(ref, event, source, causedBy) as Effect.Effect : ref[deliverEvent](event, source, causedBy) -} export interface ProcessInitialContext { readonly self: ProcessEndpoint From 764e98decd17dc0b4d1835f5125d3988a5edf04f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:18:49 +0000 Subject: [PATCH 04/11] Decode a sent event inline, without allocating Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/runtimeCompiled.ts | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 5d3b2ea3..db7e9a05 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -13,7 +13,7 @@ import * as Stream from "effect/Stream" import type * as Take from "effect/Take" import type { Inspection } from "../../LocalMachine.js" import { type ChildSelector } from "./childRegistry.js" -import { type MachineSchemaDecodeError, StoppedError } from "./errors.js" +import { MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" import { classifyOutcome } from "./observation.js" import { @@ -56,6 +56,7 @@ import { type ProcessRunContext, type ProcessRuntime, publishInspectedSent, + RefusedEvent, type RuntimeSnapshot, sendEndpoint, sendMachineTarget, @@ -202,7 +203,9 @@ class CompiledProcess implements MachineRef { if (options.programInvocation !== undefined) this.programInvocation = { ...options.programInvocation, sessionId } } this.externalEmissions = options.emissions - this.send = (event) => this.sendPublic(event) + this.send = inspector === undefined + ? (event) => this.offerMessage(event, "Sent") + : (event) => this.sendPublic(event) this.address = new CompiledAddress(this, Effect.suspend(() => this.stopFromProcess())) } @@ -653,12 +656,15 @@ class CompiledProcess implements MachineRef { return Effect.fail(new StoppedError()) } let message = offered - if (decoding === "Sent") { - const decoded = decodeSent(this.execution.decodeEvent, offered) - if (decoded._tag === "Rejected") return Effect.fail(decoded.error) - message = decoded.event - } else if (decoding === "Delivered") { - message = decodeDelivered(this.execution.decodeEvent, offered) + const decode = this.execution.decodeEvent + if (decoding !== "Decoded" && decode !== undefined) { + // Decoded inline, so a send allocates nothing more than before. + try { + message = decode(offered) + } catch (error) { + if (decoding === "Sent" && error instanceof MachineSchemaDecodeError) return Effect.fail(error) + message = new RefusedEvent(error) + } } const inspector = this.inspector const subject = this.inspectionSubject From f092901d0fc8c6eff053c46481d20d7668247a0c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 08:59:40 +0000 Subject: [PATCH 05/11] Run machines of LocalMachine on their owned step, as one driver of the compiled process A machine of LocalMachine runs as a compiled process whose drain takes each message to its owned step. Work runs through the child registry of the process, and its outcomes come back through the mailbox. The generic loop over machines is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/process.ts | 746 ++---------------- .../src/internal/machine/runtimeCompiled.ts | 7 +- .../src/internal/machine/runtimeProtocol.ts | 35 +- .../src/internal/machine/step.ts | 556 +++++++++---- .../src/internal/machine/stepHost.ts | 590 ++++++++++++++ 5 files changed, 1088 insertions(+), 846 deletions(-) create mode 100644 packages/effect-machine/src/internal/machine/stepHost.ts diff --git a/packages/effect-machine/src/internal/machine/process.ts b/packages/effect-machine/src/internal/machine/process.ts index e1ec92b5..3046eab8 100644 --- a/packages/effect-machine/src/internal/machine/process.ts +++ b/packages/effect-machine/src/internal/machine/process.ts @@ -5,73 +5,12 @@ */ import * as Effect from "effect/Effect" -import * as Option from "effect/Option" import type { Machine } from "../../Machine.js" -import * as CommandRuntime from "./commandRuntime.js" -import * as Configuration from "./configuration.js" -import { failPlanning, toStartupFailure } from "./errors.js" -import * as ExecutionPlan from "./executionPlan.js" import { type CapturedStateConfig, toImpl } from "./implementation.js" -import * as Invocation from "./invocation.js" -import * as InvocationChanges from "./invocationChanges.js" -import * as InvocationEvent from "./invocationEvent.js" -import * as internalPlanner from "./planner.js" import { decodeEventSync } from "./protocol.js" import * as ProcessRuntime from "./runtime.js" import * as internalRuntimeProtocol from "./runtimeProtocol.js" -import * as Serialization from "./serialization.js" - -type ProcessEntry = - | { - readonly _tag: "Initial" - readonly args: ReadonlyArray - } - | { - readonly _tag: "Resume" - readonly snapshot: Machine.Snapshot - } - -const runSequentialDiscard = ( - effects: ReadonlyArray> -): Effect.Effect => - effects.length === 0 - ? Effect.void - : effects.length === 1 - ? effects[0]! - : Effect.all(effects, { discard: true }) - -const acknowledgedPlan = ( - planned: { - readonly event: unknown - readonly next: unknown - readonly commands: ReadonlyArray - readonly emittedEvents: ReadonlyArray - readonly microsteps: ReadonlyArray<{ - readonly next: unknown - readonly event: unknown - readonly transitions?: ReadonlyArray - readonly commands: ReadonlyArray - readonly raisedEvents: ReadonlyArray - readonly emittedEvents: ReadonlyArray - readonly exitPaths: ReadonlyArray - readonly entryPaths: ReadonlyArray - readonly changed: boolean - }> - readonly done: boolean - readonly output: unknown - }, - snapshot: (state: unknown) => unknown -): unknown => ({ - event: planned.event, - next: snapshot(planned.next), - commands: planned.commands, - emittedEvents: planned.emittedEvents, - microsteps: planned.microsteps.map((microstep) => { - return { ...microstep, transitions: microstep.transitions ?? [], next: snapshot(microstep.next) } - }), - done: planned.done, - output: planned.output -}) +import * as StepHost from "./stepHost.js" const invokeCapabilityCache = new WeakMap() @@ -87,649 +26,42 @@ const hasInvokeCapability = (machine: Machine.Any): boolean => { return hasInvokes } -const noQueuedMessages = Effect.succeed(Option.none()) - -const makeChildlessCompiledDrain = ( - machine: Machine.Any, - checkInitialFinal: boolean -): Pick, "run" | "runSync"> => { - type Context = internalRuntimeProtocol.CompiledProcessContext - const executionPlan = ExecutionPlan.compileExecutionPlan(machine) - const liveRuntimes = new WeakMap() - const liveRuntime = (context: Context): CommandRuntime.LiveRuntime => { - let runtime = liveRuntimes.get(context.scope) - if (runtime === undefined) { - runtime = CommandRuntime.makeLiveRuntime(machine, context.scope) - liveRuntimes.set(context.scope, runtime) - } - return runtime - } - const initialOutput = (context: Context): Effect.Effect, any, any> | undefined => { - if (!checkInitialFinal) return undefined - const current = context.state() - return internalPlanner.isFinalState(machine, current) - ? internalPlanner.getFinalOutputEffect(machine, current, internalPlanner.InitialEvent).pipe( - Effect.map(Option.some) - ) - : undefined - } - const loop = (context: Context): Effect.Effect, any, any> => - Effect.suspend(() => drainSync(context) ?? noQueuedMessages) - - // Runs the effectful work of one planned message, then continues the drain. - const continueEffectful = ( - context: Context, - acknowledged: boolean, - before: unknown, - planned: ReturnType, - next: unknown - ): Effect.Effect, any, any> => { - const beforeCommit = planned.commands.length === 0 - ? undefined - : CommandRuntime.runCommands(planned.commands, context.scope) - const afterCommit = planned.emittedEvents.length === 0 - ? undefined - : CommandRuntime.runEmittedEvents(planned.emittedEvents, liveRuntime(context)) - const continueAfterCommit = (): Effect.Effect, any, any> => { - const continued = Effect.suspend(() => { - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next }) - } - return planned.done ? Effect.succeed(Option.some(planned.output)) : loop(context) - }) - return afterCommit === undefined ? continued : afterCommit.pipe(Effect.andThen(continued)) - } - const commitAndContinue = (): Effect.Effect, any, any> => { - const notification = context.commit(next) - const continued = continueAfterCommit() - const effect = notification === undefined ? continued : notification.pipe(Effect.andThen(continued)) - return notification === undefined && afterCommit === undefined - ? effect - : context.runAfterChanges(effect) - } - return beforeCommit === undefined - ? commitAndContinue() - : context.runAfterChanges(beforeCommit.pipe(Effect.andThen(Effect.suspend(commitAndContinue)))) - } - - // Commits queued messages whose transitions need no effectful work. Returns - // the drain continuing from the first message that does, or `undefined` - // once the mailbox is empty. Only this drain commits a childless machine's - // state, so the compact execution state stays valid in the process context - // while the machine is idle and the next send does not re-derive it. - const drainSync = ( - context: Context, - first?: internalRuntimeProtocol.ProcessMessage - ): Effect.Effect, any, any> | undefined => { - let delivered = first - while (true) { - let message: internalRuntimeProtocol.ProcessMessage - if (delivered !== undefined) { - message = delivered - delivered = undefined - context.beginMessage(message) - } else { - const pending = context.pollMessage() - if (Option.isNone(pending)) { - return undefined - } - message = pending.value - } - - const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) - const event = acknowledged ? message.event : message - const before = context.state() - - let planned - if (event instanceof internalRuntimeProtocol.RefusedEvent) return failPlanning(event.error) - try { - planned = executionPlan.planDecoded( - context.executionState ?? - executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, before)), - event, - // The drain owns its execution state, and builds the acknowledged - // plan from what it retained before it plans the next message. - "Owned", - acknowledged, - context.scope - ) - } catch (error) { - return failPlanning(error) - } - context.executionState = planned.next - if (planned.microsteps.length === 0) { - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: before }) - } - continue - } - - const next = executionPlan.snapshot(planned.next) - if (planned.commands.length > 0 || planned.emittedEvents.length > 0 || planned.done) { - return continueEffectful(context, acknowledged, before, planned, next) - } - const notification = context.commit(next) - if (notification !== undefined) { - return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => { - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next }) - } - return loop(context) - })))) - } - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next }) - } - } - } - - return { - run: (context) => - internalRuntimeProtocol.provideMachineRuntime(initialOutput(context) ?? loop(context), context.scope), - runSync: (context, message) => { - // A machine resumed in a final state reports its output instead; the - // message stays in flight, so termination settles it as stopped. - const output = initialOutput(context) - if (output !== undefined) { - context.beginMessage(message) - } - const remaining = output ?? drainSync(context, message) - return remaining === undefined - ? undefined - : internalRuntimeProtocol.provideMachineRuntime(remaining, context.scope) - } - } -} - -class InvokeExecutionState { - initialized = false - initial: - | { - readonly configuration: unknown - readonly activeConfiguration: Configuration.ActiveConfiguration - readonly entryPaths: ReadonlyArray - } - | undefined - - constructor(initial?: { - readonly configuration: unknown - readonly activeConfiguration: Configuration.ActiveConfiguration - readonly entryPaths: ReadonlyArray - }) { - this.initial = initial - } -} - -const makeInvokingCompiledDrain = ( - machine: Machine.Any, - checkInitialFinal: boolean -): ( - context: internalRuntimeProtocol.CompiledProcessContext -) => Effect.Effect, any, any> => { - const executionPlan = ExecutionPlan.compileExecutionPlan(machine) - return (context) => { - let current = context.state() - if (checkInitialFinal && internalPlanner.isFinalState(machine, current)) { - return internalPlanner.getFinalOutputEffect( - machine, - current, - internalPlanner.InitialEvent - ).pipe(Effect.map(Option.some)) - } - - const scope = context.scope - const stored = context.executionState - const execution = stored instanceof InvokeExecutionState - ? stored - : new InvokeExecutionState() - context.executionState = execution - let liveRuntime: CommandRuntime.LiveRuntime | undefined - let configuration: unknown - - let loop: Effect.Effect, any, any> - loop = Effect.suspend(() => { - const pending = context.pollMessage() - if (Option.isNone(pending)) { - configuration = undefined - return Effect.succeed(Option.none()) - } - - const message = pending.value - const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) - const event = acknowledged ? message.event : message - const before = current - - let planned - if (event instanceof internalRuntimeProtocol.RefusedEvent) return failPlanning(event.error) - try { - planned = executionPlan.planDecoded( - configuration ?? - executionPlan.fromConfiguration(Configuration.normalizeConfigurationSync(machine, current)), - event, - "Owned", - acknowledged, - scope - ) - } catch (error) { - return failPlanning(error) - } - configuration = planned.next - if (planned.microsteps.length === 0) { - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: current }) - } - return loop - } - - const changes = InvocationChanges.fromMicrosteps(planned.microsteps) - const activeConfiguration = executionPlan.toConfiguration(planned.next) - const next = executionPlan.snapshot(planned.next) - const beforeCommit: Array> = [] - if (planned.commands.length > 0) { - beforeCommit.push(CommandRuntime.runCommands(planned.commands, scope)) - } - if (changes !== undefined) { - const stopping = context.ownedChildren.stopPaths(changes.exited) - if (stopping !== undefined) beforeCommit.push(stopping) - } - const afterCommit: Array> = [] - if (planned.emittedEvents.length > 0) { - afterCommit.push( - CommandRuntime.runEmittedEvents( - planned.emittedEvents, - liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, scope) - ) - ) - } - if (planned.done) { - afterCommit.push(context.ownedChildren.stopAll()) - } else if (changes !== undefined) { - for (const [path, entryEvent] of changes.entered) { - const starting = Invocation.startAll( - machine, - scope, - context.ownedChildren, - activeConfiguration, - [path], - entryEvent - ) - if (starting !== undefined) afterCommit.push(starting) - } - } - - const commit = (): Effect.Effect | undefined => { - const notification = context.commit(next) - current = next - return notification - } - const continueAfterCommit = (): Effect.Effect, any, any> => { - const continued = Effect.suspend(() => { - if (acknowledged) { - context.completeMessage({ before, plan: acknowledgedPlan(planned, executionPlan.snapshot), after: next }) - } - return planned.done ? Effect.succeed(Option.some(planned.output)) : loop - }) - return afterCommit.length === 0 - ? continued - : runSequentialDiscard(afterCommit).pipe(Effect.andThen(continued)) - } - const commitAndContinue = (): Effect.Effect, any, any> => { - const notification = commit() - const continued = continueAfterCommit() - const effect = notification === undefined ? continued : notification.pipe(Effect.andThen(continued)) - return notification === undefined && afterCommit.length === 0 - ? effect - : context.runAfterChanges(effect) - } - if (beforeCommit.length === 0) { - return commitAndContinue() - } - return context.runAfterChanges( - runSequentialDiscard(beforeCommit).pipe(Effect.andThen(Effect.suspend(commitAndContinue))) - ) - }) - - const initialize = (): Effect.Effect, any, any> => { - if (execution.initialized) { - return loop - } - const seeded = execution.initial - const initialConfiguration = seeded?.activeConfiguration ?? - Configuration.normalizeConfigurationSync(machine, current) - configuration = seeded?.configuration ?? executionPlan.fromConfiguration(initialConfiguration) - const starting = Invocation.startAll( - machine, - scope, - context.ownedChildren, - initialConfiguration, - seeded?.entryPaths ?? Configuration.getInitialEntryPaths(machine, initialConfiguration), - internalPlanner.InitialEvent - ) - execution.initial = undefined - execution.initialized = true - return starting === undefined ? loop : starting.pipe(Effect.andThen(loop)) - } - return internalRuntimeProtocol.provideMachineRuntime(Effect.suspend(initialize), scope) - } -} - -// Planned initial states only carry an output once the machine is done. -const initialResult = ( - planned: { readonly state: Machine.Snapshot; readonly done: boolean; readonly output: unknown } -): internalRuntimeProtocol.CompiledProcessInitial, unknown> => - planned.done - ? { state: planned.state, done: true, output: planned.output } - : { state: planned.state, done: false, output: undefined } - const eventDecoders = new WeakMap() // One decoder per machine, so a started process holds no closure of its own -// for it. An invocation event is the runtime's own and is not decoded. +// for it. What work reports is the runtime's own message and is not decoded. const eventDecoderOf = (machine: Machine.Any): internalRuntimeProtocol.EventDecoder => { let decoder = eventDecoders.get(machine) if (decoder === undefined) { - decoder = (event) => InvocationEvent.isInvocationEvent(event) ? event : decodeEventSync(machine, event) + decoder = (event) => event instanceof internalRuntimeProtocol.WorkMessage ? event : decodeEventSync(machine, event) eventDecoders.set(machine, decoder) } return decoder } +type Planner = "Compiled" | "Reference" + // Process logic executes erased machine definitions. The public `LocalMachine` // module owns the typed contract that specializes this boundary. const makeProcessLogic = ( machine: Machine.Any, - entry: ProcessEntry + entry: StepHost.Entry, + planner: Planner ): internalRuntimeProtocol.ProcessLogic => { - const hasInvokes = hasInvokeCapability(machine) - const executionPlan = ExecutionPlan.compileExecutionPlan(machine) - const initialArgs = entry._tag === "Initial" ? entry.args : [] - const compiledInitial = entry._tag === "Initial" ? executionPlan.initial : undefined - const makeCompiledInitial = compiledInitial === undefined ? undefined : ( - scope: internalRuntimeProtocol.ProcessInitialContext> - ) => { - try { - const planned = compiledInitial(initialArgs, scope) - scope.inspectInitial(planned.initialEntryPaths) - const result = initialResult(planned) - return hasInvokes - ? { - ...result, - executionState: new InvokeExecutionState({ - configuration: planned.configuration, - activeConfiguration: planned.activeConfiguration, - entryPaths: planned.initialEntryPaths - }) - } - : result - } catch (error) { - throw toStartupFailure(error) - } - } - const makeInitial = ( - scope: internalRuntimeProtocol.ProcessInitialContext> - ) => - compiledInitial === undefined - ? internalRuntimeProtocol.provideMachineRuntime( - internalPlanner.planInitial(internalPlanner.withMachineReferences(machine, scope), ...initialArgs).pipe( - Effect.flatMap((planned) => { - scope.inspectInitial(planned.initialEntryPaths, planned.microsteps) - const commands = planned.commands.length === 0 - ? undefined - : CommandRuntime.runCommands(planned.commands, scope) - const emitted = planned.emittedEvents.length === 0 - ? undefined - : CommandRuntime.runEmittedEvents( - planned.emittedEvents, - CommandRuntime.makeLiveRuntime(machine, scope) - ) - const result = Effect.succeed(initialResult(planned)) - return commands === undefined - ? emitted === undefined ? result : emitted.pipe(Effect.andThen(result)) - : emitted === undefined - ? commands.pipe(Effect.andThen(result)) - : commands.pipe(Effect.andThen(emitted), Effect.andThen(result)) - }) - ), - scope - ) - : Effect.try({ try: () => makeCompiledInitial!(scope), catch: toStartupFailure }) - return ({ + const execution = StepHost.makeExecution( + machine, + entry, + planner, + !hasInvokeCapability(machine), + eventDecoderOf(machine) + ) + return { inspection: { kind: "Machine", definition: machine }, - execution: { - _tag: "Compiled", - childless: !hasInvokes, - decodeEvent: eventDecoderOf(machine), - ...(entry._tag === "Initial" ? { initial: makeInitial } : {}), - ...(makeCompiledInitial === undefined ? {} : { initialSync: makeCompiledInitial }), - drain: hasInvokes - ? { _tag: "Owned", run: makeInvokingCompiledDrain(machine, entry._tag === "Resume") } - : { _tag: "Owned", ...makeChildlessCompiledDrain(machine, entry._tag === "Resume") } - }, - initial: (scope) => - entry._tag === "Resume" - ? internalRuntimeProtocol.provideMachineRuntime( - Serialization.normalizeSnapshotEffect(machine, entry.snapshot), - scope - ) - : makeInitial(scope).pipe(Effect.map((initialized) => initialized.state)), - run: (context) => - internalRuntimeProtocol.provideMachineRuntime( - Effect.gen(function*() { - const { completeMessage, pollMessage, receiveMessage, state, setState } = context - if (completeMessage === undefined || pollMessage === undefined || receiveMessage === undefined) { - return yield* Effect.die(new Error("Machine statechart started without acknowledged mailbox access")) - } - let terminal: { readonly output: any } | undefined - - let current = yield* state - if (internalPlanner.isFinalState(machine, current)) { - return yield* internalPlanner.getFinalOutputEffect( - machine, - current, - internalPlanner.InitialEvent - ) - } - - if (!hasInvokes) { - // A queued batch is produced entirely by this worker, so its - // configuration is already validated. Drop both caches before - // blocking again so idle machines retain only the public snapshot. - // Keeping the loop in this generator avoids a suspended generator - // per iteration; every iteration still crosses Effect boundaries, - // so the Effect scheduler remains responsible for cooperative yield. - let configuration: Configuration.ActiveConfiguration | undefined - let pendingMessage: Option.Option>> = Option - .none() - let liveRuntime: CommandRuntime.LiveRuntime | undefined - while (terminal === undefined) { - const message = Option.isSome(pendingMessage) ? pendingMessage.value : yield* receiveMessage - pendingMessage = Option.none() - const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) - const event = acknowledged ? message.event : message - const before = current - if (event instanceof internalRuntimeProtocol.RefusedEvent) return yield* failPlanning(event.error) - let planned - try { - planned = internalPlanner.planDecodedConfiguration( - machine, - Configuration.withMachineReferences( - configuration ?? Configuration.normalizeConfigurationSync(machine, current), - context - ), - event - ) - } catch (error) { - return yield* failPlanning(error) - } - configuration = planned.next - - if (planned.microsteps.length > 0) { - const next = Configuration.snapshotFromConfiguration(machine, planned.next) - yield* CommandRuntime.runCommands(planned.commands, context) - yield* setState(next) - current = next - if (planned.emittedEvents.length > 0) { - yield* CommandRuntime.runEmittedEvents( - planned.emittedEvents, - liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, context) - ) - } - - if (planned.done) { - terminal = { output: planned.output } - } - } - - if (acknowledged) { - completeMessage({ - before, - plan: acknowledgedPlan( - planned, - (state) => - Configuration.snapshotFromConfiguration(machine, state as Configuration.ActiveConfiguration) - ), - after: current - }) - } - - if (terminal === undefined) { - pendingMessage = yield* pollMessage - if (Option.isNone(pendingMessage)) { - configuration = undefined - } - } - } - - if (terminal === undefined) { - return yield* Effect.die( - new Error("Machine process stopped receiving events before reaching a terminal configuration") - ) - } - return terminal.output - } - - // The execution descriptor requests this owner-local capability only - // when an invoking statechart is deliberately run by the generic - // reference strategy. - const ownedChildren = context.ownedChildren - if (ownedChildren === undefined) { - return yield* Effect.die(new Error("Invoking statechart started without an owned child runtime")) - } - const startInvokes: ( - configuration: Configuration.ActiveConfiguration, - paths: ReadonlyArray, - event: Machine.LifecycleEvent - ) => Effect.Effect = (configuration, paths, event) => (Invocation.startAll( - machine, - context, - ownedChildren, - configuration, - paths, - event - ) ?? Effect.void) - const stopInvokes = (paths: ReadonlyArray): Effect.Effect => - ownedChildren.stopPaths(paths) ?? Effect.void - - return yield* Effect.gen(function*() { - let configuration: Configuration.ActiveConfiguration | undefined = yield* Configuration - .normalizeConfigurationEffect( - machine, - current - ) - yield* startInvokes( - configuration, - Configuration.getInitialEntryPaths(machine, configuration), - internalPlanner.InitialEvent - ) - // As above, keep the normalized configuration only while this - // worker can continue draining an already queued batch. - configuration = undefined - let pendingMessage: Option.Option>> = Option - .none() - let liveRuntime: CommandRuntime.LiveRuntime | undefined - - // Match the compact non-invoke loop while retaining state-scoped - // child lifecycle work at the same ordered Effect boundaries. - while (terminal === undefined) { - const message = Option.isSome(pendingMessage) ? pendingMessage.value : yield* receiveMessage - pendingMessage = Option.none() - const acknowledged = internalRuntimeProtocol.isAcknowledgedMessage(message) - const event = acknowledged ? message.event : message - const before = current - if (event instanceof internalRuntimeProtocol.RefusedEvent) return yield* failPlanning(event.error) - let planned - try { - planned = internalPlanner.planDecodedConfiguration( - machine, - Configuration.withMachineReferences( - configuration ?? Configuration.normalizeConfigurationSync(machine, current), - context - ), - event - ) - } catch (error) { - return yield* failPlanning(error) - } - configuration = planned.next - if (planned.microsteps.length > 0) { - const changes = InvocationChanges.fromMicrosteps(planned.microsteps) - const next = Configuration.snapshotFromConfiguration(machine, planned.next) - yield* CommandRuntime.runCommands(planned.commands, context) - if (changes !== undefined) { - yield* stopInvokes(changes.exited) - } - yield* setState(next) - current = next - if (planned.emittedEvents.length > 0) { - yield* CommandRuntime.runEmittedEvents( - planned.emittedEvents, - liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, context) - ) - } - - if (planned.done) { - terminal = { output: planned.output } - yield* ownedChildren.stopAll() - } else if (changes !== undefined) { - for (const [path, entryEvent] of changes.entered) { - yield* startInvokes(planned.next, [path], entryEvent) - } - } - } - - if (acknowledged) { - completeMessage({ - before, - plan: acknowledgedPlan( - planned, - (state) => - Configuration.snapshotFromConfiguration(machine, state as Configuration.ActiveConfiguration) - ), - after: current - }) - } - - if (terminal === undefined) { - pendingMessage = yield* pollMessage - if (Option.isNone(pendingMessage)) { - configuration = undefined - } - } - } - - if (terminal === undefined) { - return yield* Effect.die( - new Error("Machine process stopped receiving events before reaching a terminal configuration") - ) - } - return terminal.output - }).pipe( - Effect.onExit(() => ownedChildren.stopAll()) - ) - }), - context - ) - }) + execution, + initial: (scope) => execution.initial!(scope).pipe(Effect.map((initialized) => initialized.state)), + // A machine runs only on its compiled execution. + run: () => Effect.die(new Error("A machine runs on its compiled execution")) + } } const initialProcessLogicCache = new WeakMap< @@ -742,7 +74,7 @@ export const toProcessLogic = ( ...args: ReadonlyArray ): internalRuntimeProtocol.ProcessLogic => { if (args.length > 0) { - return makeProcessLogic(machine, { _tag: "Initial", args }) + return makeProcessLogic(machine, { _tag: "Initial", args }, "Compiled") } // The execution descriptor stores process-local invoke sessions by each // runtime address and evaluates initialization/services on every start. A @@ -753,7 +85,7 @@ export const toProcessLogic = ( if (cached !== undefined) { return cached as any } - const logic = makeProcessLogic(machine, { _tag: "Initial", args }) + const logic = makeProcessLogic(machine, { _tag: "Initial", args }, "Compiled") initialProcessLogicCache.set(machine, logic as any) return logic } @@ -762,13 +94,29 @@ const toResumedProcessLogic = ( machine: Machine.Any, snapshot: Machine.Snapshot ): internalRuntimeProtocol.ProcessLogic => - makeProcessLogic(machine, { _tag: "Resume", snapshot }) + makeProcessLogic(machine, { _tag: "Resume", snapshot }, "Compiled") const toChildProcessLogic: internalRuntimeProtocol.MakeChildLogic = (machine, input) => machine.input === undefined ? toProcessLogic(machine) : toProcessLogic(machine, input) const runtime = ProcessRuntime.make(toChildProcessLogic) +// The reference strategy runs a machine on the same driver as every other, +// with a step that always plans with the reference planner. +const strategyLogic = ( + machine: Machine.Any, + strategy: ProcessRuntime.ProcessRuntimeStrategy, + entry: StepHost.Entry +): internalRuntimeProtocol.ProcessLogic => + strategy === "generic" + ? makeProcessLogic(machine, entry, "Reference") + : entry._tag === "Initial" + ? toProcessLogic(machine, ...entry.args) + : toResumedProcessLogic(machine, entry.snapshot) + +const runtimeStrategy = (strategy: ProcessRuntime.ProcessRuntimeStrategy): ProcessRuntime.ProcessRuntimeStrategy => + strategy === "generic" ? "compiled" : strategy + /** @internal Test-only runtime strategy selection for a fresh machine. */ export const startWithRuntimeStrategyForTesting = ( machine: Machine.Any, @@ -776,8 +124,8 @@ export const startWithRuntimeStrategyForTesting = ( ...args: ReadonlyArray ): Effect.Effect, any, any> => runtime.startProcessWithStrategyForTesting( - toProcessLogic(machine, ...args), - strategy, + strategyLogic(machine, strategy, { _tag: "Initial", args }), + runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) @@ -788,8 +136,8 @@ export const prepareWithRuntimeStrategyForTesting = ( ...args: ReadonlyArray ): Effect.Effect, any, any> => runtime.prepareProcessWithStrategyForTesting( - toProcessLogic(machine, ...args), - strategy, + strategyLogic(machine, strategy, { _tag: "Initial", args }), + runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) @@ -800,8 +148,8 @@ export const resumeWithRuntimeStrategyForTesting = ( strategy: ProcessRuntime.ProcessRuntimeStrategy ): Effect.Effect, any, any> => runtime.startProcessWithStrategyForTesting( - toResumedProcessLogic(machine, snapshot), - strategy, + strategyLogic(machine, strategy, { _tag: "Resume", snapshot }), + runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) @@ -812,8 +160,8 @@ export const prepareResumedWithRuntimeStrategyForTesting = ( strategy: ProcessRuntime.ProcessRuntimeStrategy ): Effect.Effect, any, any> => runtime.prepareProcessWithStrategyForTesting( - toResumedProcessLogic(machine, snapshot), - strategy, + strategyLogic(machine, strategy, { _tag: "Resume", snapshot }), + runtimeStrategy(strategy), machine.id === undefined ? undefined : { id: machine.id } ) diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index db7e9a05..a7e65497 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -60,6 +60,7 @@ import { type RuntimeSnapshot, sendEndpoint, sendMachineTarget, + sentOf, snapshotObserver, type StartInternalOptions, type StartProcess, @@ -281,7 +282,7 @@ class CompiledProcess implements MachineRef { this.address, this.options.runtime, this.services, - (event) => this.sendAcknowledgedEffect(decodeDelivered(this.execution.decodeEvent, event), event) + (event) => this.sendAcknowledgedEffect(decodeDelivered(this.execution.decodeEvent, event), sentOf(event)) ) } const parent = this.options.parent @@ -363,7 +364,7 @@ class CompiledProcess implements MachineRef { self.address, self.options.runtime, self.services, - (event) => self.sendAcknowledgedEffect(decodeDelivered(self.execution.decodeEvent, event), event) + (event) => self.sendAcknowledgedEffect(decodeDelivered(self.execution.decodeEvent, event), sentOf(event)) ) } const parent = self.options.parent @@ -594,7 +595,7 @@ class CompiledProcess implements MachineRef { return this.offerMessage(event, "Delivered") as Effect.Effect } return Effect.suspend(() => - this.offerEvent(decodeDelivered(this.execution.decodeEvent, event), source, causedBy, undefined, event) + this.offerEvent(decodeDelivered(this.execution.decodeEvent, event), source, causedBy, undefined, sentOf(event)) ) } diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 5ea8f872..67951824 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -94,6 +94,27 @@ export class RefusedEvent { constructor(readonly error: unknown) {} } +/** + * What running work reports to the machine that owns it, as a message of the + * machine's mailbox, so its step takes the report in the machine's own turn: + * `Settle` ends the work with the `Exit` in `value`, `Element` delivers an + * element of a stream, and `Report` a snapshot of a child. It is never decoded. + * `sent` is the event that inspection reports for it. + * + * @internal + */ +export class WorkMessage { + constructor( + readonly _tag: "Settle" | "Element" | "Report", + readonly work: unknown, + readonly value: unknown, + readonly sent: unknown + ) {} +} + +/** The event that inspection reports for a message: what a report of work stands for, or the event. */ +export const sentOf = (event: unknown): unknown => event instanceof WorkMessage ? event.sent : event + /** * Decodes an event that enters a mailbox. An invocation event is the host's * own and is not decoded. @@ -864,6 +885,8 @@ export interface OwnedChildRuntime { readonly beginGeneration: (path: string) => InvocationEvent.Generation readonly stopAll: () => Effect.Effect readonly stopPaths: (paths: ReadonlyArray) => Effect.Effect | undefined + /** Stops the child that was spawned with `key`, while its owner holds it. */ + readonly stopKey: (key: string) => Effect.Effect } export interface ChildRuntime { @@ -1031,6 +1054,15 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR }) } + stopKey(key: string): Effect.Effect { + return Effect.suspend(() => { + for (const entry of this.registry.children.values()) { + if (entry.ownerActive && entry.ownerKey === key) return this.stopEntry(entry) + } + return Effect.void + }) + } + stopPaths(paths: ReadonlyArray): Effect.Effect | undefined { if (paths.length === 0) return undefined this.retireGenerations(paths) @@ -1117,7 +1149,8 @@ export const childlessRuntime: ChildRuntime = { // Unreachable for childless logic; `spawn` reports the defect as a failure. beginGeneration: () => ({ current: true }), stopAll: () => Effect.void, - stopPaths: () => undefined + stopPaths: () => undefined, + stopKey: () => Effect.void } } diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index 3bf827f9..a4407965 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -34,7 +34,9 @@ import * as Context from "effect/Context" import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" +import * as Equal from "effect/Equal" import * as Exit from "effect/Exit" +import * as Hash from "effect/Hash" import * as Stream from "effect/Stream" import type { ChildMachine, ChildOwner, Logic, Machine, MachineTarget } from "../../Machine.js" import { ChildMachineRuntime, MachineRuntime } from "./capability.js" @@ -198,10 +200,56 @@ interface PublishedMicrostep { readonly changed: boolean } -/** The machine of a step function, and the plan it steps with. */ -interface Planning { - readonly machine: Machine.Any - readonly plan: ExecutionPlan.CompiledExecutionPlan +/** + * The machine of a step function, the plan it steps with, and the host it runs + * on: what its transitions address, and the children its work acts on. A host + * builds one for each machine it runs, and every state of that machine carries + * it. What work needs of it is built when work first needs it, so a machine + * that invokes nothing holds only these fields. + * + * @internal + */ +export class Planning implements Configuration.PlanningMachineReferences { + #services: Context.Context | undefined + + constructor( + readonly machine: Machine.Any, + readonly plan: ExecutionPlan.CompiledExecutionPlan, + readonly self: MachineTarget, + readonly parent: MachineTarget | undefined, + /** The children of the machine, or `undefined` for a host that owns them itself. */ + children: Children | undefined, + /** + * Whether the host runs work inside the services of this machine already, + * as the local runtime runs work in processes of the machine, so work is + * not provided them again. + */ + readonly ambient = false + ) { + this.children = children ?? (this as unknown as Children) + } + + readonly children: Children + + // A host is compared by identity: hashing a state, as a failure that holds one + // may be hashed, never reads the targets of the host. + [Hash.symbol](): number { + return Hash.random(this) + } + + [Equal.symbol](that: unknown): boolean { + return this === that + } + + /** What the source and input mapper of work receive, built for each entry that resolves work. */ + get capabilities(): InvocationResolution.InvocationCapabilities { + return { self: this.self, parent: this.parent, children: childOwnerOf(this.children) } + } + + /** The services through which work acts on the children of this machine. */ + get services(): Context.Context { + return this.#services ??= servicesOf(this.children) + } } const empty: ReadonlyArray = [] @@ -212,6 +260,10 @@ const empty: ReadonlyArray = [] * runtime attaches them. The configuration and the public snapshot are built * from it on first read. * + * A state that rests holds only its snapshot, its work and its runs: its + * execution state is built again from the snapshot when a step needs it, as a + * host that keeps a machine idle does not hold it. + * * A `"Persistent"` state never changes after it is built. The `execution` of * an `"Owned"` state is written in place by the step that it is handed over to, * and so is everything read from it that was not read before. @@ -219,8 +271,9 @@ const empty: ReadonlyArray = [] * @internal */ export class State { - readonly [StateTypeId]: typeof StateTypeId = StateTypeId + declare readonly [StateTypeId]: typeof StateTypeId declare readonly [OwnershipTypeId]: O + #execution: unknown #configuration: Configuration.ActiveConfiguration | undefined #snapshot: Machine.Snapshot | undefined /** Whether an owned state was handed over to a step, which may have written it. */ @@ -228,7 +281,8 @@ export class State { constructor( readonly planning: Planning, - readonly execution: unknown, + /** The execution state of the plan, or `undefined` for a state that rests. */ + execution: unknown, configuration: Configuration.ActiveConfiguration | undefined, snapshot: Machine.Snapshot | undefined, /** The work that runs, in start order. */ @@ -237,6 +291,7 @@ export class State { readonly runs: number, readonly exit: Exit.Exit | undefined ) { + this.#execution = execution this.#configuration = configuration this.#snapshot = snapshot } @@ -245,17 +300,34 @@ export class State { return this.planning.machine } + /** The execution state of the plan. Building it again from the snapshot may throw. */ + get execution(): unknown { + return this.#execution ??= this.planning.plan.fromConfiguration(this.configuration) + } + get configuration(): Configuration.ActiveConfiguration { - return this.#configuration ??= this.planning.plan.toConfiguration(this.execution) + return this.#configuration ??= this.#execution === undefined + ? Configuration.normalizeConfigurationSync(this.planning.machine, this.#snapshot!) + : this.planning.plan.toConfiguration(this.#execution) } get snapshot(): Machine.Snapshot { - return this.#snapshot ??= this.planning.plan.snapshot(this.execution) + return this.#snapshot ??= this.planning.plan.snapshot(this.#execution) } /** This state with other running work, keeping what was read of it. */ withRunning(running: ReadonlyArray): State { - return new State(this.planning, this.execution, this.#configuration, this.#snapshot, running, this.runs, this.exit) + return new State(this.planning, this.#execution, this.#configuration, this.#snapshot, running, this.runs, this.exit) + } + + /** This state as it rests: its snapshot, its work and its runs. */ + resting(): State { + return new State(this.planning, undefined, undefined, this.snapshot, this.running, this.runs, this.exit) + } + + /** What was built of this state, without building anything. */ + get built(): { readonly execution: unknown; readonly configuration: Configuration.ActiveConfiguration | undefined } { + return { execution: this.#execution, configuration: this.#configuration } } /** @@ -336,6 +408,11 @@ export class Step { return this.state.snapshot } + /** Whether the step planned a microstep, so its state is a new one to publish. */ + get planned(): boolean { + return (this.#microsteps ?? this.#published!).length > 0 + } + get running(): ReadonlyArray { return this.state.running } @@ -377,6 +454,11 @@ export class Step { export interface MachineStep { readonly start: (...input: ReadonlyArray) => Exit.Exit, unknown> readonly send: (state: State, event: unknown) => Exit.Exit, unknown> + /** + * Plans an event that its host decoded already, as `send` does after it + * decodes. A machine that has ended takes no event: its host stops sending. + */ + readonly sendDecoded: (state: State, event: Machine.EventOf) => Step readonly settle: (state: State, work: Work, exit: Exit.Exit) => Step readonly element: (state: State, work: Work, element: unknown) => Step readonly report: (state: State, work: Work, snapshot: unknown) => Step @@ -395,9 +477,173 @@ export interface MachineStep { */ export type OwnedMachineStep = MachineStep<"Owned"> +/** + * The step functions of a machine, built once for each machine, ownership and + * planner, for every host that runs it. A state carries the {@link Planning} + * of its host, so only `start` and `resume`, which take no state, are passed + * one. + * + * @internal + */ +export interface Kernel + extends Omit, "start" | "resume" | "sendDecoded" | "settle" | "element" | "report"> +{ + readonly plan: ExecutionPlan.CompiledExecutionPlan + /** + * As in {@link MachineStep}. A host that reads no microstep of the step it + * gets passes `retain: false`, so an owned plan writes in place and keeps no + * transition; the step still lists the paths it exited and entered. + */ + readonly sendDecoded: (state: State, event: Machine.EventOf, retain?: boolean) => Step + readonly settle: (state: State, work: Work, exit: Exit.Exit, retain?: boolean) => Step + readonly element: (state: State, work: Work, element: unknown, retain?: boolean) => Step + readonly report: (state: State, work: Work, snapshot: unknown, retain?: boolean) => Step + /** + * Starts the machine with `input`. Without `retain`, a machine that the + * execution plan starts itself starts there, and its step lists no microstep. + */ + readonly start: ( + planning: Planning, + input: ReadonlyArray, + retain?: boolean + ) => Exit.Exit, unknown> + readonly resume: ( + planning: Planning, + snapshot: Machine.Snapshot, + progress?: ReadonlyArray + ) => Exit.Exit, unknown> + /** + * The state of an active machine that invokes no work, from a snapshot that + * its host published: a host that keeps only that snapshot while the machine + * is idle builds its state again with it. It throws for a machine that + * invokes work, whose work a snapshot does not hold, and for a snapshot that + * does not normalize. + */ + readonly fromSnapshot: (planning: Planning, snapshot: Machine.Snapshot) => State + /** + * The state as it rests, for a host that keeps a machine idle: its snapshot, + * its work and its runs. A later step builds its execution state again from + * the snapshot. An owned state is handed over. + */ + readonly rest: (state: State) => State +} + /** @internal */ export const isState = (value: unknown): value is State => value instanceof State +/** + * One piece of work, as a step lists it. What it describes is read from its + * invocation, and each accessor evaluates user code once and keeps its result, + * so a piece of work holds no closure of its own. Work is compared by identity. + */ +class WorkOf { + #evaluated: Exit.Exit | undefined + readonly [WorkTypeId]: InvocationResolution.ResolvedInvocation + + constructor( + invocation: InvocationResolution.ResolvedInvocation, + readonly run: number, + private readonly planning: Planning + ) { + this[WorkTypeId] = invocation + } + + [Hash.symbol](): number { + return Hash.random(this) + } + + [Equal.symbol](that: unknown): boolean { + return this === that + } + + get _tag(): Work["_tag"] { + return this[WorkTypeId]._tag + } + + get path(): string { + return this[WorkTypeId].path + } + + get id(): string { + return this[WorkTypeId].id + } + + get source(): string | undefined { + const invocation = this[WorkTypeId] + return invocation._tag === "Child" ? undefined : invocation.sourceName + } + + get address(): string | undefined { + const invocation = this[WorkTypeId] + return invocation._tag === "Logic" ? invocation.address : undefined + } + + get child(): ChildMachine.Any | undefined { + const invocation = this[WorkTypeId] + return invocation._tag === "Child" ? invocation.child : undefined + } + + /** Evaluates user code once, and keeps its result or its throw. */ + private evaluate(evaluate: (invocation: any) => A): Exit.Exit { + if (this.#evaluated === undefined) { + try { + this.#evaluated = Exit.succeed(evaluate(this[WorkTypeId])) + } catch (error) { + this.#evaluated = Exit.die(error) + } + } + return this.#evaluated as Exit.Exit + } + + /** Work acts on the children of its machine through the services of its host. */ + private provide(effect: Effect.Effect): Effect.Effect { + const planning = this.planning + return planning.ambient + ? effect + : Effect.updateContext(effect, (context: Context.Context) => Context.merge(context, planning.services)) + } + + effect(): Exit.Exit> { + if (this[WorkTypeId]._tag === "Timer") return Exit.map(this.duration(), Effect.sleep) + // Each run owns a scope, closed with its exit, as on the local runtime. + return this.evaluate((invocation: InvocationResolution.EffectInvocation) => + this.provide(Effect.scoped(invocation.effect())) + ) + } + + duration(): Exit.Exit { + return this.evaluate((invocation: InvocationResolution.TimerInvocation) => invocation.duration()) + } + + stream(): Exit.Exit> { + // A run of a Stream owns a scope too, closed with its end or its stop. + return this.evaluate((invocation: InvocationResolution.StreamInvocation) => { + const planning = this.planning + const stream = Stream.scoped(invocation.stream()) + return planning.ambient + ? stream + : Stream.updateContext(stream, (context: Context.Context) => Context.merge(context, planning.services)) + }) + } + + logic(): Exit.Exit { + return this.evaluate((invocation: InvocationResolution.LogicInvocation) => { + const scoped = LogicScope.scoped(invocation.logic()) + if (this.planning.ambient) return scoped + return { + initial: (context) => this.provide(scoped.initial(context)), + run: (context) => this.provide(scoped.run(context)) + } + }) + } + + input(): Exit.Exit> { + return this.evaluate((invocation: Extract) => + invocation.input === undefined ? empty : [invocation.input()] + ) + } +} + const unchanged = (state: State): Step => new Step(state, undefined, empty, empty, empty, empty, empty) @@ -409,21 +655,6 @@ const exitOfThrow = (error: unknown): Exit.Exit => const latestFirst = (running: ReadonlyArray): ReadonlyArray => running.length < 2 ? running : running.slice().reverse() -/** Calls user code once, and keeps its result or its throw. */ -const once = (evaluate: () => A): () => Exit.Exit => { - let result: Exit.Exit | undefined - return () => { - if (result === undefined) { - try { - result = Exit.succeed(evaluate()) - } catch (error) { - result = Exit.die(error) - } - } - return result - } -} - /** Whether a running piece of work is the child that a command selects, as the local registry matches it. */ const selects = (work: Work, child: ChildSelector): boolean => typeof child === "string" @@ -494,89 +725,18 @@ const invokingPaths = (machine: Machine.Any): ReadonlySet => { */ const build = ( machine: Machine.Any, - options: Options, ownership: O, plan: ExecutionPlan.CompiledExecutionPlan -): MachineStep => { - const planning: Planning = { machine, plan } +): Kernel => { // A machine that invokes no work runs none, so its steps track none. const invoking = invokingPaths(machine) - const references: Configuration.PlanningMachineReferences = { self: options.self, parent: options.parent } - const initialMachine = Planner.withMachineReferences(machine, references) - const children = options.children ?? refusedChildren - const capabilities: InvocationResolution.InvocationCapabilities = { - self: options.self, - parent: options.parent, - children: childOwnerOf(children) - } - // Work acts on the children of this machine through the services of its host. - const services = servicesOf(children) - const provide = (effect: Effect.Effect): Effect.Effect => - Effect.updateContext(effect, (context: Context.Context) => Context.merge(context, services)) - - const scopedLogic = (logic: AnyLogic): AnyLogic => { - const scoped = LogicScope.scoped(logic) - return { - initial: (context) => provide(scoped.initial(context)), - run: (context) => provide(scoped.run(context)) - } - } /** Describes one invocation, without calling any of its user code. */ - const describe = (invocation: InvocationResolution.ResolvedInvocation, run: number): Work => { - const base = { [WorkTypeId]: invocation, path: invocation.path, id: invocation.id, run } - switch (invocation._tag) { - case "Effect": - return { - ...base, - _tag: "Effect", - source: invocation.sourceName, - // Each run owns a scope, closed with its exit, as on the local runtime. - effect: once(() => provide(Effect.scoped(invocation.effect()))) - } - case "Timer": { - const duration = once(invocation.duration) - return { - ...base, - _tag: "Timer", - source: invocation.sourceName, - duration, - effect: () => Exit.map(duration(), Effect.sleep) - } - } - case "Stream": - return { - ...base, - _tag: "Stream", - source: invocation.sourceName, - // A run of a Stream owns a scope too, closed with its end or its stop. - stream: once(() => - Stream.updateContext( - Stream.scoped(invocation.stream()), - (context: Context.Context) => Context.merge(context, services) - ) - ) - } - case "Logic": - return { - ...base, - _tag: "Logic", - source: invocation.sourceName, - address: invocation.address, - logic: once(() => scopedLogic(invocation.logic())) - } - case "Child": { - const input = invocation.input - return { - ...base, - _tag: "Child", - source: undefined, - child: invocation.child, - input: once(() => input === undefined ? empty : [input()]) - } - } - } - } + const describe = ( + planning: Planning, + invocation: InvocationResolution.ResolvedInvocation, + run: number + ): Work => new WorkOf(invocation, run, planning) as unknown as Work /** * Commands of a transition, as data, in order. A command that selects a @@ -626,6 +786,7 @@ const build = ( /** The logical state that a step reached, and what was built of it already. */ interface Reached { + readonly planning: Planning readonly execution: unknown readonly configuration: Configuration.ActiveConfiguration | undefined readonly snapshot: Machine.Snapshot | undefined @@ -633,11 +794,12 @@ const build = ( } const reached = ( + planning: Planning, execution: unknown, configuration: Configuration.ActiveConfiguration | undefined, snapshot: Machine.Snapshot | undefined, runs: number - ): Reached => ({ execution, configuration, snapshot, runs }) + ): Reached => ({ planning, execution, configuration, snapshot, runs }) /** * A machine that ends in a step stops all of its work. `next` is the state the @@ -650,7 +812,7 @@ const build = ( published: Published = nothing ): Step => new Step( - new State(planning, next.execution, next.configuration, next.snapshot, empty, next.runs, exit), + new State(next.planning, next.execution, next.configuration, next.snapshot, empty, next.runs, exit), published.event, published.microsteps, published.emitted, @@ -662,8 +824,10 @@ const build = ( // A plan that throws leaves the state it received as it was, so the state // before a failed step is still the state that was passed in. - const endedFrom = (state: State): Reached => - reached(state.execution, state.configuration, state.snapshot, state.runs) + const endedFrom = (state: State): Reached => { + const built = state.built + return reached(state.planning, built.execution, built.configuration, state.snapshot, state.runs) + } /** * Lists the work of the entered paths, one run per entry. Work that `progress` @@ -687,13 +851,15 @@ const build = ( let added: Array | undefined if (entered.some(([paths]) => paths.some((path) => invoking.has(path)))) { configuration ??= plan.toConfiguration(next.execution) - for (const group of InvocationResolution.resolveEntries(machine, configuration, entered, capabilities)) { + for ( + const group of InvocationResolution.resolveEntries(machine, configuration, entered, next.planning.capabilities) + ) { const run = runs++ for (const invocation of group.invocations) { const status = progress?.find((entry) => entry.path === invocation.path && entry.id === invocation.id) ?.status if (status === "Ended") continue - const work = describe(invocation, run) + const work = describe(next.planning, invocation, run) ;(added ??= []).push(work) if (status !== "Running") (start ??= []).push(work) } @@ -701,7 +867,17 @@ const build = ( } const running = added === undefined ? kept : kept.length === 0 ? added : [...kept, ...added] return new Step( - new State(planning, next.execution, configuration, next.snapshot, running, runs, undefined), + // An owned state keeps only what its host reads again: the configuration + // is built again when a later step needs it. + new State( + next.planning, + next.execution, + ownership === "Owned" ? undefined : configuration, + next.snapshot, + running, + runs, + undefined + ), published.event, published.microsteps, published.emitted, @@ -719,12 +895,13 @@ const build = ( const advance = ( state: State, running: ReadonlyArray, - event: Machine.EventOf | InvocationEvent.InvocationEvent + event: Machine.EventOf | InvocationEvent.InvocationEvent, + retain: boolean ): Step => { let planned: ExecutionPlan.ExecutionMacrostep try { - // A step publishes its microsteps, so every plan retains them. - planned = plan.planDecoded(state.execution, event, ownership, true, references) + // A step publishes its microsteps, so a plan retains them unless its host reads none. + planned = plan.planDecoded(state.execution, event, ownership, retain, state.planning) } catch (error) { // The step planned the event, as transitions receive it, and its planning failed. const planning = InvocationEvent.isInvocationEvent(event) ? InvocationEvent.toLifecycleEvent(event) : event @@ -746,13 +923,13 @@ const build = ( if (invoking.size === 0) { return planned.done ? ended( - reached(planned.next, undefined, undefined, state.runs), + reached(state.planning, planned.next, undefined, undefined, state.runs), empty, Exit.succeed(planned.output), { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } ) : new Step( - new State(planning, planned.next, undefined, undefined, empty, state.runs, undefined), + new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), planned.event, planned.microsteps, planned.emittedEvents, @@ -768,7 +945,7 @@ const build = ( emitted: planned.emittedEvents, commands } - const next = reached(planned.next, undefined, undefined, state.runs) + const next = reached(state.planning, planned.next, undefined, undefined, state.runs) const { kept, stop } = InvocationChanges.partition(commanded === undefined ? running : commanded.running, changes) if (planned.done) { return ended(next, [...stop, ...latestFirst(kept)], Exit.succeed(planned.output), published) @@ -790,17 +967,21 @@ const build = ( /** The state a step starts in, from a configuration that the reference planner built. */ const initial = ( + planning: Planning, configuration: Configuration.ActiveConfiguration, snapshot: Machine.Snapshot - ): Reached => reached(plan.fromConfiguration(configuration), configuration, snapshot, 0) + ): Reached => reached(planning, plan.fromConfiguration(configuration), configuration, snapshot, 0) // Starting and resuming plan with the reference planner: they happen once per // machine, and their result enters the plan through `fromConfiguration`. - const start: MachineStep["start"] = (...input) => { + const start: Kernel["start"] = (planning, input, retain = true) => { + // The execution plan starts a machine that it covers without publishing + // microsteps: a host that reads none takes that start. + if (!retain && plan.initial !== undefined) return startUnretained(planning, plan.initial, input) let planned: ReturnType let configuration: Configuration.ActiveConfiguration try { - planned = Planner.planInitialSync(initialMachine, ...input) + planned = Planner.planInitialSync(Planner.withMachineReferences(machine, planning), ...input) configuration = Configuration.normalizeConfigurationSync(machine, planned.state) } catch (error) { return Exit.fail(toStartupFailure(error)) @@ -815,7 +996,7 @@ const build = ( entered: Planner.sortEntryPaths(machine, Configuration.getInitialEntryPaths(machine, configuration)) } } - const next = initial(configuration, planned.state) + const next = initial(planning, configuration, planned.state) if (planned.done) { return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published)) } @@ -824,6 +1005,39 @@ const build = ( ) } + const startUnretained = ( + planning: Planning, + initialOf: NonNullable, + input: ReadonlyArray + ): Exit.Exit, unknown> => { + let planned: ReturnType + try { + planned = initialOf(input, planning) + } catch (error) { + return Exit.fail(toStartupFailure(error)) + } + const configuration = planned.activeConfiguration + const published: Published = { + event: Planner.InitialEvent, + microsteps: empty, + emitted: empty, + commands: empty, + paths: { exited: empty, entered: Planner.sortEntryPaths(machine, planned.initialEntryPaths) } + } + const next = reached(planning, planned.configuration, configuration, planned.state, 0) + if (planned.done) { + return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published)) + } + return Exit.succeed( + enter(next, InvocationResolution.initialEntries(machine, configuration), empty, empty, published) + ) + } + + const fromSnapshot: Kernel["fromSnapshot"] = (planning, snapshot) => { + if (invoking.size > 0) throw new Error("A machine that invokes work runs its work in its state") + return new State(planning, undefined, undefined, snapshot, empty, 0, undefined) + } + const send = (state: State, event: unknown): Exit.Exit, unknown> => { if (state.exit !== undefined) return Exit.fail(new StoppedError()) let decoded: Machine.EventOf @@ -836,17 +1050,20 @@ const build = ( ? Exit.fail(error) : Exit.succeed(ended(endedFrom(state), latestFirst(state.running), Exit.die(error))) } - return Exit.succeed(advance(state, state.running, decoded)) + return Exit.succeed(advance(state, state.running, decoded, true)) } - const settle = (state: State, work: Work, exit: Exit.Exit): Step => { + const sendDecoded = (state: State, event: Machine.EventOf, retain = true): Step => + state.exit === undefined ? advance(state, state.running, event, retain) : unchanged(state) + + const settle = (state: State, work: Work, exit: Exit.Exit, retain = true): Step => { const settled = current(state, work) if (settled === undefined) return unchanged(state) const running = state.running.filter((other) => other !== settled) const decision = InvocationOutcome.decide(settled[WorkTypeId], generation(), InvocationOutcome.fromExit(exit)) switch (decision._tag) { case "Deliver": - return advance(state, running, decision.event) + return advance(state, running, decision.event, retain) case "Fail": return ended(endedFrom(state), latestFirst(running), Exit.failCause(decision.cause)) case "Ignore": @@ -854,23 +1071,23 @@ const build = ( } } - const element = (state: State, work: Work, value: unknown): Step => { + const element = (state: State, work: Work, value: unknown, retain = true): Step => { const streaming = current(state, work) if (streaming === undefined) return unchanged(state) const invocation = streaming[WorkTypeId] if (invocation._tag !== "Stream") return unchanged(state) const decision = InvocationOutcome.decideElement(invocation, generation(), value) - return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event) + return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event, retain) } - const report = (state: State, work: Work, snapshot: unknown): Step => { + const report = (state: State, work: Work, snapshot: unknown, retain = true): Step => { const reporting = current(state, work) if (reporting === undefined) return unchanged(state) const invocation = reporting[WorkTypeId] if (invocation._tag !== "Logic" && invocation._tag !== "Child") return unchanged(state) // Owners read the state of an active process, as the local runtime reports it. const decision = InvocationOutcome.decideSnapshot(invocation, generation(), { status: "active", state: snapshot }) - return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event) + return decision._tag === "Ignore" ? unchanged(state) : advance(state, state.running, decision.event, retain) } const stop = (state: State): Step => @@ -878,7 +1095,7 @@ const build = ( ? ended(endedFrom(state), latestFirst(state.running), Exit.fail(new StoppedError())) : unchanged(state) - const resume: MachineStep["resume"] = (snapshot, progress) => { + const resume: Kernel["resume"] = (planning, snapshot, progress) => { const normalized = Effect.runSyncExit(Serialization.normalizeSnapshotEffect(machine, snapshot)) if (Exit.isFailure(normalized)) return Exit.failCause(normalized.cause) const state = normalized.value @@ -889,7 +1106,7 @@ const build = ( return exitOfThrow(error) } const published: Published = { ...nothing, event: Planner.InitialEvent } - const next = initial(configuration, state) + const next = initial(planning, configuration, state) if (!Planner.isFinalState(machine, state)) { return Exit.succeed( enter(next, InvocationResolution.initialEntries(machine, configuration), empty, empty, published, progress) @@ -902,38 +1119,99 @@ const build = ( } if (ownership === "Persistent") { - return { start, send, settle, element, report, stop, resume } + return { plan, start, fromSnapshot, rest: (state) => state.resting(), send, sendDecoded, settle, element, report, stop, resume } } // An owned state is taken over by the step it is passed to, and handed back // when the step returns that very state, or refuses the event. return { + plan, start, + fromSnapshot, + rest: (state) => state.handOverNeverReuse().resting(), send: (state, event) => { const exit = send(state.handOverNeverReuse(), event) if (Exit.isFailure(exit) || exit.value.state === state) state.giveBackUnchanged() return exit }, - settle: (state, work, exit) => givenBackIfUnchanged(state, settle(state.handOverNeverReuse(), work, exit)), - element: (state, work, value) => givenBackIfUnchanged(state, element(state.handOverNeverReuse(), work, value)), - report: (state, work, snapshot) => givenBackIfUnchanged(state, report(state.handOverNeverReuse(), work, snapshot)), + sendDecoded: (state, event, retain) => + givenBackIfUnchanged(state, sendDecoded(state.handOverNeverReuse(), event, retain)), + settle: (state, work, exit, retain) => + givenBackIfUnchanged(state, settle(state.handOverNeverReuse(), work, exit, retain)), + element: (state, work, value, retain) => + givenBackIfUnchanged(state, element(state.handOverNeverReuse(), work, value, retain)), + report: (state, work, snapshot, retain) => + givenBackIfUnchanged(state, report(state.handOverNeverReuse(), work, snapshot, retain)), stop: (state) => givenBackIfUnchanged(state, stop(state.handOverNeverReuse())), resume } } +Object.defineProperty(State.prototype, StateTypeId, { value: StateTypeId }) + /** Gives an owned state back to the caller of a step that returned it unchanged. */ const givenBackIfUnchanged = (state: State, step: Step): Step => { if (step.state === state) state.giveBackUnchanged() return step } +type PlannerKind = "Compiled" | "Reference" + +const kernels = { + Persistent: { Compiled: new WeakMap(), Reference: new WeakMap() }, + Owned: { Compiled: new WeakMap(), Reference: new WeakMap() } +} satisfies Record>>> + +/** + * The step functions of `machine` that take states of `ownership` and plan + * with `planner`: the execution plan of the machine, which `compileExecutionPlan` + * selects, or always the reference planner. They are built once per machine. + * + * @internal + */ +export const kernel = (machine: Machine.Any, ownership: O, planner: PlannerKind): Kernel => { + const cache = kernels[ownership][planner] as WeakMap> + let built = cache.get(machine) + if (built === undefined) { + built = build( + machine, + ownership, + planner === "Compiled" + ? ExecutionPlan.compileExecutionPlan(machine) + : ExecutionPlan.selectExecutionPlanForTesting(machine, "generic").plan + ) + cache.set(machine, built) + } + return built +} + +/** The step functions of `kernel`, bound to one host. */ +const bind = (machine: Machine.Any, kernel: Kernel, options: Options): MachineStep => { + const planning = new Planning( + machine, + kernel.plan, + options.self, + options.parent, + options.children ?? refusedChildren + ) + return { + start: (...input) => kernel.start(planning, input), + send: kernel.send, + sendDecoded: kernel.sendDecoded, + settle: kernel.settle, + element: kernel.element, + report: kernel.report, + stop: kernel.stop, + resume: (snapshot, progress) => kernel.resume(planning, snapshot, progress) + } +} + /** * The step functions of `Machine.toStep`, which take immutable state values. * * @internal */ export const make = (machine: Machine.Any, options: Options): MachineStep<"Persistent"> => - build(machine, options, "Persistent", ExecutionPlan.compileExecutionPlan(machine)) + bind(machine, kernel(machine, "Persistent", "Compiled"), options) /** * Step functions that take each state over and may update it in place, for a @@ -944,7 +1222,7 @@ export const make = (machine: Machine.Any, options: Options): MachineStep<"Persi * @internal */ export const makeOwned = (machine: Machine.Any, options: Options): OwnedMachineStep => - build(machine, options, "Owned", ExecutionPlan.compileExecutionPlan(machine)) + bind(machine, kernel(machine, "Owned", "Compiled"), options) /** * Step functions of either ownership that plan with the planner of `planner`: @@ -957,13 +1235,5 @@ export const makeForTesting = ( machine: Machine.Any, options: Options, ownership: O, - planner: "Compiled" | "Reference" -): MachineStep => - build( - machine, - options, - ownership, - planner === "Compiled" - ? ExecutionPlan.compileExecutionPlan(machine) - : ExecutionPlan.selectExecutionPlanForTesting(machine, "generic").plan - ) + planner: PlannerKind +): MachineStep => bind(machine, kernel(machine, ownership, planner), options) diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts new file mode 100644 index 00000000..e28e6119 --- /dev/null +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -0,0 +1,590 @@ +/** + * Runs a machine on its owned step, as a compiled process of the local runtime. + * + * The step decides everything a machine does: its next state, its commands and + * emissions, the work it starts and stops, and what the result of that work + * means. This module only carries a step out, in the order of the step: the + * commands, the work of exited states, the new state, the emitted events, then + * the work of entered states. Work runs as an owned process of the machine, so + * it starts in the turn of the event that entered its state, and its result + * reaches the step through the mailbox of the machine, in a later turn. + * + * @since 0.48.0 + */ + +import * as Cause from "effect/Cause" +import * as Effect from "effect/Effect" +import * as Exit from "effect/Exit" +import * as Option from "effect/Option" +import * as Stream from "effect/Stream" +import type { Inspection } from "../../LocalMachine.js" +import type { ChildMachine, Machine } from "../../Machine.js" +import * as ChildRegistry from "./childRegistry.js" +import * as CommandRuntime from "./commandRuntime.js" +import { ChildAlreadyExistsError, failPlanning } from "./errors.js" +import type * as InvocationEvent from "./invocationEvent.js" +import * as InvocationOutcome from "./invocationOutcome.js" +import type * as InvocationResolution from "./invocationResolution.js" +import * as Runtime from "./runtimeProtocol.js" +import * as Step from "./step.js" + +type OwnedStep = Step.Step<"Owned"> +type Kernel = Step.Kernel<"Owned"> +type Context = Runtime.CompiledProcessContext, unknown> +type Scope = Runtime.ProcessInitialContext +type AnyProcessLogic = Runtime.ProcessLogic +type Drain = Effect.Effect, unknown, unknown> + +/** How a process of the machine begins: started with input, or resumed from a snapshot. */ +export type Entry = + | { readonly _tag: "Initial"; readonly args: ReadonlyArray } + | { readonly _tag: "Resume"; readonly snapshot: Machine.Snapshot } + +/** + * The host of a step in a process, which is also the execution state of the + * process: the latest state of its step, and the step whose work is still to + * start, which only its first step has. Work runs as a process of the + * machine, which finds the services of the machine in its own: every process + * of the runtime provides them. The children of the machine are the children + * its process owns. + */ +class Host extends Step.Planning implements Step.Children { + state!: Step.State<"Owned"> + pending: OwnedStep | undefined + liveRuntime: CommandRuntime.LiveRuntime | undefined + + constructor(machine: Machine.Any, kernel: Kernel, private readonly scope: Scope) { + super(machine, kernel.plan, scope.self, scope.parent, undefined, true) + } + + spawn(child: ChildMachine.Any, options: { readonly input: unknown } | undefined) { + const spawn = this.scope.spawn as (child: unknown, ...options: ReadonlyArray) => Effect.Effect + return options === undefined ? spawn(child) : spawn(child, options) + } + spawnLogic( + logic: Parameters[0], + options: { readonly id?: string | undefined } | undefined + ) { + const spawn = this.scope.spawn as (logic: unknown, options?: unknown) => Effect.Effect + return options === undefined ? spawn(logic) : spawn(logic, options) + } + sendTo(child: string | ChildMachine.Any, event: unknown) { + return this.scope.sendTo(child, event) + } + stop(child: string | ChildMachine.Any) { + return this.scope.stopChild(child) + } +} + +/** Whether the process reports what it does, so its steps keep their microsteps. */ +const isInspected = (scope: Scope): boolean => scope.self.inspectionSubject !== undefined + +const runSequentialDiscard = (effects: ReadonlyArray>): Effect.Effect => + effects.length === 1 ? effects[0]! : Effect.all(effects, { discard: true }) + +/** Carries out the commands of a step, in order. */ +const runCommands = (commands: ReadonlyArray, scope: Scope): Effect.Effect => + Effect.forEach(commands, (command) => { + switch (command._tag) { + case "Send": + return scope.sendTo(command.target, command.event) + case "SendToChild": + return scope.sendTo(command.child, command.event) + case "StopChild": + return scope.stopChild(command.child) + } + }, { discard: true }) + +/** @internal */ +export const makeKey = (path: string, id: string): string => `${path.length}:${path}${id}` + +/** Stops running work, all at once, as the local runtime stops the children of exited states. */ +const stopWork = (context: Context, work: ReadonlyArray): Effect.Effect | undefined => + work.length === 0 + ? undefined + : work.length === 1 + ? context.ownedChildren.stopKey(makeKey(work[0]!.path, work[0]!.id)) + : Effect.all(work.map((one) => context.ownedChildren.stopKey(makeKey(one.path, one.id))), { + concurrency: "unbounded", + discard: true + }) + +// Invocations the runtime hosts as an inspected and traced program. +type ProgramInvocation = + | InvocationResolution.EffectInvocation + | InvocationResolution.TimerInvocation + | InvocationResolution.StreamInvocation + +const isProgram = (invocation: InvocationResolution.ResolvedInvocation): invocation is ProgramInvocation => + invocation._tag === "Effect" || invocation._tag === "Timer" || invocation._tag === "Stream" + +// Logic addresses and child descriptor ids are caller-chosen; every other id is +// owned by the runtime. +const childId = (invocation: InvocationResolution.ResolvedInvocation): string => { + switch (invocation._tag) { + case "Effect": + case "Timer": + case "Stream": + return `${ChildRegistry.invocationChildIdPrefix}${makeKey(invocation.path, invocation.id)}` + case "Logic": + return invocation.address + case "Child": + return invocation.child.id + } +} + +/** + * The value of an accessor of work. Its failure is thrown inside the startup + * boundary of the process that would run the work, which fails the machine. + */ +const valueOf = (exit: Exit.Exit): A => { + if (Exit.isSuccess(exit)) return exit.value + throw Cause.squash(exit.cause) +} + +// The planner reads currency from a generation. The registry of the process +// decides currency for the work it hosts, so each decision gets a current one. +const current = (): InvocationEvent.Generation => ({ current: true }) + +/** The exit of work as its step settles it. */ +const exitOf = (outcome: InvocationOutcome.Outcome): Exit.Exit => + outcome._tag === "Done" ? Exit.succeed(outcome.output) : Exit.failCause((outcome as { cause: Cause.Cause }).cause) + +const traced = (scope: Scope, invocation: ProgramInvocation, logic: AnyProcessLogic): AnyProcessLogic => ({ + ...logic, + run: (context: Runtime.ProcessRunContext) => + Effect.withSpan( + Effect.suspend(() => logic.run(context)), + "Machine.invoke", + { + attributes: { + "machine.id": scope.self.id, + "machine.sessionId": scope.self.sessionId, + "machine.state.path": invocation.path, + "machine.invoke.id": invocation.id, + "machine.invoke.source": invocation.sourceName ?? invocation.id, + "machine.invoke.kind": invocation._tag, + "machine.invoke.sessionId": context.self.sessionId + }, + captureStackTrace: false + } + ) +}) + +/** The process that runs a program, built when its process starts. */ +const programLogic = (scope: Scope, work: Step.Work, invocation: ProgramInvocation): AnyProcessLogic => { + switch (work._tag) { + case "Effect": { + const effect = valueOf(work.effect()) + return traced(scope, invocation, { initial: () => Effect.void, run: () => effect }) + } + case "Timer": { + const duration = valueOf(work.duration()) + return traced(scope, invocation, { initial: () => Effect.void, run: () => Effect.sleep(duration) }) + } + case "Stream": { + const stream = valueOf(work.stream()) + const inspected = isInspected(scope) + return traced(scope, invocation, { + initial: () => Effect.void, + run: ({ parent }: Runtime.ProcessRunContext) => { + const send = parent?.[Runtime.acknowledgedSend] + if (send === undefined) { + return Effect.die(new Error("Stream invocation requires an acknowledged parent machine")) + } + // Each element waits for the machine to take it, which paces the stream. + return Effect.scoped(Stream.runForEach( + stream, + (element) => + send( + new Runtime.WorkMessage( + "Element", + work, + element, + inspected + ? (InvocationOutcome.decideElement(invocation as InvocationResolution.StreamInvocation, current(), element) as InvocationOutcome.Deliver).event + : undefined + ) + ).pipe( + Effect.asVoid, + Effect.catchCause(() => Effect.interrupt) + ) + )) + } + }) + } + default: + throw new Error(`Work of kind ${work._tag} is not a program`) + } +} + +/** Reports the result of work to its machine, which plans it in a later turn. */ +const report = ( + scope: Scope, + message: Runtime.WorkMessage, + invocationSessionId: string | undefined +): Effect.Effect => + (invocationSessionId === undefined || scope.self.sendInspected === undefined + ? scope.self.send(message) + : scope.self.sendInspected( + message, + scope.self.inspectionSubject, + { _tag: "ProgramInvocation", invocationSessionId } satisfies Inspection.Causation + )).pipe(Effect.catchTag("StoppedError", () => Effect.void)) + +/** Starts one piece of work that a step listed, as an owned process of the machine. */ +const startWork = (context: Context, work: Step.Work): Effect.Effect => { + const scope = context.scope + const invocation = work[Step.WorkTypeId] + const program = isProgram(invocation) + // Keep caller-chosen ids out of the namespace reserved for runtime-owned + // invocation ids; runtime-owned ids skip this check. + if (!program && ChildRegistry.isReservedChildId(childId(invocation))) { + return Effect.fail(new ChildAlreadyExistsError({ id: invocation.id })) + } + return Effect.suspend(() => + context.ownedChildren.spawn( + program + ? () => programLogic(scope, work, invocation) + : work._tag === "Logic" + ? () => valueOf(work.logic()) as AnyProcessLogic + // The runtime builds the child's logic from this description, so a + // running parent retains no closure for it. + : invocation as Extract, + { + key: makeKey(work.path, work.id), + path: work.path, + id: childId(invocation), + duplicateId: work.id, + ...(program ? { programKind: invocation._tag } : undefined), + sendParent: (isCurrent, event) => isCurrent() ? scope.self.send(event) : Effect.void, + // The work starts while the event that entered its state is processed, + // and its outcome is handled in a later turn, even when the work + // completes without suspending. The entered state is therefore always + // observed before the outcome leaves it, and the outcome of a state that + // was exited in between is discarded. + onOutcome: (isCurrent, outcome, invocationSessionId) => + Effect.andThen( + Effect.yieldNow, + Effect.suspend(() => { + if (!isCurrent()) return Effect.void + // The step decides what the outcome means. A failure fails the + // machine at once, as the step would when it settles the work. + const decision = InvocationOutcome.decide(invocation, current(), outcome) + switch (decision._tag) { + case "Deliver": + return report( + scope, + new Runtime.WorkMessage("Settle", work, exitOf(outcome), decision.event), + program ? invocationSessionId : undefined + ) + case "Fail": + return scope.failCause(decision.cause) + case "Ignore": + return Effect.void + } + }) + ), + ...(invocation.channels.snapshot + ? { + onSnapshot: (isCurrent: () => boolean, snapshot: { readonly state: unknown }) => { + if (!isCurrent()) return Effect.void + const decision = InvocationOutcome.decideSnapshot(invocation, current(), snapshot) + return decision._tag === "Ignore" + ? Effect.void + : report(scope, new Runtime.WorkMessage("Report", work, snapshot.state, decision.event), undefined) + } + } + : undefined) + } + ) + ) +} + +const startAll = (context: Context, work: ReadonlyArray): Effect.Effect | undefined => + work.length === 0 ? undefined : runSequentialDiscard(work.map((one) => startWork(context, one))) + +/** The plan of a step, as an acknowledged delivery reports it. */ +const planOf = (step: OwnedStep): unknown => { + const microsteps = step.microsteps + const exit = step.exit + return { + event: step.event, + next: step.snapshot, + commands: microsteps.length === 0 ? microsteps : microsteps.flatMap((microstep) => microstep.commands), + emittedEvents: step.emitted, + microsteps, + done: exit !== undefined && Exit.isSuccess(exit), + output: exit !== undefined && Exit.isSuccess(exit) ? exit.value : undefined + } +} + +const noQueuedMessages: Drain = Effect.succeed(Option.none()) + +/** + * The drain of a machine on `kernel`. It plans each message with the step, + * commits steps that need no effectful work in the caller, and returns the + * drain continuing from the first step that does. + */ +const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => { + // A machine that invokes no work keeps only its snapshot until it takes a + // message, and its state from then on. + const hostOf = (context: Context): Host => { + let host = context.executionState as Host | undefined + if (host === undefined) { + host = new Host(machine, kernel, context.scope) + host.state = kernel.fromSnapshot(host, context.state()) + context.executionState = host + } + return host + } + + const takeMessage = (state: Step.State<"Owned">, event: unknown, retain: boolean): OwnedStep => { + if (event instanceof Runtime.WorkMessage) { + const work = event.work as Step.Work + switch (event._tag) { + case "Settle": + return kernel.settle(state, work, event.value as Exit.Exit, retain) + case "Element": + return kernel.element(state, work, event.value, retain) + case "Report": + return kernel.report(state, work, event.value, retain) + } + } + return kernel.sendDecoded(state, event as Machine.EventOf, retain) + } + + const loop = (context: Context): Drain => Effect.suspend(() => drainSync(context) ?? noQueuedMessages) + + /** Starts the work of the first step of the process, then drains. */ + const startPending = (context: Context, host: Host, step: OwnedStep): Drain => { + host.pending = undefined + const starting = startAll(context, step.start) + return starting === undefined ? loop(context) : starting.pipe(Effect.andThen(loop(context))) + } + + /** Carries out a step that needs effectful work, then continues the drain. */ + const continueEffectful = ( + context: Context, + host: Host, + step: OwnedStep, + acknowledged: boolean, + before: Machine.Snapshot, + settled: Step.Work | undefined + ): Drain => { + const scope = context.scope + const exit = step.exit + const done = exit !== undefined + // A machine that ends stops the work of the states it exited before its + // new state, and then the rest of its work, after its emitted events. + // Work that ended in a state the step exits is awaited with the rest, so + // its process has stopped before the state is entered again. + let stopBefore: ReadonlyArray = settled === undefined ? step.stop : [settled, ...step.stop] + let stopAfter: ReadonlyArray = [] + if (done && step.stop.length > 0) { + const exited = new Set(step.exited) + stopBefore = stopBefore.filter((work) => exited.has(work.path)) + stopAfter = step.stop.filter((work) => !exited.has(work.path)) + } + const beforeCommit: Array> = [] + if (step.commands.length > 0) beforeCommit.push(runCommands(step.commands, scope)) + const stopping = stopWork(context, stopBefore) + if (stopping !== undefined) beforeCommit.push(stopping) + const afterCommit: Array> = [] + if (step.emitted.length > 0) { + afterCommit.push( + CommandRuntime.runEmittedEvents(step.emitted, host.liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, scope)) + ) + } + if (done) { + const stopped = stopWork(context, stopAfter) + if (stopped !== undefined) afterCommit.push(stopped) + } else { + const starting = startAll(context, step.start) + if (starting !== undefined) afterCommit.push(starting) + } + const planned = step.planned + const after = planned ? step.snapshot : before + const continueAfterCommit = (): Drain => { + const continued = Effect.suspend((): Drain => { + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after }) + return done ? Effect.succeed(Option.some((exit as Exit.Success).value)) : loop(context) + }) + return afterCommit.length === 0 ? continued : runSequentialDiscard(afterCommit).pipe(Effect.andThen(continued)) + } + const commitAndContinue = (): Drain => { + const notification = planned ? context.commit(after) : undefined + const continued = continueAfterCommit() + const effect = notification === undefined ? continued : notification.pipe(Effect.andThen(continued)) + return notification === undefined && afterCommit.length === 0 ? effect : context.runAfterChanges(effect) + } + return beforeCommit.length === 0 + ? commitAndContinue() + : context.runAfterChanges(runSequentialDiscard(beforeCommit).pipe(Effect.andThen(Effect.suspend(commitAndContinue)))) + } + + // Commits queued messages whose steps need no effectful work. Returns the + // drain continuing from the first message that does, or `undefined` once the + // mailbox is empty. + const drainSync = (context: Context, first?: Runtime.ProcessMessage): Drain | undefined => { + const host = hostOf(context) + if (host.pending !== undefined) { + if (first !== undefined) context.beginMessage(first) + return startPending(context, host, host.pending) + } + let delivered = first + while (true) { + let message: Runtime.ProcessMessage + if (delivered !== undefined) { + message = delivered + delivered = undefined + context.beginMessage(message) + } else { + const pending = context.pollMessage() + if (Option.isNone(pending)) { + // A machine that runs work keeps, while it is idle, only what the + // work needs: its execution state is built again for its next message. + if (!childless) host.state = kernel.rest(host.state) + return undefined + } + message = pending.value + } + const acknowledged = Runtime.isAcknowledgedMessage(message) + const event = Runtime.messageEvent(message) + if (event instanceof Runtime.RefusedEvent) return failPlanning(event.error) + const before = context.state() + // Only an acknowledged delivery reads the microsteps of its step. + const step = takeMessage(host.state, event, acknowledged) + host.state = step.state + const exit = step.exit + if (exit !== undefined && Exit.isFailure(exit)) return Effect.failCause(exit.cause) + const settled = event instanceof Runtime.WorkMessage && event._tag === "Settle" && step.planned && + step.exited.includes((event.work as Step.Work).path) + ? event.work as Step.Work + : undefined + if ( + exit === undefined && settled === undefined && step.commands.length === 0 && step.stop.length === 0 && + step.start.length === 0 && step.emitted.length === 0 + ) { + if (!step.planned) { + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: before }) + continue + } + const next = step.snapshot + const notification = context.commit(next) + if (notification !== undefined) { + return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => { + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) + return loop(context) + })))) + } + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) + continue + } + return continueEffectful(context, host, step, acknowledged, before, settled) + } + } + + return { + run: (context: Context): Drain => + Runtime.provideMachineRuntime(Effect.suspend(() => drainSync(context) ?? noQueuedMessages), context.scope), + runSync: (context: Context, message: Runtime.ProcessMessage): Drain | undefined => { + const remaining = drainSync(context, message) + return remaining === undefined ? undefined : Runtime.provideMachineRuntime(remaining, context.scope) + } + } +} + +/** The result of the first step of a process, as the compiled process takes it. */ +const initialOf = ( + step: OwnedStep, + host: Host | undefined +): Runtime.CompiledProcessInitial, unknown> => { + const exit = step.exit + const done = exit !== undefined && Exit.isSuccess(exit) + if (host === undefined) { + return done + ? { state: step.snapshot, done: true, output: (exit as Exit.Success).value } + : { state: step.snapshot, done: false, output: undefined } + } + return done + ? { state: step.snapshot, done: true, output: (exit as Exit.Success).value, executionState: host } + : { state: step.snapshot, done: false, output: undefined, executionState: host } +} + +/** + * The execution of a machine on its owned step, which plans with `planner`. + * + * @internal + */ +export const makeExecution = ( + machine: Machine.Any, + entry: Entry, + planner: "Compiled" | "Reference", + childless: boolean, + decodeEvent: Runtime.EventDecoder +): Runtime.CompiledProcessExecution, unknown, any, any, any, any> => { + const kernel = Step.kernel(machine, "Owned", planner) + const drain = makeDrain(machine, kernel, childless) + + const first = (scope: Scope): Exit.Exit => + entry._tag === "Initial" + ? kernel.start(new Host(machine, kernel, scope), entry.args, isInspected(scope)) + : kernel.resume(new Host(machine, kernel, scope), entry.snapshot) + + // An idle machine that invokes no work holds only its snapshot. + const host = (step: OwnedStep): Host | undefined => { + if (childless) return undefined + const host = step.state.planning as Host + host.state = step.state + if (step.start.length > 0) host.pending = step + return host + } + + // A machine that its execution plan starts runs no command and emits nothing + // when it starts, so it starts without an Effect. + const initialSync = entry._tag === "Initial" && kernel.plan.initial !== undefined + ? (scope: Scope): Runtime.CompiledProcessInitial, unknown> => { + const started = first(scope) + if (Exit.isFailure(started)) throw Cause.squash(started.cause) + const step = started.value + if (step.commands.length > 0 || step.emitted.length > 0) { + throw new Error("Machine started by its execution plan planned startup commands or emissions") + } + if (entry._tag === "Initial") scope.inspectInitial(step.entered, step.microsteps) + return initialOf(step, host(step)) + } + : undefined + + const initial = ( + scope: Scope + ): Effect.Effect, unknown>, unknown, unknown> => + Runtime.provideMachineRuntime( + Effect.suspend(() => { + const started = first(scope) + if (Exit.isFailure(started)) return Effect.failCause(started.cause) + const step = started.value + if (entry._tag === "Initial") scope.inspectInitial(step.entered, step.microsteps) + const result = Effect.succeed(initialOf(step, host(step))) + const commands = step.commands.length === 0 ? undefined : runCommands(step.commands, scope) + const emitted = step.emitted.length === 0 + ? undefined + : CommandRuntime.runEmittedEvents(step.emitted, CommandRuntime.makeLiveRuntime(machine, scope)) + return commands === undefined + ? emitted === undefined ? result : emitted.pipe(Effect.andThen(result)) + : emitted === undefined + ? commands.pipe(Effect.andThen(result)) + : commands.pipe(Effect.andThen(emitted), Effect.andThen(result)) + }), + scope + ) + + return { + _tag: "Compiled", + childless, + decodeEvent, + initial, + ...(initialSync === undefined ? undefined : { initialSync }), + drain: { _tag: "Owned", run: drain.run, runSync: drain.runSync } + } +} From ae0b5ebdcba2d3ca92f84624f4e7054e97e5c5a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:15:00 +0000 Subject: [PATCH 06/11] Run Machine.logic on the same local process, and delete the generic runtime Logic other than a machine runs as a resident program of the local process: it starts in its starter's turn, receives from the same mailbox, and its exit ends the process. The generic runtime, the invocation host and its generation bookkeeping are gone; the step owns those rules. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .changeset/local-rejects-refused-events.md | 2 + .../src/internal/machine/childRegistry.ts | 3 - .../src/internal/machine/invocation.ts | 278 ------ .../internal/machine/invocationGeneration.ts | 84 -- .../internal/machine/invocationResolution.ts | 28 +- .../src/internal/machine/runtime.ts | 17 +- .../src/internal/machine/runtimeCompiled.ts | 382 +++++--- .../src/internal/machine/runtimeGeneric.ts | 862 ------------------ .../src/internal/machine/runtimeProtocol.ts | 57 +- .../src/internal/machine/step.ts | 27 +- .../src/internal/machine/stepHost.ts | 19 +- .../test/internal/machine/invocation.test.ts | 49 - .../machine/invocationOutcome.test.ts | 18 - .../test/internal/machine/stepHost.test.ts | 9 + scripts/check-architecture.mjs | 24 +- scripts/check-architecture.test.mjs | 25 +- 16 files changed, 357 insertions(+), 1527 deletions(-) delete mode 100644 packages/effect-machine/src/internal/machine/invocation.ts delete mode 100644 packages/effect-machine/src/internal/machine/invocationGeneration.ts delete mode 100644 packages/effect-machine/src/internal/machine/runtimeGeneric.ts delete mode 100644 packages/effect-machine/test/internal/machine/invocation.test.ts create mode 100644 packages/effect-machine/test/internal/machine/stepHost.test.ts diff --git a/.changeset/local-rejects-refused-events.md b/.changeset/local-rejects-refused-events.md index 958f4c90..1dbe6453 100644 --- a/.changeset/local-rejects-refused-events.md +++ b/.changeset/local-rejects-refused-events.md @@ -7,3 +7,5 @@ A timer that cannot start now has one failure mode: `Machine.MachineStep.Work.Timer.duration()` returns an `Exit`, which fails when the input mapper or the source throws and when the input names no duration. Every host settles the timer with that failure where it would have started. A transition that throws follows one documented rule on every host: the error goes to the sender when one waits for the event to be processed, and otherwise the machine fails. Each host keeps its behaviour. + +Every machine and every `Machine.logic` that `LocalMachine` runs now shares one process. A `send` to logic whose stop was already requested fails with `StoppedError`, as it does for a machine, and the `Initialized` inspection event of an inspected machine lists its entry paths and microsteps in the order of the reference planner. diff --git a/packages/effect-machine/src/internal/machine/childRegistry.ts b/packages/effect-machine/src/internal/machine/childRegistry.ts index cf31a745..1e08212e 100644 --- a/packages/effect-machine/src/internal/machine/childRegistry.ts +++ b/packages/effect-machine/src/internal/machine/childRegistry.ts @@ -15,7 +15,6 @@ export type ChildEntry = readonly _tag: "Starting" readonly token: symbol readonly ownerKey?: string - readonly ownerPath?: string ownerActive?: boolean } | { @@ -24,7 +23,6 @@ export type ChildEntry = readonly descriptor: ChildDescriptor | undefined readonly ref: MachineRef readonly ownerKey?: string - readonly ownerPath?: string ownerActive?: boolean } @@ -141,7 +139,6 @@ export const registerChild = ( descriptor, ref, ownerKey: entry.ownerKey, - ownerPath: entry.ownerPath!, ownerActive: entry.ownerActive === true } registry.children.set(key, started) diff --git a/packages/effect-machine/src/internal/machine/invocation.ts b/packages/effect-machine/src/internal/machine/invocation.ts deleted file mode 100644 index c88f9716..00000000 --- a/packages/effect-machine/src/internal/machine/invocation.ts +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Runs resolved invocations as owned processes of the local runtime. - * - * @since 0.4.0 - */ - -import * as Effect from "effect/Effect" -import * as Stream from "effect/Stream" -import type { ChildMachine, ChildOwner, Machine } from "../../Machine.js" -import * as ChildRegistry from "./childRegistry.js" -import * as Configuration from "./configuration.js" -import { ChildAlreadyExistsError } from "./errors.js" -import type * as InvocationEvent from "./invocationEvent.js" -import * as InvocationOutcome from "./invocationOutcome.js" -import * as InvocationResolution from "./invocationResolution.js" -import * as LogicScope from "./logicScope.js" -import * as Runtime from "./runtimeProtocol.js" - -type AnyProcessLogic = Runtime.ProcessLogic - -/** Invocations the runtime hosts as an inspected and traced program. */ -type ProgramInvocation = - | InvocationResolution.EffectInvocation - | InvocationResolution.TimerInvocation - | InvocationResolution.StreamInvocation - -/** @internal */ -export const makeKey = (path: string, id: string): string => `${path.length}:${path}${id}` - -/** @internal */ -export const makeChildId = (path: string, id: string): string => - `${ChildRegistry.invocationChildIdPrefix}${makeKey(path, id)}` - -// Each run of invoked work owns a `Scope`, closed with the run's exit when the -// work ends or is stopped, so its resources never outlive it. -const oneShot = ( - effect: Effect.Effect -): Runtime.ProcessLogic => ({ - initial: () => Effect.void, - run: () => Effect.scoped(effect) -}) - -// A timer acquires nothing, so it needs no scope of its own. -const delay = ( - duration: ReturnType -): Runtime.ProcessLogic => ({ - initial: () => Effect.void, - run: () => Effect.sleep(duration) -}) - -const streamLogic = ( - invocation: InvocationResolution.StreamInvocation, - generation: InvocationEvent.Generation -): Runtime.ProcessLogic => { - const stream = invocation.stream() - return { - initial: () => Effect.void, - run: ({ parent }) => { - const send = parent?.[Runtime.acknowledgedSend] - if (send === undefined) { - return Effect.die(new Error("Stream invocation requires an acknowledged parent machine")) - } - return Effect.scoped(Stream.runForEach( - stream, - (element) => { - const decision = InvocationOutcome.decideElement(invocation, generation, element) - return decision._tag === "Ignore" - ? Effect.interrupt - : send(decision.event).pipe( - Effect.asVoid, - Effect.catchCause(() => Effect.interrupt) - ) - } - )) - } - } -} - -const makeChildOwner = (scope: Runtime.ProcessInitialContext): ChildOwner => ({ - spawn: ( - child: Child & ChildMachine.Executable & ChildMachine.ParentCompatibility, - ...options: ChildMachine.SpawnArgs - ) => scope.spawn(child, ...options), - sendTo: (descriptor: ChildMachine.Any, event: unknown) => scope.sendTo(descriptor, event), - stop: (descriptor: ChildMachine.Any) => scope.stopChild(descriptor) -}) - -const runSequentialDiscard = ( - effects: ReadonlyArray> -): Effect.Effect => - effects.length === 1 - ? effects[0]! - : Effect.all(effects, { discard: true }) - -const sendLifecycle = ( - scope: Runtime.ProcessInitialContext, - event: InvocationEvent.InvocationEvent, - invocationSessionId?: string -): Effect.Effect => - (invocationSessionId === undefined - ? scope.self.send(event) - : scope.self.sendInspected === undefined - ? scope.self.send(event) - : scope.self.sendInspected( - event, - scope.self.inspectionSubject, - { _tag: "ProgramInvocation", invocationSessionId } - )).pipe(Effect.catchTag("StoppedError", () => Effect.void)) - -const isProgram = (invocation: InvocationResolution.ResolvedInvocation): invocation is ProgramInvocation => { - switch (invocation._tag) { - case "Effect": - case "Timer": - case "Stream": - return true - case "Logic": - case "Child": - return false - } -} - -const traced = ( - scope: Runtime.ProcessInitialContext, - invocation: ProgramInvocation, - logic: AnyProcessLogic -): AnyProcessLogic => ({ - ...logic, - run: (context: Runtime.ProcessRunContext) => - Effect.withSpan( - Effect.suspend(() => logic.run(context)), - "Machine.invoke", - { - attributes: { - "machine.id": scope.self.id, - "machine.sessionId": scope.self.sessionId, - "machine.state.path": invocation.path, - "machine.invoke.id": invocation.id, - "machine.invoke.source": invocation.sourceName ?? invocation.id, - "machine.invoke.kind": invocation._tag, - "machine.invoke.sessionId": context.self.sessionId - }, - captureStackTrace: false - } - ) -}) - -// Source construction keeps its startup failure boundary. Only the hosted -// program is wrapped; child statecharts retain their execution descriptors. -const programLogic = ( - scope: Runtime.ProcessInitialContext, - invocation: ProgramInvocation, - generation: InvocationEvent.Generation -): AnyProcessLogic => { - switch (invocation._tag) { - case "Effect": - return traced(scope, invocation, oneShot(invocation.effect())) - case "Timer": - return traced(scope, invocation, delay(invocation.duration())) - case "Stream": - return traced(scope, invocation, streamLogic(invocation, generation)) - } -} - -// Logic addresses and child descriptor ids are caller-chosen; every other id is -// owned by the runtime. -const childId = (invocation: InvocationResolution.ResolvedInvocation): string => { - switch (invocation._tag) { - case "Effect": - case "Timer": - case "Stream": - return makeChildId(invocation.path, invocation.id) - case "Logic": - return invocation.address - case "Child": - return invocation.child.id - } -} - -// A running invocation retains this closure context, so every closure below -// shares it and captures only the scope, the description, and the generation. -const spawn = ( - scope: Runtime.ProcessInitialContext, - ownedChildren: Runtime.OwnedChildRuntime, - invocation: InvocationResolution.ResolvedInvocation, - generation: InvocationEvent.Generation -): Effect.Effect => - ownedChildren.spawn( - isProgram(invocation) - ? () => programLogic(scope, invocation, generation) - : invocation._tag === "Logic" - ? () => LogicScope.scoped(invocation.logic() as AnyProcessLogic) - // The runtime builds the child's logic from this description, so a - // running parent retains no closure for it. - : invocation, - { - key: makeKey(invocation.path, invocation.id), - path: invocation.path, - id: childId(invocation), - duplicateId: invocation.id, - ...(isProgram(invocation) ? { programKind: invocation._tag } : undefined), - sendParent: (isCurrent, event) => isCurrent() ? scope.self.send(event) : Effect.void, - // The work starts while the event that entered its state is processed, - // and its outcome is handled in a later turn, even when the work - // completes without suspending. The entered state is therefore always - // observed before the outcome leaves it, and the outcome of a state that - // was exited in between is discarded. - onOutcome: (isCurrent, outcome, invocationSessionId) => - Effect.andThen( - Effect.yieldNow, - Effect.suspend(() => { - if (!isCurrent()) return Effect.void - const decision = InvocationOutcome.decide(invocation, generation, outcome) - switch (decision._tag) { - case "Deliver": - return sendLifecycle(scope, decision.event, isProgram(invocation) ? invocationSessionId : undefined) - case "Fail": - return scope.failCause(decision.cause) - case "Ignore": - return Effect.void - } - }) - ), - ...(invocation.channels.snapshot - ? { - onSnapshot: (isCurrent: () => boolean, snapshot: unknown) => { - if (!isCurrent()) return Effect.void - const decision = InvocationOutcome.decideSnapshot(invocation, generation, snapshot) - return decision._tag === "Ignore" ? Effect.void : sendLifecycle(scope, decision.event) - } - } - : undefined) - } - ) - -// Keep caller-chosen ids out of the namespace reserved for runtime-owned -// invocation ids; runtime-owned ids skip this check. -const start = ( - scope: Runtime.ProcessInitialContext, - ownedChildren: Runtime.OwnedChildRuntime, - invocation: InvocationResolution.ResolvedInvocation, - generation: InvocationEvent.Generation -): Effect.Effect => - !isProgram(invocation) && ChildRegistry.isReservedChildId(childId(invocation)) - ? Effect.fail(new ChildAlreadyExistsError({ id: invocation.id })) - : Effect.suspend(() => spawn(scope, ownedChildren, invocation, generation)) - -/** - * Starts every invocation owned by active entry paths in deterministic entry - * order. `undefined` keeps the compiled drain free of empty Effect nodes. - * - * @internal - */ -export const startAll = ( - machine: Machine.Any, - scope: Runtime.ProcessInitialContext, - ownedChildren: Runtime.OwnedChildRuntime, - configuration: Configuration.ActiveConfiguration, - paths: ReadonlyArray, - event: Machine.LifecycleEvent -): Effect.Effect | undefined => { - const references = Configuration.getMachineReferences(configuration) ?? scope - const groups = InvocationResolution.resolve(machine, configuration, paths, event, { - self: references.self, - parent: references.parent, - children: makeChildOwner(scope) - }) - if (groups.length === 0) return undefined - const effects: Array> = [] - for (const group of groups) { - // Every invocation started by this entry shares one generation, which its - // outcomes carry until the state exits. - const generation = ownedChildren.beginGeneration(group.path) - for (const invocation of group.invocations) { - effects.push(start(scope, ownedChildren, invocation, generation)) - } - } - return runSequentialDiscard(effects) -} diff --git a/packages/effect-machine/src/internal/machine/invocationGeneration.ts b/packages/effect-machine/src/internal/machine/invocationGeneration.ts deleted file mode 100644 index 9826e578..00000000 --- a/packages/effect-machine/src/internal/machine/invocationGeneration.ts +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Generation bookkeeping for the invoking states of one machine instance. - * - * @since 0.47.2 - */ - -import type * as InvocationEvent from "./invocationEvent.js" - -/** - * The current generation of each active invoking state of one machine instance. - * - * A host owns one instance per hosted machine instance and must: - * - * - begin a generation each time it starts the invocations of an entered state, - * once per group returned by `InvocationResolution.resolve`; - * - keep it current while the state stays active, including after its - * invocations have finished; - * - retire it when the state exits, no later than the invocations it owns are - * stopped, and retire every generation when the machine stops. - * - * Retiring is what makes late outcomes harmless: every `InvocationEvent` - * carries its generation, so the planner ignores one that was queued before its - * state exited, even after the same path and id are entered again. - * - * @internal - */ -export class InvocationGenerations { - // Most configurations have one invoking path, held inline; further paths use - // the map. Entries are removed when their state exits, so neither outgrows - // the active configuration. - private generationPath: string | undefined - private generation: InvocationEvent.Generation | undefined - private generations: Map | undefined - - /** Begins the generation of an entered path and retires the one it replaces. */ - beginGeneration(path: string): InvocationEvent.Generation { - this.retireGeneration(path) - const generation: InvocationEvent.Generation = { current: true } - if (this.generationPath === undefined) { - this.generationPath = path - this.generation = generation - } else { - ;(this.generations ??= new Map()).set(path, generation) - } - return generation - } - - /** Retires the generations of exited paths; paths without one are ignored. */ - retireGenerations(paths: ReadonlyArray): void { - if (this.generation !== undefined || (this.generations !== undefined && this.generations.size > 0)) { - for (const path of paths) this.retireGeneration(path) - } - } - - /** Retires every generation when the machine stops. */ - retireAllGenerations(): void { - if (this.generation !== undefined) { - this.generation.current = false - this.generationPath = undefined - this.generation = undefined - } - const generations = this.generations - if (generations !== undefined && generations.size > 0) { - for (const generation of generations.values()) generation.current = false - generations.clear() - } - } - - private retireGeneration(path: string): void { - const inline = this.generation - if (inline !== undefined && this.generationPath === path) { - inline.current = false - this.generationPath = undefined - this.generation = undefined - return - } - const generations = this.generations - const generation = generations?.get(path) - if (generations !== undefined && generation !== undefined) { - generation.current = false - generations.delete(path) - } - } -} diff --git a/packages/effect-machine/src/internal/machine/invocationResolution.ts b/packages/effect-machine/src/internal/machine/invocationResolution.ts index a04f97c0..6e8bfaa2 100644 --- a/packages/effect-machine/src/internal/machine/invocationResolution.ts +++ b/packages/effect-machine/src/internal/machine/invocationResolution.ts @@ -2,28 +2,12 @@ * Host-neutral resolution of the work owned by entered states. * * `resolve` answers which invocations a step starts, in which order, and what - * each one is. It runs nothing. Starting the work, owning it, and returning its - * outcomes to the planner belong to the host, such as the local runtime in - * `invocation.ts`. - * - * A host must: - * - * - resolve against the configuration the step settled in, with the lifecycle - * event that last entered each path, as `InvocationChanges` reads them; - * - stop the work and retire the generations of exited paths before it starts - * the work of entered ones; - * - begin one generation for each returned group, through - * `InvocationGenerations`, and start the group's invocations in order; - * - call each lazy source at most once per start, inside its own startup failure - * boundary, after the previous invocation has started. A host that stores when - * a timer is due evaluates its duration earlier, and reports a failure of that - * where the timer would have started; - * - route everything the work reports through `InvocationOutcome` with the - * group's generation, and plan a delivered event in a later turn than the one - * that started the work. - * - * `step.ts` follows these rules for hosts outside this package, which use - * `Machine.toStep` instead. + * each one is. It runs nothing. `step.ts` is its one caller: it resolves the + * work of entered states against the configuration the step settled in, stops + * the work of exited paths before it starts the work of entered ones, evaluates + * each lazy source at most once per start, and routes what the work reports + * through `InvocationOutcome`. Every host, the local runtime included, starts + * and owns the work that a step lists. * * @since 0.47.2 */ diff --git a/packages/effect-machine/src/internal/machine/runtime.ts b/packages/effect-machine/src/internal/machine/runtime.ts index 747f67c1..37b2835e 100644 --- a/packages/effect-machine/src/internal/machine/runtime.ts +++ b/packages/effect-machine/src/internal/machine/runtime.ts @@ -6,7 +6,6 @@ import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import * as InspectionRuntime from "./inspectionRuntime.js" import { startCompactCompiledInternal, startCompiledSync } from "./runtimeCompiled.js" -import { startGenericInternal } from "./runtimeGeneric.js" import { type MachineRef, type MakeChildLogic, @@ -18,13 +17,8 @@ import { type StartProcess } from "./runtimeProtocol.js" -const startLogicInternal: StartProcess = (( - logic: ProcessLogic, - options: StartInternalOptions -) => - logic.execution?._tag === "Compiled" - ? startCompactCompiledInternal(logic, options) - : startGenericInternal(logic, options)) as StartProcess +// Every logic runs on one local process. +const startLogicInternal: StartProcess = startCompactCompiledInternal export type ProcessRuntimeStrategy = "generic" | "compiled" | "auto" @@ -113,9 +107,6 @@ export const make = (makeChildLogic: MakeChildLogic) => { detached: true, runtime } - if (strategy === "generic") { - return yield* ownedByScope((hooks) => startGenericInternal(logic, { ...internalOptions, ...hooks })) - } if (strategy === "compiled") { if (logic.execution?._tag !== "Compiled") { return yield* Effect.die(new Error("Machine cannot force the compiled runtime for generic process logic")) @@ -228,9 +219,7 @@ export const make = (makeChildLogic: MakeChildLogic) => { } const initialize = (hooks: OwnershipHooks) => { const startOptions = { ...internalOptions, ...hooks } - return strategy === "generic" - ? startGenericInternal(logic, startOptions) - : strategy === "compiled" + return strategy === "compiled" ? logic.execution?._tag === "Compiled" ? startCompactCompiledInternal(logic, startOptions) : Effect.die(new Error("Machine cannot force the compiled runtime for generic process logic")) diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index a7e65497..0ec70dbc 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -1,4 +1,8 @@ -/** Compiled statechart execution strategy. */ +/** + * The local process: one driver for every logic that LocalMachine runs. A + * machine drains its mailbox through its compiled execution, and other logic + * runs as a resident program that receives from the same mailbox. + */ import * as Cause from "effect/Cause" import * as Channel from "effect/Channel" import * as Context from "effect/Context" @@ -9,6 +13,7 @@ import * as Fiber from "effect/Fiber" import * as Option from "effect/Option" import * as PubSub from "effect/PubSub" import type { SchedulerDispatcher } from "effect/Scheduler" +import * as Semaphore from "effect/Semaphore" import * as Stream from "effect/Stream" import type * as Take from "effect/Take" import type { Inspection } from "../../LocalMachine.js" @@ -23,6 +28,7 @@ import { childlessRuntime, type ChildRuntime, closeCompactMailbox, + closeProcessMailbox, type CompactProcessMailbox, type CompiledProcessContext, type CompiledProcessExecution, @@ -32,30 +38,35 @@ import { deliverEvent, type EmissionRuntime, EmissionsClosed, + type EventDecoder, + executionIsChildless, failAcknowledgedMessage, inspectionSubject, isAcknowledgedMessage, isMachineTarget, type LazyEmissions, type MachineRef, - makeChildRuntime, makeChildRuntimeSync, makeInspectedMessage, + makeProcessMailbox, messageCausation, messageEvent, noInspectInitial, noParentSend, notifyActiveSnapshot, offerCompactMailbox, + offerProcessMailbox, type OwnedChildRuntime, pollCompactMailbox, type ProcessEndpoint, type ProcessInitialContext, type ProcessLogic, + type ProcessMailbox, type ProcessMessage, type ProcessRunContext, type ProcessRuntime, publishInspectedSent, + receiveProcessMailbox, RefusedEvent, type RuntimeSnapshot, sendEndpoint, @@ -89,7 +100,7 @@ class CompiledAddress implements ProcessEndpoint { readonly id: string readonly sessionId: string declare readonly inspectionSubject?: Inspection.Subject - constructor(private readonly process: CompiledProcess, readonly stop: Effect.Effect) { + constructor(private readonly process: LocalProcess, readonly stop: Effect.Effect) { this.id = process.id this.sessionId = process.sessionId if (process.inspectionSubject !== undefined) { @@ -109,14 +120,14 @@ class CompiledAddress implements ProcessEndpoint { } /** - * Compact runtime for compiled statecharts. + * A local process. * * All long-lived state is stored directly on this object. Operations are * implemented by shared prototype methods, and public Effect / Stream values - * are materialized only when accessed. Arbitrary process logic continues to - * use the general runtime above. + * are materialized only when accessed. `MachineProcess` drains a compiled + * execution, and `LogicProcess` runs other logic as a resident program. */ -class CompiledProcess implements MachineRef { +abstract class LocalProcess implements MachineRef { readonly id: string readonly sessionId: string readonly inspectionSubject?: Inspection.Subject @@ -135,17 +146,6 @@ class CompiledProcess implements MachineRef { ): Effect.Effect { return this.deliver(event, source, causedBy) } - [acknowledgedSend]( - event: unknown - ): Effect.Effect, unknown | StoppedError> { - return Effect.suspend(() => { - if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) - const decoded = decodeSent(this.execution.decodeEvent, event) - return decoded._tag === "Rejected" - ? Effect.fail(decoded.error) - : this.sendAcknowledgedEffect(decoded.event, event) - }) - } [snapshotObserver](observer: () => void): () => void { const observers = this.snapshotObservers ??= new Set() observers.add(observer) @@ -154,34 +154,34 @@ class CompiledProcess implements MachineRef { } } - private readonly mailbox: CompactProcessMailbox = { + protected readonly mailbox: CompactProcessMailbox = { items: undefined, index: 0, closed: false } - private readonly address: CompiledAddress + protected readonly address: CompiledAddress private childRuntime: ChildRuntime = childlessRuntime - private processScope!: ProcessInitialContext - private processContext: ProcessRunContext | undefined + protected processScope!: ProcessInitialContext + protected processContext: ProcessRunContext | undefined private compiledContext: CompiledProcessContext | undefined - private current!: VersionedSnapshot + protected current!: VersionedSnapshot /** * `Active` has no terminal payload, `TerminationRequested` owns * `termination` and its optional reserved snapshot, and `Completed` owns * `completion`. `runState` independently tracks worker activity. */ - private lifecycle: CompiledLifecycle = "Active" - private runState: CompiledRunState = "Initializing" + protected lifecycle: CompiledLifecycle = "Active" + protected runState: CompiledRunState = "Initializing" private completion: CompiledCompletion | undefined private waiter: Deferred.Deferred | undefined private termination: CompiledTermination | undefined private terminationSnapshot: RuntimeSnapshot | undefined - private worker: Fiber.Fiber | undefined + protected worker: Fiber.Fiber | undefined private interruptRequested = false private offerRevision = 0 private snapshotObservers: Set<() => void> | undefined private changesFlushScheduled = false - private inFlightMessage: ProcessMessage | undefined + protected inFlightMessage: ProcessMessage | undefined private readonly externalEmissions: EmissionRuntime | undefined private emissionsPubSub: LazyEmissions private readonly programInvocation?: Inspection.ProgramInvocation @@ -190,9 +190,9 @@ class CompiledProcess implements MachineRef { private initializing?: boolean constructor( - private readonly logic: ProcessLogic, - private readonly options: StartInternalOptions, - private readonly services: Context.Context, + protected readonly logic: ProcessLogic, + protected readonly options: StartInternalOptions, + protected readonly services: Context.Context, sessionId: string ) { this.sessionId = sessionId @@ -210,7 +210,7 @@ class CompiledProcess implements MachineRef { this.address = new CompiledAddress(this, Effect.suspend(() => this.stopFromProcess())) } - private get inspector(): InspectionRuntime.Runtime | undefined { + protected get inspector(): InspectionRuntime.Runtime | undefined { return this.options.runtime.inspection } @@ -271,20 +271,51 @@ class CompiledProcess implements MachineRef { ) } - private get execution(): CompiledProcessExecution { + protected get execution(): CompiledProcessExecution { return this.logic.execution as CompiledProcessExecution } + /** Decodes a public event as it enters the mailbox; only a machine decodes. */ + protected get decodeEvent(): EventDecoder | undefined { + const execution = this.logic.execution + return execution?._tag === "Compiled" ? execution.decodeEvent : undefined + } + + private get childless(): boolean { + return executionIsChildless(this.logic.execution) + } + + /** The children of this process, as its logic spawns them. */ + protected abstract makeChildRuntime(): ChildRuntime + + /** Enqueues a message that the mailbox accepts. */ + protected enqueue(message: ProcessMessage): void { + offerCompactMailbox(this.mailbox, message) + } + + protected closeMailbox(): void { + closeCompactMailbox(this.mailbox) + } + + protected prepareCompiledContext(initialized: object): void { + this.compiledContext = new CompiledProcessContextImpl(this.processScope, this.childRuntime.owned, this) + if ("executionState" in initialized) { + this.compiledContext.executionState = (initialized as { readonly executionState: unknown }).executionState + } + } + + /** Prepares how the process runs once its initial state is known. */ + protected abstract prepareRun(initialized: object): void + + /** Runs the process once it is initialized and its startup hooks ran. */ + protected abstract run(): Effect.Effect + + /** The run state of an initialized process that does not run yet. */ + protected abstract readonly initializedRunState: CompiledRunState + initializeCompiledSync(): Effect.Effect, unknown> { this.publishCreated() - if (!this.execution.childless) { - this.childRuntime = makeChildRuntimeSync( - this.address, - this.options.runtime, - this.services, - (event) => this.sendAcknowledgedEffect(decodeDelivered(this.execution.decodeEvent, event), sentOf(event)) - ) - } + if (!this.childless) this.childRuntime = this.makeChildRuntime() const parent = this.options.parent const sendParent = this.options.sendParent ?? (parent === undefined ? noParentSend @@ -334,10 +365,7 @@ class CompiledProcess implements MachineRef { snapshot: { status: "active", state: initialized.state } } this.publishInitialized(initialized.state) - this.compiledContext = new CompiledProcessContextImpl(this.processScope, this.childRuntime.owned, this) - if ("executionState" in initialized) { - this.compiledContext.executionState = initialized.executionState - } + this.prepareCompiledContext(initialized) if (this.options.onReadySync !== undefined && !this.options.onReadySync(this)) { this.requestTerminationSync({ _tag: "Stopped" }) } @@ -345,7 +373,7 @@ class CompiledProcess implements MachineRef { this.requestTerminationSync({ _tag: "Done", output: initialized.output }) } if ( - initialized.done === false && this.execution.childless && + initialized.done === false && this.childless && this.lifecycle === "Active" && this.mailbox.items === undefined ) { @@ -359,14 +387,7 @@ class CompiledProcess implements MachineRef { const self = this return Effect.gen(function*() { self.publishCreated() - if (!self.execution.childless) { - self.childRuntime = yield* makeChildRuntime( - self.address, - self.options.runtime, - self.services, - (event) => self.sendAcknowledgedEffect(decodeDelivered(self.execution.decodeEvent, event), sentOf(event)) - ) - } + if (!self.childless) self.childRuntime = self.makeChildRuntime() const parent = self.options.parent const sendParent = self.options.sendParent ?? (parent === undefined ? noParentSend @@ -402,7 +423,7 @@ class CompiledProcess implements MachineRef { const cleanupStartupFailure = (exit: Exit.Exit): Effect.Effect => Exit.isFailure(exit) ? self.childRuntime.close(exit) : Effect.void - const compiledInitial = self.execution.initial + const compiledInitial = self.logic.execution?._tag === "Compiled" ? self.execution.initial : undefined const initializeEffect: Effect.Effect< { readonly state: unknown @@ -422,7 +443,7 @@ class CompiledProcess implements MachineRef { return cleanupStartupFailure(exit) }), Effect.ensuring(Effect.sync(() => { - self.runState = "Idle" + self.runState = self.initializedRunState })) ) const initial = initialized.state @@ -433,24 +454,7 @@ class CompiledProcess implements MachineRef { snapshot: { status: "active", state: initial } } self.publishInitialized(initial) - if (self.execution.drain._tag === "Process") { - self.processContext = { - ...self.processScope, - receive: Effect.never, - poll: Effect.sync(() => Option.map(pollCompactMailbox(self.mailbox), messageEvent)), - receiveMessage: Effect.never, - pollMessage: Effect.sync(() => self.pollCompiledMessage()), - completeMessage: (delivery) => self.completeCompiledMessage(delivery), - state: Effect.sync(() => self.current.snapshot.state), - setState: (state: unknown) => self.setActiveState(state), - updateState: (f) => self.updateState(f) - } - } else { - self.compiledContext = new CompiledProcessContextImpl(self.processScope, self.childRuntime.owned, self) - if ("executionState" in initialized) { - self.compiledContext.executionState = initialized.executionState - } - } + self.prepareRun(initialized) if (self.options.onReadySync !== undefined && !self.options.onReadySync(self)) { yield* self.requestTermination({ _tag: "Stopped" }) @@ -470,14 +474,13 @@ class CompiledProcess implements MachineRef { // first drain to perform. Future sends observe an idle run state and // start the ordinary compiled worker. if ( - initialized.done === false && self.execution.childless && + initialized.done === false && self.childless && self.lifecycle === "Active" && self.mailbox.items === undefined ) { return self } - self.runState = "Draining" - yield* self.drainRuntime() + yield* self.run() return self }) } @@ -520,7 +523,7 @@ class CompiledProcess implements MachineRef { return this.childRuntime.changes(child) } - private requestTermination(requested: CompiledTermination): Effect.Effect { + protected requestTermination(requested: CompiledTermination): Effect.Effect { return Effect.sync(() => this.requestTerminationSync(requested)) } @@ -528,7 +531,7 @@ class CompiledProcess implements MachineRef { return this.lifecycle === "TerminationRequested" } - private requestTerminationSync(requested: CompiledTermination): boolean { + protected requestTerminationSync(requested: CompiledTermination): boolean { if (this.lifecycle !== "Active") { return false } @@ -554,7 +557,7 @@ class CompiledProcess implements MachineRef { return snapshot } - private stopFromProcess(): Effect.Effect { + protected stopFromProcess(): Effect.Effect { const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid) return this.runState === "Initializing" ? request : request.pipe(Effect.andThen(Effect.interrupt)) } @@ -578,7 +581,7 @@ class CompiledProcess implements MachineRef { if (this.inspector === undefined) return this.offerMessage(event, "Sent") return Effect.suspend((): Effect.Effect => { if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) - const decoded = decodeSent(this.execution.decodeEvent, event) + const decoded = decodeSent(this.decodeEvent, event) return decoded._tag === "Rejected" ? Effect.fail(decoded.error) : this.offerEvent(decoded.event, undefined, undefined, undefined, event) @@ -595,11 +598,11 @@ class CompiledProcess implements MachineRef { return this.offerMessage(event, "Delivered") as Effect.Effect } return Effect.suspend(() => - this.offerEvent(decodeDelivered(this.execution.decodeEvent, event), source, causedBy, undefined, sentOf(event)) + this.offerEvent(decodeDelivered(this.decodeEvent, event), source, causedBy, undefined, sentOf(event)) ) } - private sendAcknowledgedEffect( + protected sendAcknowledgedEffect( event: unknown, sent: unknown = event ): Effect.Effect, unknown | StoppedError> { @@ -657,7 +660,7 @@ class CompiledProcess implements MachineRef { return Effect.fail(new StoppedError()) } let message = offered - const decode = this.execution.decodeEvent + const decode = this.decodeEvent if (decoding !== "Decoded" && decode !== undefined) { // Decoded inline, so a send allocates nothing more than before. try { @@ -673,13 +676,11 @@ class CompiledProcess implements MachineRef { this.offerRevision += 1 // Initialization drains whatever it queued once it finishes, and an // idle machine has an empty mailbox, so it receives the message directly. - const drain = this.execution.drain const context = this.compiledContext - const runSync = this.runState === "Idle" && context !== undefined && drain._tag === "Owned" - ? drain.runSync - : undefined + const drain = this.runState === "Idle" && context !== undefined ? this.execution.drain : undefined + const runSync = drain?._tag === "Owned" ? drain.runSync : undefined if (runSync === undefined) { - offerCompactMailbox(this.mailbox, message) + this.enqueue(message) } if (this.runState !== "Idle") { return Effect.void @@ -766,7 +767,7 @@ class CompiledProcess implements MachineRef { private finishIdleChildlessStop(): boolean { if ( - !this.execution.childless || this.runState !== "Idle" || this.worker !== undefined || + !this.childless || this.runState !== "Idle" || this.worker !== undefined || this.lifecycle !== "Active" || (this.options.onOutcome !== undefined && this.options.skipStoppedOutcome !== true) || this.options.onStop !== undefined || @@ -784,7 +785,7 @@ class CompiledProcess implements MachineRef { this.lifecycle = "TerminationRequested" this.termination = { _tag: "Stopped" } this.terminationSnapshot = snapshot - closeCompactMailbox(this.mailbox) + this.closeMailbox() this.current = { revision: this.current.revision + 1, terminalizing: true, @@ -808,7 +809,7 @@ class CompiledProcess implements MachineRef { return true } - private settleRequestedTermination(): Effect.Effect { + protected settleRequestedTermination(): Effect.Effect { return Effect.suspend(() => { if (this.runState !== "Draining") { return this.finishRequestedTermination() @@ -850,7 +851,7 @@ class CompiledProcess implements MachineRef { return stopped } - private drainRuntime( + protected drainRuntime( first?: Effect.Effect, unknown, unknown> ): Effect.Effect { const self = this @@ -903,19 +904,21 @@ class CompiledProcess implements MachineRef { ) } - private finishRequestedTermination(): Effect.Effect { + protected finishRequestedTermination(): Effect.Effect { return Effect.suspend(() => { if (this.lifecycle !== "TerminationRequested") { return Effect.void } const requested = this.termination if (requested === undefined) { - return Effect.void + return this.awaitCompletion() } const snapshot = this.terminationSnapshot ?? this.reserveTermination(requested) if (snapshot === undefined) { return this.awaitCompletion() } + // One caller finishes the process; any other awaits its completion. + this.termination = undefined const exit = requested._tag === "Stopped" ? Exit.void : requested._tag === "Done" @@ -953,7 +956,7 @@ class CompiledProcess implements MachineRef { ) return Effect.uninterruptible( Effect.sync(() => { - closeCompactMailbox(this.mailbox) + this.closeMailbox() }).pipe( Effect.andThen(this.childRuntime.close(exit)), Effect.andThen(this.setAndPublishSnapshot(snapshot)), @@ -1094,7 +1097,7 @@ class CompiledProcess implements MachineRef { }) } - private setActiveState(state: unknown): Effect.Effect { + protected setActiveState(state: unknown): Effect.Effect { return Effect.suspend(() => this.commitActiveState(state) ?? Effect.void) } @@ -1123,7 +1126,7 @@ class CompiledProcess implements MachineRef { return this.commitActiveState(state, true) } - private commitActiveState(state: unknown, batchChanges = false): Effect.Effect | undefined { + protected commitActiveState(state: unknown, batchChanges = false): Effect.Effect | undefined { const latest = this.current if (latest.terminalizing || latest.snapshot.status !== "active") { return undefined @@ -1196,7 +1199,7 @@ class CompiledProcess implements MachineRef { PubSub.publishUnsafe(current.changes, pendingChanges) } - private updateState( + protected updateState( f: (state: unknown) => Effect.Effect ): Effect.Effect { return Effect.suspend(() => { @@ -1274,13 +1277,184 @@ class CompiledProcess implements MachineRef { } } +/** A machine: its compiled execution drains its mailbox. */ +class MachineProcess extends LocalProcess { + [acknowledgedSend]( + event: unknown + ): Effect.Effect, unknown | StoppedError> { + return Effect.suspend(() => { + if (this.mailbox.closed || this.lifecycle !== "Active") return Effect.fail(new StoppedError()) + const decoded = decodeSent(this.decodeEvent, event) + return decoded._tag === "Rejected" + ? Effect.fail(decoded.error) + : this.sendAcknowledgedEffect(decoded.event, event) + }) + } + + protected readonly initializedRunState: CompiledRunState = "Idle" + + protected makeChildRuntime(): ChildRuntime { + return makeChildRuntimeSync( + this.address, + this.options.runtime, + this.services, + (event) => this.sendAcknowledgedEffect(decodeDelivered(this.decodeEvent, event), sentOf(event)) + ) + } + + protected prepareRun(initialized: object): void { + if (this.execution.drain._tag === "Process") { + this.processContext = { + ...this.processScope, + receive: Effect.never, + poll: Effect.sync(() => Option.map(pollCompactMailbox(this.mailbox), messageEvent)), + receiveMessage: Effect.never, + pollMessage: Effect.sync(() => this.pollCompiledMessage()), + completeMessage: (delivery) => this.completeCompiledMessage(delivery), + state: Effect.sync(() => this.current.snapshot.state), + setState: (state: unknown) => this.setActiveState(state), + updateState: (f) => this.updateState(f) + } + } else { + this.prepareCompiledContext(initialized) + } + } + + protected run(): Effect.Effect { + this.runState = "Draining" + return this.drainRuntime() + } +} + +/** + * Logic other than a machine, run as a resident program: it starts in the + * turn of its starter, receives from the mailbox, and its exit ends the + * process. Its state is updated one change at a time. + */ +class LogicProcess extends LocalProcess { + // A resident program runs from the end of its startup until it exits, so + // the process never rests idle and every send only enqueues. + protected readonly initializedRunState: CompiledRunState = "Initializing" + protected override readonly mailbox: ProcessMailbox = makeProcessMailbox() + private updates: Semaphore.Semaphore | undefined + + protected makeChildRuntime(): ChildRuntime { + return makeChildRuntimeSync(this.address, this.options.runtime) + } + + protected override enqueue(message: ProcessMessage): void { + offerProcessMailbox(this.mailbox, message) + } + + protected override closeMailbox(): void { + closeProcessMailbox(this.mailbox) + } + + /** + * Initialization finishes constructing a state before a stopped snapshot can + * be published, so a stop requested there is recorded and returns. Once + * running, the process that stops itself never continues: the program is + * interrupted, and the caller waits until it is. + */ + protected override stopFromProcess(): Effect.Effect { + const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid) + return this.runState === "Initializing" + ? request + : request.pipe( + Effect.andThen(Effect.forkDetach(this.settleRequestedTermination())), + Effect.andThen(Effect.never) + ) + } + + protected prepareRun(): void { + const inspected = this.inspector !== undefined + const receive = receiveProcessMailbox(this.mailbox) + const poll = Effect.sync(() => pollCompactMailbox(this.mailbox)) + this.processContext = { + ...this.processScope, + receive: inspected + ? Effect.map(receive, (message) => messageEvent(this.inFlightMessage = message)) + : Effect.map(receive, messageEvent), + poll: inspected + ? Effect.map(poll, (message) => { + if (Option.isSome(message)) this.inFlightMessage = message.value + return Option.map(message, messageEvent) + }) + : Effect.map(poll, Option.map(messageEvent)), + state: Effect.sync(() => this.current.snapshot.state), + setState: (state: unknown) => this.serialized(Effect.suspend(() => this.changeState(state))), + updateState: (f) => + this.serialized(Effect.suspend(() => { + const observed = this.current + if (observed.terminalizing || observed.snapshot.status !== "active") return Effect.void + return Effect.flatMap(f(observed.snapshot.state), (state) => this.changeState(state)) + })) + } + } + + /** Changes of state wait for an update in progress, as one change at a time. */ + private serialized(effect: Effect.Effect): Effect.Effect { + return (this.updates ??= Semaphore.makeUnsafe(1)).withPermits(1)(effect) + } + + /** Commits a state, reported as a change of state of logic that is not a machine. */ + private changeState(state: unknown): Effect.Effect { + const before = this.current + const published = this.commitActiveState(state) + const inspector = this.inspector + if ( + inspector !== undefined && this.current !== before && this.logic.inspection?.kind !== "Machine" + ) { + const message = this.inFlightMessage + inspector.publishUnsafe({ + _tag: "StateChanged", + subject: this.inspectionSubject!, + before: before.snapshot.state, + after: state, + causedByDeliveryId: message !== undefined && isAcknowledgedMessage(message) + ? message.inspection?.deliveryId + : undefined + }) + } + return published ?? Effect.void + } + + protected run(): Effect.Effect { + return Effect.suspend(() => { + if (this.lifecycle !== "Active") return this.finishRequestedTermination() + this.runState = "Draining" + const program = Effect.uninterruptibleMask((restore) => + restore(Effect.suspend(() => this.logic.run(this.processContext!))).pipe( + Effect.exit, + Effect.flatMap((exit) => { + this.requestTerminationSync( + Exit.isFailure(exit) ? { _tag: "Failure", cause: exit.cause } : { _tag: "Done", output: exit.value } + ) + return this.finishRequestedTermination() + }) + ) + ) + // The program starts in the caller's turn and runs until it first + // suspends, so a process started while an event is processed begins its + // work before that event's sender continues. + const fork = this.options.detached === true + ? Effect.forkDetach(program, { startImmediately: true }) + : Effect.forkChild(program, { startImmediately: true }) + return Effect.flatMap(fork, (fiber) => + Effect.sync(() => { + if (fiber.pollUnsafe() === undefined) this.worker = fiber + })) + }) + } +} + class CompiledProcessContextImpl implements CompiledProcessContext { executionState: unknown constructor( readonly scope: ProcessInitialContext, readonly ownedChildren: OwnedChildRuntime, - private readonly process: CompiledProcess + private readonly process: LocalProcess ) {} poll(): Option.Option { @@ -1319,12 +1493,14 @@ export const startCompactCompiledInternal: StartProcess = Effect.fnUntraced(func ) { const sessionId = options.sessionId ?? (yield* options.runtime.nextSessionId) const services = yield* Effect.context() - const execution = logic.execution as CompiledProcessExecution - const process = new CompiledProcess(logic, options, services, sessionId) + const execution = logic.execution?._tag === "Compiled" ? logic.execution : undefined + const process = logic.execution?._tag === "Compiled" + ? new MachineProcess(logic, options, services, sessionId) + : new LogicProcess(logic, options, services, sessionId) // A compiled initializer is synchronous by construction. Only startup // callbacks that themselves return Effects need the generic initialization // program; the compiled drain is still provided the complete service context. - const initialize = execution.initialSync !== undefined && + const initialize = execution?.initialSync !== undefined && options.onReady === undefined && options.onSnapshot === undefined ? process.initializeCompiledSync() : process.initialize() @@ -1345,7 +1521,7 @@ export const startCompactCompiledInternal: StartProcess = Effect.fnUntraced(func /** Preserves synchronous startup for owned compiled children. */ export const startCompiledSync: ProcessRuntime["startCompiledSync"] = (logic, options, services, sessionId) => - new CompiledProcess(logic, options, services, sessionId).initializeCompiledSync() + new MachineProcess(logic, options, services, sessionId).initializeCompiledSync() type CompiledTermination = | { readonly _tag: "Stopped" } diff --git a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts b/packages/effect-machine/src/internal/machine/runtimeGeneric.ts deleted file mode 100644 index 4124b2fb..00000000 --- a/packages/effect-machine/src/internal/machine/runtimeGeneric.ts +++ /dev/null @@ -1,862 +0,0 @@ -/** General Effect process worker and supervisor strategy. */ -import * as Cause from "effect/Cause" -import * as Channel from "effect/Channel" -import * as Deferred from "effect/Deferred" -import * as Effect from "effect/Effect" -import * as Exit from "effect/Exit" -import * as Fiber from "effect/Fiber" -import * as Option from "effect/Option" -import * as PubSub from "effect/PubSub" -import * as Stream from "effect/Stream" -import * as SynchronizedRef from "effect/SynchronizedRef" -import type * as Take from "effect/Take" -import type { Inspection } from "../../LocalMachine.js" -import { type ChildSelector } from "./childRegistry.js" -import { type MachineSchemaDecodeError, StoppedError } from "./errors.js" -import * as InspectionRuntime from "./inspectionRuntime.js" -import { classifyOutcome } from "./observation.js" -import { - type AcknowledgedDelivery, - AcknowledgedMessageTypeId, - acknowledgedSend, - childlessRuntime, - closeProcessMailbox, - decodeDelivered, - decodeSent, - type Deliverable, - deliverEvent, - executionIsChildless, - failAcknowledgedMessage, - type InspectedOffer, - inspectionSubject, - isAcknowledgedMessage, - isMachineTarget, - type MachineRef, - makeChildRuntime, - makeEmissionRuntime, - makeInspectedMessage, - makeProcessMailbox, - messageCausation, - messageEvent, - noCausation, - noInspectInitial, - noParentSend, - notifyActiveSnapshot, - offerProcessMailbox, - pollCompactMailbox, - type ProcessEndpoint, - type ProcessInitialContext, - type ProcessLogic, - type ProcessMessage, - type ProcessRunContext, - publishInspectedSent, - receiveProcessMailbox, - type RuntimeSnapshot, - sendEndpoint, - sendMachineTarget, - type StartInternalOptions, - type StartProcess, - stopAcknowledgedMessage, - succeedAcknowledgedMessage, - type VersionedSnapshot -} from "./runtimeProtocol.js" - -// `Machine.logic` permits an arbitrary Effect program, including programs that -// suspend or supervise their own fibers. Keep its two-fiber worker/supervisor -// protocol as the general contract rather than weakening it for statecharts. -export const startGenericInternal: StartProcess = Effect.fnUntraced( - function*( - logic: ProcessLogic, - options: StartInternalOptions - ) { - const { - detached, - id: requestedId, - onOutcome, - onReady, - onReadySync, - onSnapshot, - onStop, - onStopSync, - parent, - runtime, - sendParent: overrideSendParent - } = options - type ProcessTermination = - | { readonly _tag: "Stopped" } - | { readonly _tag: "Done"; readonly output: Output } - | { readonly _tag: "Failure"; readonly cause: Cause.Cause } - - const sessionId = options.sessionId ?? (yield* runtime.nextSessionId) - const id = requestedId ?? sessionId - const inspector = runtime.inspection - const subject = inspector === undefined ? undefined : inspectionSubject(logic, id, sessionId) - const programInvocation: Inspection.ProgramInvocation | undefined = - inspector === undefined || options.programInvocation === undefined - ? undefined - : { ...options.programInvocation, sessionId } - let initialEntryPaths: ReadonlyArray | undefined - let initialMicrosteps: ReadonlyArray | undefined - const mailbox = makeProcessMailbox() - const emissions = options.emissions ?? makeEmissionRuntime() - const termination = yield* Deferred.make() - const done = yield* Deferred.make() - const awaitCompletion = Deferred.await(done).pipe(Effect.exit, Effect.asVoid) - let initializing = true - let inFlightMessage: ProcessMessage | undefined - const requestStop = Deferred.succeed(termination, { _tag: "Stopped" }).pipe(Effect.asVoid) - const offerDirect = ( - message: ProcessMessage, - onAccepted?: () => void - ): Effect.Effect => - Effect.suspend(() => - offerProcessMailbox(mailbox, message, onAccepted) ? Effect.void : Effect.fail(new StoppedError()) - ) - // A machine decodes an event as it enters the mailbox; other logic takes - // its events as they are. Logic that neither decodes nor is inspected - // offers directly, without the closures below. - const decodeEvent = logic.execution?._tag === "Compiled" ? logic.execution.decodeEvent : undefined - const direct = inspector === undefined && decodeEvent === undefined - const offerEvent = direct ? undefined! : ( - event: Event, - source: Inspection.Subject | undefined, - causedBy: Inspection.Causation | undefined, - deferred: Deferred.Deferred, unknown> | undefined, - sent: unknown - ): Effect.Effect => - Effect.suspend(() => { - if (inspector === undefined) { - return offerDirect( - deferred === undefined ? event : { [AcknowledgedMessageTypeId]: true as const, event, deferred } - ) - } - const message: ProcessMessage = inspector.isActive() - ? makeInspectedMessage(inspector, subject!, event, source, causedBy, deferred, sent) - : deferred === undefined - ? event - : { [AcknowledgedMessageTypeId]: true as const, event, deferred } - return offerDirect(message, () => publishInspectedSent(inspector, subject!, message)) - }) - // A delivery from work, a child, a parent or a command of another machine: - // a refused event fails this machine when it is planned. - const deliver: InspectedOffer = direct - ? undefined! - : decodeEvent === undefined - ? (event, source, causedBy) => offerEvent(event, source, causedBy, undefined, event) - : (event, source, causedBy) => - Effect.suspend(() => - offerEvent(decodeDelivered(decodeEvent, event) as Event, source, causedBy, undefined, event) - ) - // A public `send` of a machine rejects an event that the schema refuses, - // and the machine keeps running. A machine that has ended rejects first. - const sendPublic: ((event: Event) => Effect.Effect) | undefined = - decodeEvent === undefined ? - undefined : - (event) => - Effect.suspend((): Effect.Effect => { - if (mailbox.closed) return Effect.fail(new StoppedError()) - const decoded = decodeSent(decodeEvent, event) - return decoded._tag === "Rejected" - ? Effect.fail(decoded.error) - : offerEvent(decoded.event as Event, undefined, undefined, undefined, event) - }) - const offerInspected: InspectedOffer | undefined = inspector === undefined ? undefined : deliver - const sendAcknowledged: - | ((event: Event) => Effect.Effect, Error | StoppedError>) - | undefined = logic.execution?._tag !== "Compiled" - ? undefined - : (event) => - Effect.uninterruptibleMask((restore) => - Deferred.make, unknown>().pipe( - Effect.flatMap((deferred) => { - const offered = offerEvent( - decodeEvent === undefined ? event : decodeDelivered(decodeEvent, event) as Event, - undefined, - undefined, - deferred, - event - ) - return offered.pipe(Effect.andThen(restore(Deferred.await(deferred)))) - }), - Effect.map((delivery) => delivery as AcknowledgedDelivery) - ) - ) as Effect.Effect, Error | StoppedError> - - const self: ProcessEndpoint = { - id, - sessionId, - // Initialization must finish constructing a state before a stopped - // snapshot can be published. A stop requested there is therefore recorded - // and returns so initialization can finish. Once running, the requesting - // process waits forever and is interrupted by the supervisor after the - // stop request wins, so execution never continues after `self.stop`. - stop: Effect.suspend(() => - initializing - ? requestStop - : requestStop.pipe(Effect.andThen(Effect.never)) - ), - send: direct - ? (event) => offerDirect(event) - : (event) => deliver(event, undefined, undefined), - ...(inspector === undefined - ? undefined - : { inspectionSubject: subject!, sendInspected: offerInspected! }) - } - - let { - changes: childChanges, - close: closeChildren, - get: getChild, - owned: ownedChildren, - sendTo, - spawn, - stop: stopChild - } = childlessRuntime - if (!executionIsChildless(logic.execution)) { - ;({ - changes: childChanges, - close: closeChildren, - get: getChild, - owned: ownedChildren, - sendTo, - spawn, - stop: stopChild - } = yield* makeChildRuntime( - self, - runtime, - undefined, - sendAcknowledged === undefined ? undefined : (event) => sendAcknowledged(event as Event) - )) - } - const cleanupStartupFailure = (exit: Exit.Exit): Effect.Effect => { - if (Exit.isSuccess(exit)) return Effect.void - if (inspector !== undefined) { - inspector.publishUnsafe( - programInvocation === undefined - ? { _tag: "StartFailed", subject: subject!, cause: exit.cause } - : { - _tag: "ProgramInvocationStopped", - subject: programInvocation.owner, - invocation: programInvocation, - exit - } - ) - } - return closeChildren(exit).pipe( - Effect.andThen(emissions.close()), - Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void) - ) - } - const cleanup = onStopSync === undefined ? onStop ?? Effect.void : Effect.sync(() => onStopSync(ref)) - const currentCausation = inspector === undefined - ? noCausation - : (): Inspection.Causation | undefined => messageCausation(inFlightMessage, initializing) - const sendParent = overrideSendParent ?? (parent === undefined - ? noParentSend - : inspector === undefined - ? parent.send - : (event) => sendEndpoint(parent, event, subject, currentCausation())) - const emit = inspector === undefined - ? emissions.emit - : (event: unknown) => - emissions.emit(event).pipe( - Effect.tap(() => - Effect.sync(() => - inspector.publishUnsafe({ - _tag: "Emitted", - subject: subject!, - emission: event, - causedBy: currentCausation() - }) - ) - ) - ) - const sendToTarget: ProcessInitialContext["sendTo"] = inspector === undefined - ? ((target: unknown, event: unknown) => - isMachineTarget(target) - ? sendMachineTarget(target, event, undefined, undefined) - : sendTo(target as ChildSelector, event)) as ProcessInitialContext["sendTo"] - : ((target: unknown, event: unknown) => - isMachineTarget(target) - ? sendMachineTarget(target, event, subject, currentCausation()) - : sendTo(target as ChildSelector, event, subject, currentCausation())) as ProcessInitialContext< - Event - >["sendTo"] - - const scope: ProcessInitialContext = { - self, - parent, - spawn, - sendParent, - emit, - sendTo: sendToTarget, - stopChild, - failCause: (cause) => - Deferred.succeed(termination, { - _tag: "Failure", - cause: cause as Cause.Cause - }).pipe(Effect.asVoid), - inspectInitial: inspector === undefined - ? noInspectInitial - : (paths, microsteps = []) => { - initialEntryPaths = paths - initialMicrosteps = microsteps - } - } - - if (inspector !== undefined) { - inspector.publishUnsafe( - programInvocation === undefined - ? { - _tag: "Created", - subject: subject!, - parent: parent?.inspectionSubject, - origin: options.origin ?? { _tag: "Root" }, - definition: logic.inspection?.definition - } - : { _tag: "ProgramInvocationStarted", subject: programInvocation.owner, invocation: programInvocation } - ) - } - - const initial = yield* logic.initial(scope).pipe( - Effect.onExit(cleanupStartupFailure), - Effect.ensuring(Effect.sync(() => { - initializing = false - })) - ) - const current = yield* SynchronizedRef.make>({ - revision: 0, - terminalizing: false, - changes: undefined, - snapshot: { - status: "active", - state: initial - } - }) - if (programInvocation === undefined) { - inspector?.publishUnsafe({ - _tag: "Initialized", - subject: subject!, - snapshot: { status: "active", state: initial }, - initialEntryPaths: initialEntryPaths ?? [], - microsteps: InspectionRuntime.microsteps({ microsteps: initialMicrosteps ?? [] }) - }) - } - const publishSnapshot: ( - snapshot: VersionedSnapshot - ) => Effect.Effect> = onSnapshot === undefined - ? (snapshot) => - snapshot.changes === undefined - ? Effect.succeed(snapshot) - : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot)) - : (snapshot) => { - const publish = snapshot.changes === undefined - ? Effect.succeed(snapshot) - : PubSub.publish(snapshot.changes, [snapshot] as const).pipe(Effect.as(snapshot)) - const runtimeSnapshot = snapshot.snapshot - return runtimeSnapshot.status !== "active" - ? publish - : publish.pipe(Effect.tap(() => notifyActiveSnapshot(onSnapshot, runtimeSnapshot))) - } - - const completeChanges = ( - snapshot: VersionedSnapshot - ): Effect.Effect => - snapshot.changes === undefined - ? Effect.void - : PubSub.publish(snapshot.changes, Exit.succeed(undefined)).pipe(Effect.asVoid) - - const completeIfTerminal = ( - snapshot: VersionedSnapshot - ): Effect.Effect> => { - if (snapshot.snapshot.status === "active") { - return Effect.succeed(snapshot) - } - return completeChanges(snapshot).pipe(Effect.as(snapshot)) - } - - const publishIfCurrent = ( - snapshot: VersionedSnapshot - ): Effect.Effect | undefined> => - SynchronizedRef.get(current).pipe( - Effect.flatMap(( - currentSnapshot - ): Effect.Effect | undefined> => - currentSnapshot.revision === snapshot.revision - ? publishSnapshot(snapshot).pipe(Effect.flatMap(completeIfTerminal)) - : Effect.succeed(undefined) - ) - ) - - type SnapshotModification = readonly [ - VersionedSnapshot | undefined, - VersionedSnapshot - ] - - const updateSnapshot = ( - f: ( - snapshot: RuntimeSnapshot - ) => Effect.Effect | undefined, E2, R2> - ): Effect.Effect | undefined, E2, R2> => - SynchronizedRef.modifyEffect( - current, - (current) => - current.terminalizing - ? Effect.succeed([undefined, current] as const) - : Effect.map( - f(current.snapshot), - (next) => { - if (next === undefined) { - return [undefined, current] as const - } - const versioned = { - revision: current.revision + 1, - snapshot: next, - terminalizing: false, - changes: current.changes - } - return [versioned, versioned] as const - } - ) - ).pipe( - Effect.flatMap((versioned) => - versioned === undefined ? Effect.succeed(undefined) : publishIfCurrent(versioned) - ), - Effect.map((published) => published?.snapshot) - ) - - const reserveTerminalSnapshot = ( - f: ( - snapshot: Extract, { readonly status: "active" }> - ) => RuntimeSnapshot - ): Effect.Effect | undefined> => - SynchronizedRef.modify( - current, - (current): SnapshotModification => { - if (current.terminalizing || current.snapshot.status !== "active") { - return [undefined, current] - } - return [ - { - revision: current.revision + 1, - snapshot: f(current.snapshot), - terminalizing: true, - changes: current.changes - }, - { ...current, terminalizing: true } - ] - } - ).pipe(Effect.map((versioned) => versioned?.snapshot)) - - const setAndPublishSnapshot = ( - snapshot: RuntimeSnapshot - ): Effect.Effect => - SynchronizedRef.updateAndGet(current, (current) => ({ - revision: current.revision + 1, - snapshot, - terminalizing: true, - changes: current.changes - })).pipe( - Effect.flatMap(publishSnapshot), - Effect.flatMap(completeIfTerminal), - Effect.asVoid - ) - - const setActiveStateDirect = (state: State) => - updateSnapshot((snapshot) => - Effect.succeed( - snapshot.status === "active" - ? { - status: "active", - state - } - : undefined - ) - ).pipe(Effect.asVoid) - - const setActiveState = inspector === undefined ? - setActiveStateDirect : - (state: State) => - SynchronizedRef.get(current).pipe( - Effect.flatMap((before) => - updateSnapshot((snapshot) => - Effect.succeed( - snapshot.status === "active" - ? { - status: "active", - state - } - : undefined - ) - ).pipe( - Effect.tap((after) => - Effect.sync(() => { - if (logic.inspection?.kind === "Machine" || after === undefined) return - inspector.publishUnsafe({ - _tag: "StateChanged", - subject: subject!, - before: before.snapshot.state, - after: state, - causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage) - ? inFlightMessage.inspection?.deliveryId - : undefined - }) - }) - ) - ) - ), - Effect.asVoid - ) - - const terminalizeWith = ( - snapshot: RuntimeSnapshot, - exit: Exit.Exit, - completeDone: Effect.Effect - ): Effect.Effect => { - const notifyOutcome = - onOutcome === undefined || (snapshot.status === "stopped" && options.skipStoppedOutcome === true) - ? Effect.void - : Effect.suspend(() => onOutcome(classifyOutcome(snapshot)!)).pipe( - Effect.exit, - Effect.asVoid - ) - const closeEmissionsAndInspect = inspector === undefined - ? emissions.close() - : emissions.close().pipe( - Effect.andThen(Effect.sync(() => - inspector.publishUnsafe( - programInvocation === undefined - ? { _tag: "Terminated", subject: subject!, snapshot } - : { - _tag: "ProgramInvocationStopped", - subject: programInvocation.owner, - invocation: programInvocation, - exit: snapshot.status === "stopped" ? Exit.interrupt() : exit - } - ) - )) - ) - return Effect.uninterruptible( - Effect.sync(() => closeProcessMailbox(mailbox)).pipe( - Effect.andThen(closeChildren(exit)), - Effect.andThen(setAndPublishSnapshot(snapshot)), - Effect.andThen(closeEmissionsAndInspect), - Effect.andThen(Effect.sync(() => { - if (Exit.isFailure(exit)) { - failAcknowledgedMessage(inFlightMessage, exit.cause) - } else { - stopAcknowledgedMessage(inFlightMessage) - } - inFlightMessage = undefined - })), - Effect.andThen(notifyOutcome), - Effect.andThen(cleanup), - Effect.andThen(options.inspectionRoot === true && inspector !== undefined ? inspector.close : Effect.void), - Effect.andThen(completeDone) - ) - ) - } - - const reserveStoppedSnapshot = reserveTerminalSnapshot((snapshot) => ({ - status: "stopped", - state: snapshot.state - })) - - const reserveFailureSnapshot = (cause: Cause.Cause) => - reserveTerminalSnapshot((snapshot) => ({ - status: "failed", - state: snapshot.state, - cause - })) - - const reserveSuccessSnapshot = (output: Output) => - reserveTerminalSnapshot((snapshot) => ({ - status: "done", - state: snapshot.state, - output - })) - - const terminalizeReservedStop = ( - snapshot: RuntimeSnapshot - ): Effect.Effect => { - const exit = Exit.void - return terminalizeWith( - snapshot, - exit, - Deferred.fail(done, new StoppedError()) - ) - } - - const terminalizeReservedFailure = ( - snapshot: RuntimeSnapshot, - cause: Cause.Cause - ): Effect.Effect => { - const exit = Exit.failCause(cause) - return terminalizeWith(snapshot, exit, Deferred.failCause(done, cause)) - } - - const terminalizeReservedSuccess = ( - snapshot: RuntimeSnapshot, - output: Output - ): Effect.Effect => { - const exit = Exit.succeed(output) - return terminalizeWith(snapshot, exit, Deferred.succeed(done, output)) - } - - const stop: Effect.Effect = Effect.uninterruptible( - requestStop.pipe(Effect.andThen(awaitCompletion)) - ) - - const acknowledgedContext: - | Pick< - ProcessRunContext, - "receiveMessage" | "pollMessage" | "completeMessage" - > - | undefined = logic.execution?._tag !== "Compiled" ? undefined : { - receiveMessage: receiveProcessMailbox(mailbox).pipe( - Effect.tap((message) => - Effect.sync(() => { - inFlightMessage = isAcknowledgedMessage(message) ? message : undefined - }) - ) - ), - pollMessage: Effect.sync(() => pollCompactMailbox(mailbox)).pipe( - Effect.tap((message) => - Effect.sync(() => { - if (Option.isSome(message)) { - inFlightMessage = isAcknowledgedMessage(message.value) ? message.value : undefined - } - }) - ) - ), - completeMessage: (delivery) => { - succeedAcknowledgedMessage(inFlightMessage, delivery) - inFlightMessage = undefined - } - } - const receive = inspector === undefined || logic.execution?._tag === "Compiled" - ? receiveProcessMailbox(mailbox).pipe(Effect.map(messageEvent)) - : receiveProcessMailbox(mailbox).pipe( - Effect.tap((message) => - Effect.sync(() => { - inFlightMessage = message - }) - ), - Effect.map(messageEvent) - ) - const poll = inspector === undefined || logic.execution?._tag === "Compiled" - ? Effect.sync(() => pollCompactMailbox(mailbox)).pipe(Effect.map(Option.map(messageEvent))) - : Effect.sync(() => pollCompactMailbox(mailbox)).pipe( - Effect.tap((message) => - Effect.sync(() => { - if (Option.isSome(message)) inFlightMessage = message.value - }) - ), - Effect.map(Option.map(messageEvent)) - ) - const updateStateDirect = (f: (state: State) => Effect.Effect) => - updateSnapshot((snapshot) => - snapshot.status === "active" - ? f(snapshot.state).pipe( - Effect.map((state) => ({ - status: "active" as const, - state - })) - ) - : Effect.succeed(undefined) - ).pipe(Effect.asVoid) - const updateState: ProcessRunContext["updateState"] = inspector === undefined - ? updateStateDirect - : (f) => - SynchronizedRef.get(current).pipe( - Effect.flatMap((before) => - updateSnapshot((snapshot) => - snapshot.status === "active" - ? f(snapshot.state).pipe( - Effect.map((state) => ({ - status: "active" as const, - state - })) - ) - : Effect.succeed(undefined) - ).pipe( - Effect.tap((after) => - Effect.sync(() => { - if (logic.inspection?.kind === "Machine" || after?.status !== "active") return - inspector.publishUnsafe({ - _tag: "StateChanged", - subject: subject!, - before: before.snapshot.state, - after: after.state, - causedByDeliveryId: inFlightMessage !== undefined && isAcknowledgedMessage(inFlightMessage) - ? inFlightMessage.inspection?.deliveryId - : undefined - }) - }) - ) - ) - ), - Effect.asVoid - ) - const context: ProcessRunContext = { - ...scope, - ...(logic.execution?._tag === "Compiled" && !logic.execution.childless ? { ownedChildren } : undefined), - ...acknowledgedContext, - receive, - poll, - state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)), - setState: setActiveState, - updateState - } - - const getOrCreateChanges = SynchronizedRef.modifyEffect( - current, - (current) => { - if (current.snapshot.status !== "active") { - return Effect.succeed([undefined, current] as const) - } - if (current.changes !== undefined) { - return Effect.succeed([current.changes, current] as const) - } - return PubSub.unbounded>>({ replay: 1 }).pipe( - Effect.map((changes) => [changes, { ...current, changes }] as const) - ) - } - ) - - const changesStream: Stream.Stream> = Stream.unwrap( - Effect.gen(function*() { - const changes = yield* getOrCreateChanges - if (changes === undefined) { - return Stream.succeed((yield* SynchronizedRef.get(current)).snapshot) - } - const subscription = yield* PubSub.subscribe(changes) - const captured = yield* SynchronizedRef.get(current) - if (captured.snapshot.status !== "active") { - return Stream.succeed(captured.snapshot) - } - return Stream.succeed(captured.snapshot).pipe( - Stream.concat( - Stream.fromChannel(Channel.fromEffectTake(PubSub.take(subscription))).pipe( - Stream.filter((next) => next.revision > captured.revision), - Stream.map((next) => next.snapshot) - ) - ) - ) - }) - ) - - const ref: MachineRef = { - id, - sessionId, - ...(inspector === undefined - ? undefined - : { inspectionSubject: subject!, sendInspected: offerInspected! }), - state: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot.state)), - snapshot: SynchronizedRef.get(current).pipe(Effect.map((current) => current.snapshot)), - changes: changesStream, - emissions: emissions.stream as Stream.Stream, - join: Deferred.await(done), - stop, - send: sendPublic ?? self.send, - ...(decodeEvent === undefined ? undefined : { [deliverEvent]: deliver as Deliverable[typeof deliverEvent] }), - ...(sendAcknowledged === undefined ? undefined : { - [acknowledgedSend]: (event: Event) => - Effect.suspend( - (): Effect.Effect, Error | StoppedError | MachineSchemaDecodeError> => { - if (decodeEvent === undefined) return sendAcknowledged(event) - if (mailbox.closed) return Effect.fail(new StoppedError()) - const decoded = decodeSent(decodeEvent, event) - return decoded._tag === "Rejected" ? Effect.fail(decoded.error) : sendAcknowledged(event) - } - ) - }), - child: getChild, - childChanges - } - - if (onReadySync !== undefined && !onReadySync(ref)) { - yield* requestStop - } else if (onReady !== undefined) { - yield* onReady(ref, requestStop) - } - if (onSnapshot !== undefined) { - yield* notifyActiveSnapshot(onSnapshot, { status: "active", state: initial }) - } - - const reserveTermination = (termination: ProcessTermination) => { - switch (termination._tag) { - case "Stopped": - return reserveStoppedSnapshot - case "Done": - return reserveSuccessSnapshot(termination.output) - case "Failure": - return reserveFailureSnapshot(termination.cause) - } - } - - const completeTermination = ( - termination: ProcessTermination, - snapshot: RuntimeSnapshot - ) => { - switch (termination._tag) { - case "Stopped": - return terminalizeReservedStop(snapshot) - case "Done": - return terminalizeReservedSuccess(snapshot, termination.output) - case "Failure": - return terminalizeReservedFailure(snapshot, termination.cause) - } - } - - // The worker starts in the caller's turn and runs until it first suspends, - // so a process started while an event is processed, such as an - // invocation, begins its work before that event's sender continues. - const forkRuntime = (effect: Effect.Effect) => - detached === true - ? Effect.forkDetach(effect, { startImmediately: true }) - : Effect.forkChild(effect, { startImmediately: true }) - - const pendingTermination = yield* Deferred.poll(termination) - const worker = Option.isNone(pendingTermination) - ? yield* Effect.uninterruptibleMask((restore) => - restore(Effect.suspend(() => logic.run(context))).pipe( - Effect.exit, - Effect.flatMap((exit) => - Deferred.succeed( - termination, - Exit.isFailure(exit) - ? { _tag: "Failure", cause: exit.cause } - : { _tag: "Done", output: exit.value } - ) - ) - ) - ).pipe(forkRuntime) - : undefined - - // One Deferred arbitrates all terminal causes. The supervisor reserves the - // terminal snapshot before interrupting the worker, so worker finalizers - // cannot mutate the frozen state. It then waits for those finalizers before - // publishing and completing `join` / `stop`. - const runFiber: Effect.Effect = Effect.uninterruptibleMask((restore) => - Effect.gen(function*() { - const requested = Option.isSome(pendingTermination) - ? yield* pendingTermination.value - : yield* restore(Deferred.await(termination)) - - const snapshot = yield* reserveTermination(requested) - if (worker !== undefined) { - yield* Fiber.interrupt(worker) - } - if (snapshot === undefined) { - return yield* awaitCompletion - } - return yield* completeTermination(requested, snapshot) - }) - ) - - yield* forkRuntime(runFiber) - - return ref - } -) diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 67951824..2885eed0 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -36,8 +36,6 @@ import { } from "./childRegistry.js" import { ChildAlreadyExistsError, MachineSchemaDecodeError, StoppedError } from "./errors.js" import * as InspectionRuntime from "./inspectionRuntime.js" -import type * as InvocationEvent from "./invocationEvent.js" -import { InvocationGenerations } from "./invocationGeneration.js" /** @internal */ export const activeSnapshotObserver: unique symbol = Symbol.for("effect/Machine/activeSnapshotObserver") @@ -377,8 +375,6 @@ export interface ProcessRunContext extends ProcessInitialContext( f: (state: State) => Effect.Effect ) => Effect.Effect - /** Present only when a compiled statechart is forced through the generic runtime. @internal */ - readonly ownedChildren?: OwnedChildRuntime } /** @@ -877,14 +873,6 @@ export interface OwnedChildRuntime { source: OwnedChildSource, options: OwnedChildSpawnOptions ) => Effect.Effect - /** - * Begins the generation of an entered invoking state and retires the one it - * replaces. The generation stays current after its children finish and is - * retired only when the state exits, by `stopPaths` or `stopAll`. - */ - readonly beginGeneration: (path: string) => InvocationEvent.Generation - readonly stopAll: () => Effect.Effect - readonly stopPaths: (paths: ReadonlyArray) => Effect.Effect | undefined /** Stops the child that was spawned with `key`, while its owner holds it. */ readonly stopKey: (key: string) => Effect.Effect } @@ -908,9 +896,7 @@ export interface ChildRuntime { readonly owned: OwnedChildRuntime } -// Extends the generation bookkeeping so a running machine retains one object for -// both. -class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildRuntime { +class OwnedChildRuntimeImpl implements OwnedChildRuntime { private scopedServices: Context.Context | undefined constructor( @@ -921,9 +907,7 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR private readonly sendAcknowledged?: ( event: unknown ) => Effect.Effect, unknown | StoppedError> - ) { - super() - } + ) {} private has(key: string): boolean { for (const entry of this.registry.children.values()) { @@ -960,7 +944,6 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR _tag: "Starting", token, ownerKey: options.key, - ownerPath: options.path, ownerActive: true }) const parent: ProcessEndpoint = { @@ -1039,21 +1022,6 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR }) } - stopAll(): Effect.Effect { - return Effect.suspend(() => { - this.retireAllGenerations() - const effects: Array> = [] - for (const entry of this.registry.children.values()) { - if (entry.ownerActive) effects.push(this.stopEntry(entry)) - } - return effects.length === 0 - ? Effect.void - : effects.length === 1 - ? effects[0]! - : Effect.all(effects, { concurrency: "unbounded", discard: true }) - }) - } - stopKey(key: string): Effect.Effect { return Effect.suspend(() => { for (const entry of this.registry.children.values()) { @@ -1062,23 +1030,6 @@ class OwnedChildRuntimeImpl extends InvocationGenerations implements OwnedChildR return Effect.void }) } - - stopPaths(paths: ReadonlyArray): Effect.Effect | undefined { - if (paths.length === 0) return undefined - this.retireGenerations(paths) - const pathSet = new Set(paths) - const effects: Array> = [] - for (const entry of this.registry.children.values()) { - if (entry.ownerActive && entry.ownerPath !== undefined && pathSet.has(entry.ownerPath)) { - effects.push(this.stopEntry(entry)) - } - } - return effects.length === 0 - ? undefined - : effects.length === 1 - ? effects[0]! - : Effect.all(effects, { concurrency: "unbounded", discard: true }) - } } const noChildChanges = Stream.succeed(Option.none()).pipe(Stream.concat(Stream.never)) @@ -1146,10 +1097,6 @@ export const childlessRuntime: ChildRuntime = { stop: () => Effect.void, owned: { spawn: () => Effect.die(new Error("Childless machine logic cannot spawn an owned process")), - // Unreachable for childless logic; `spawn` reports the defect as a failure. - beginGeneration: () => ({ current: true }), - stopAll: () => Effect.void, - stopPaths: () => undefined, stopKey: () => Effect.void } } diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index a4407965..7beace4e 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -21,12 +21,11 @@ * over and may update its storage in place. Both are one implementation, which * differs only in whether a plan copies or updates what it writes. * - * The order is the one of the generic runtime in `process.ts`: commands, the - * work of exited states, the new state, emitted events, and the work of entered - * states. A step calls no user code for the work it lists: each piece of work - * evaluates its source and its input mapper when its host starts it, at most - * once, inside its own startup failure boundary, as `invocationResolution.ts` - * requires of a host. + * A host applies a step in one order, as the local host in `stepHost.ts` + * does: commands, the work of exited states, the new state, emitted events, and + * the work of entered states. A step calls no user code for the work it lists: + * each piece of work evaluates its source and its input mapper when its host + * starts it, at most once, inside its own startup failure boundary. * * @since 0.48.0 */ @@ -229,7 +228,7 @@ export class Planning implements Configuration.PlanningMachineReferences { this.children = children ?? (this as unknown as Children) } - readonly children: Children + readonly children: Children; // A host is compared by identity: hashing a state, as a failure that holds one // may be hashed, never reads the targets of the host. @@ -1119,7 +1118,19 @@ const build = ( } if (ownership === "Persistent") { - return { plan, start, fromSnapshot, rest: (state) => state.resting(), send, sendDecoded, settle, element, report, stop, resume } + return { + plan, + start, + fromSnapshot, + rest: (state) => state.resting(), + send, + sendDecoded, + settle, + element, + report, + stop, + resume + } } // An owned state is taken over by the step it is passed to, and handed back // when the step returns that very state, or refuses the event. diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index e28e6119..38dfe166 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -148,7 +148,9 @@ const current = (): InvocationEvent.Generation => ({ current: true }) /** The exit of work as its step settles it. */ const exitOf = (outcome: InvocationOutcome.Outcome): Exit.Exit => - outcome._tag === "Done" ? Exit.succeed(outcome.output) : Exit.failCause((outcome as { cause: Cause.Cause }).cause) + outcome._tag === "Done" + ? Exit.succeed(outcome.output) + : Exit.failCause((outcome as { cause: Cause.Cause }).cause) const traced = (scope: Scope, invocation: ProgramInvocation, logic: AnyProcessLogic): AnyProcessLogic => ({ ...logic, @@ -202,7 +204,11 @@ const programLogic = (scope: Scope, work: Step.Work, invocation: ProgramInvocati work, element, inspected - ? (InvocationOutcome.decideElement(invocation as InvocationResolution.StreamInvocation, current(), element) as InvocationOutcome.Deliver).event + ? (InvocationOutcome.decideElement( + invocation as InvocationResolution.StreamInvocation, + current(), + element + ) as InvocationOutcome.Deliver).event : undefined ) ).pipe( @@ -393,7 +399,10 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => const afterCommit: Array> = [] if (step.emitted.length > 0) { afterCommit.push( - CommandRuntime.runEmittedEvents(step.emitted, host.liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, scope)) + CommandRuntime.runEmittedEvents( + step.emitted, + host.liveRuntime ??= CommandRuntime.makeLiveRuntime(machine, scope) + ) ) } if (done) { @@ -420,7 +429,9 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => } return beforeCommit.length === 0 ? commitAndContinue() - : context.runAfterChanges(runSequentialDiscard(beforeCommit).pipe(Effect.andThen(Effect.suspend(commitAndContinue)))) + : context.runAfterChanges( + runSequentialDiscard(beforeCommit).pipe(Effect.andThen(Effect.suspend(commitAndContinue))) + ) } // Commits queued messages whose steps need no effectful work. Returns the diff --git a/packages/effect-machine/test/internal/machine/invocation.test.ts b/packages/effect-machine/test/internal/machine/invocation.test.ts deleted file mode 100644 index 1b6f5c22..00000000 --- a/packages/effect-machine/test/internal/machine/invocation.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { assert, describe, it } from "@effect/vitest" -import { Effect } from "effect" -import { makeChildId, makeKey } from "../../../src/internal/machine/invocation.js" -import * as RuntimeProtocol from "../../../src/internal/machine/runtimeProtocol.js" - -describe("machine invocation ownership", () => { - it("keeps path and invoke id boundaries collision-free", () => { - assert.notStrictEqual(makeKey("a", "bc"), makeKey("ab", "c")) - assert.notStrictEqual(makeKey("root.child", "worker"), makeKey("root", ".childworker")) - }) - - it("derives stable child addresses in the invocation namespace", () => { - assert.strictEqual( - makeChildId("root.child", "worker"), - "Machine.invocation:10:root.childworker" - ) - }) - - it.effect("keeps a generation current until its owner path exits", () => - Effect.gen(function*() { - // Generation bookkeeping never reaches the process address or runtime. - const owned = RuntimeProtocol.makeChildRuntimeSync( - {} as RuntimeProtocol.ProcessEndpoint, - {} as RuntimeProtocol.ProcessRuntime - ).owned - const left = owned.beginGeneration("Active.left") - const right = owned.beginGeneration("Active.right") - assert.isTrue(left.current) - assert.isTrue(right.current) - - // Exiting one owner path retires only that path's generation. - yield* owned.stopPaths(["Active.left"]) ?? Effect.void - assert.isFalse(left.current) - assert.isTrue(right.current) - - // Entering a path again begins a distinct generation, and an entry that - // replaces a generation directly also retires it. - const reentered = owned.beginGeneration("Active.left") - assert.notStrictEqual(reentered, left) - assert.isTrue(reentered.current) - const replaced = owned.beginGeneration("Active.left") - assert.isFalse(reentered.current) - assert.isTrue(replaced.current) - - yield* owned.stopAll() - assert.isFalse(replaced.current) - assert.isFalse(right.current) - })) -}) diff --git a/packages/effect-machine/test/internal/machine/invocationOutcome.test.ts b/packages/effect-machine/test/internal/machine/invocationOutcome.test.ts index 0ee914b2..c44ab8db 100644 --- a/packages/effect-machine/test/internal/machine/invocationOutcome.test.ts +++ b/packages/effect-machine/test/internal/machine/invocationOutcome.test.ts @@ -2,7 +2,6 @@ import { assert, describe, it } from "@effect/vitest" import { Cause, Exit } from "effect" import { StoppedError } from "../../../src/internal/machine/errors.js" import * as InvocationEvent from "../../../src/internal/machine/invocationEvent.js" -import { InvocationGenerations } from "../../../src/internal/machine/invocationGeneration.js" import * as InvocationOutcome from "../../../src/internal/machine/invocationOutcome.js" import type * as InvocationResolution from "../../../src/internal/machine/invocationResolution.js" @@ -127,20 +126,3 @@ describe("invocation outcome policy", () => { assert.deepStrictEqual(InvocationOutcome.fromExit(Exit.failCause(defect)), { _tag: "Cause", cause: defect }) }) }) - -describe("invocation generations", () => { - it("keeps a generation current until its path exits or is entered again", () => { - const generations = new InvocationGenerations() - const left = generations.beginGeneration("Active.left") - const right = generations.beginGeneration("Active.right") - generations.retireGenerations(["Unrelated", "Active.left"]) - assert.deepStrictEqual([left.current, right.current], [false, true]) - - const reentered = generations.beginGeneration("Active.left") - const replaced = generations.beginGeneration("Active.left") - assert.deepStrictEqual([reentered.current, replaced.current, right.current], [false, true, true]) - - generations.retireAllGenerations() - assert.deepStrictEqual([replaced.current, right.current], [false, false]) - }) -}) diff --git a/packages/effect-machine/test/internal/machine/stepHost.test.ts b/packages/effect-machine/test/internal/machine/stepHost.test.ts new file mode 100644 index 00000000..70f88339 --- /dev/null +++ b/packages/effect-machine/test/internal/machine/stepHost.test.ts @@ -0,0 +1,9 @@ +import { assert, describe, it } from "@effect/vitest" +import { makeKey } from "../../../src/internal/machine/stepHost.js" + +describe("local host of a step", () => { + it("keeps path and invoke id boundaries collision-free", () => { + assert.notStrictEqual(makeKey("a", "bc"), makeKey("ab", "c")) + assert.notStrictEqual(makeKey("root.child", "worker"), makeKey("root", ".childworker")) + }) +}) diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs index 86c27532..ada65e8a 100644 --- a/scripts/check-architecture.mjs +++ b/scripts/check-architecture.mjs @@ -244,12 +244,10 @@ export const checkArchitecture = ({ const runtimeModules = new Set([ "src/internal/machine/runtime.ts", "src/internal/machine/runtimeProtocol.ts", - "src/internal/machine/runtimeGeneric.ts", "src/internal/machine/runtimeCompiled.ts" ]) const hostNeutralModules = new Set([ "src/internal/machine/invocationChanges.ts", - "src/internal/machine/invocationGeneration.ts", "src/internal/machine/invocationOutcome.ts", "src/internal/machine/invocationResolution.ts", "src/internal/machine/step.ts" @@ -260,7 +258,7 @@ export const checkArchitecture = ({ "src/internal/machine/childRegistry.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/inspectionRuntime.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/process.ts" ]) // Hosts a local machine, so it depends on the local runtime by design. @@ -313,7 +311,7 @@ export const checkArchitecture = ({ "src/internal/machine/planner.ts", "src/internal/machine/command.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" @@ -324,7 +322,7 @@ export const checkArchitecture = ({ "src/internal/machine/planner.ts", "src/internal/machine/command.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" @@ -334,7 +332,7 @@ export const checkArchitecture = ({ "src/internal/machine/planner.ts", "src/internal/machine/command.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" @@ -343,14 +341,14 @@ export const checkArchitecture = ({ "src/internal/machine/planner.ts", "src/internal/machine/command.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" ])], ["src/internal/machine/command.ts", new Set([ "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" @@ -358,14 +356,14 @@ export const checkArchitecture = ({ ["src/internal/machine/planner.ts", new Set([ "src/internal/machine/serialization.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" ])], ["src/internal/machine/executionPlan.ts", new Set([ "src/internal/machine/serialization.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/commandRuntime.ts", "src/internal/machine/process.ts", "src/internal/machine/runtime.ts" @@ -376,7 +374,7 @@ export const checkArchitecture = ({ if (forbidden.has("src/internal/machine/runtime.ts")) { for (const module of runtimeModules) forbidden.add(module) } - if (forbidden.has("src/internal/machine/invocation.ts")) { + if (forbidden.has("src/internal/machine/stepHost.ts")) { for (const module of hostNeutralModules) forbidden.add(module) } } @@ -437,7 +435,7 @@ export const checkArchitecture = ({ [ "src/internal/machine/commandRuntime.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/process.ts", ...runtimeModules ].includes(edge.target) @@ -464,7 +462,7 @@ export const checkArchitecture = ({ [ "src/internal/machine/configuration.ts", "src/internal/machine/executionPlan.ts", - "src/internal/machine/invocation.ts", + "src/internal/machine/stepHost.ts", "src/internal/machine/invocationOutcome.ts", "src/internal/machine/invocationResolution.ts", "src/internal/machine/planner.ts", diff --git a/scripts/check-architecture.test.mjs b/scripts/check-architecture.test.mjs index 69c2bc00..3b80356d 100644 --- a/scripts/check-architecture.test.mjs +++ b/scripts/check-architecture.test.mjs @@ -103,15 +103,15 @@ test("rejects value back-edges and execution-layer inversions", () => { test("rejects outward machine semantic dependencies", () => { const root = makeProject({ - "src/internal/machine/topology.ts": 'import { decode } from "./protocol.js"\nimport { invoke } from "./invocation.js"\nexport const topology = decode + invoke', + "src/internal/machine/topology.ts": 'import { decode } from "./protocol.js"\nimport { invoke } from "./stepHost.js"\nexport const topology = decode + invoke', "src/internal/machine/protocol.ts": "export const decode = 1", - "src/internal/machine/invocation.ts": "export const invoke = 1" + "src/internal/machine/stepHost.ts": "export const invoke = 1" }) assert.deepEqual(rules(root), ["ARCH005", "ARCH005", "ARCH014"]) }) test("enforces semantic boundaries for each runtime strategy and shared protocol", () => { - for (const module of ["runtimeProtocol", "runtimeGeneric", "runtimeCompiled"]) { + for (const module of ["runtimeProtocol", "runtimeCompiled"]) { const root = makeProject({ "src/internal/machine/planner.ts": `import { run } from "./${module}.js"\nexport const plan = run`, [`src/internal/machine/${module}.ts`]: 'import type { value } from "./process.js"\nexport const run: typeof value = 1', @@ -122,18 +122,17 @@ test("enforces semantic boundaries for each runtime strategy and shared protocol }) test("keeps host-neutral invocation modules independent of the local runtime", () => { - for (const module of ["invocationChanges", "invocationGeneration", "invocationOutcome", "invocationResolution"]) { + for (const module of ["invocationChanges", "invocationOutcome", "invocationResolution", "step"]) { for ( const local of [ "childRegistry", "commandRuntime", "inspectionRuntime", - "invocation", "process", "runtime", "runtimeCompiled", - "runtimeGeneric", - "runtimeProtocol" + "runtimeProtocol", + "stepHost" ] ) { const root = makeProject({ @@ -150,12 +149,11 @@ const localRuntimeModules = [ "src/internal/machine/childRegistry", "src/internal/machine/commandRuntime", "src/internal/machine/inspectionRuntime", - "src/internal/machine/invocation", "src/internal/machine/process", "src/internal/machine/runtime", "src/internal/machine/runtimeCompiled", - "src/internal/machine/runtimeGeneric", - "src/internal/machine/runtimeProtocol" + "src/internal/machine/runtimeProtocol", + "src/internal/machine/stepHost" ] const relativeModule = (from, to) => { @@ -265,12 +263,11 @@ test("keeps the public local host behind its implementation seam", () => { assert.deepEqual(new Set(rules(root)), new Set(["ARCH002", "ARCH003", "ARCH009", "ARCH013"])) }) -test("keeps the halves split out of the invocation host outside inner layers", () => { +test("keeps invocation semantics outside the planner and the runtime", () => { const root = makeProject({ "src/internal/machine/planner.ts": 'import type { Outcome } from "./invocationOutcome.js"\nexport type Planned = Outcome', - "src/internal/machine/runtimeProtocol.ts": 'import type { Outcome } from "./invocationOutcome.js"\nimport type { Generations } from "./invocationGeneration.js"\nexport type Runtime = [Outcome, Generations]', - "src/internal/machine/invocationOutcome.ts": "export type Outcome = 1", - "src/internal/machine/invocationGeneration.ts": "export type Generations = 1" + "src/internal/machine/runtimeProtocol.ts": 'import type { Outcome } from "./invocationOutcome.js"\nexport type Runtime = Outcome', + "src/internal/machine/invocationOutcome.ts": "export type Outcome = 1" }) assert.deepEqual(rules(root), ["ARCH005", "ARCH006"]) }) From 5e16194f14c68323a3d05b747585616cbb0fce9b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:20:23 +0000 Subject: [PATCH 07/11] Read the entry paths of a first step only when inspected Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/step.ts | 33 +++++++++++++++---- .../src/internal/machine/stepHost.ts | 4 +-- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index 7beace4e..87083abc 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -361,6 +361,16 @@ interface Paths { const noPaths: Paths = { exited: empty, entered: empty } +/** The paths of an initial step, sorted when first read. */ +class InitialPaths implements Paths { + #entered: ReadonlyArray | undefined + readonly exited: ReadonlyArray = empty + constructor(private readonly machine: Machine.Any, private readonly paths: () => ReadonlyArray) {} + get entered(): ReadonlyArray { + return this.#entered ??= Planner.sortEntryPaths(this.machine, this.paths()) + } +} + const pathsOf = (microsteps: ReadonlyArray): Paths => { const changes = InvocationChanges.fromMicrosteps(microsteps) return changes === undefined @@ -990,17 +1000,20 @@ const build = ( microsteps: planned.microsteps, emitted: planned.emittedEvents, commands: commandsOf(planned.commands, empty).commands, - paths: { - exited: empty, - entered: Planner.sortEntryPaths(machine, Configuration.getInitialEntryPaths(machine, configuration)) - } + paths: new InitialPaths(machine, () => Configuration.getInitialEntryPaths(machine, configuration)) } const next = initial(planning, configuration, planned.state) if (planned.done) { return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published)) } return Exit.succeed( - enter(next, InvocationResolution.initialEntries(machine, configuration), empty, empty, published) + enter( + next, + invoking.size === 0 ? empty : InvocationResolution.initialEntries(machine, configuration), + empty, + empty, + published + ) ) } @@ -1021,14 +1034,20 @@ const build = ( microsteps: empty, emitted: empty, commands: empty, - paths: { exited: empty, entered: Planner.sortEntryPaths(machine, planned.initialEntryPaths) } + paths: new InitialPaths(machine, () => planned.initialEntryPaths) } const next = reached(planning, planned.configuration, configuration, planned.state, 0) if (planned.done) { return Exit.succeed(ended(next, empty, Exit.succeed(planned.output), published)) } return Exit.succeed( - enter(next, InvocationResolution.initialEntries(machine, configuration), empty, empty, published) + enter( + next, + invoking.size === 0 ? empty : InvocationResolution.initialEntries(machine, configuration), + empty, + empty, + published + ) ) } diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index 38dfe166..d4f506d8 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -562,7 +562,7 @@ export const makeExecution = ( if (step.commands.length > 0 || step.emitted.length > 0) { throw new Error("Machine started by its execution plan planned startup commands or emissions") } - if (entry._tag === "Initial") scope.inspectInitial(step.entered, step.microsteps) + if (entry._tag === "Initial" && isInspected(scope)) scope.inspectInitial(step.entered, step.microsteps) return initialOf(step, host(step)) } : undefined @@ -575,7 +575,7 @@ export const makeExecution = ( const started = first(scope) if (Exit.isFailure(started)) return Effect.failCause(started.cause) const step = started.value - if (entry._tag === "Initial") scope.inspectInitial(step.entered, step.microsteps) + if (entry._tag === "Initial" && isInspected(scope)) scope.inspectInitial(step.entered, step.microsteps) const result = Effect.succeed(initialOf(step, host(step))) const commands = step.commands.length === 0 ? undefined : runCommands(step.commands, scope) const emitted = step.emitted.length === 0 From acc61a71e0a404ddcc146bc66fb726ebfb304525 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:06:15 +0000 Subject: [PATCH 08/11] Take each message of a drain with one check of its kind Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/runtimeProtocol.ts | 2 +- .../src/internal/machine/stepHost.ts | 75 ++++++++++--------- 2 files changed, 40 insertions(+), 37 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 2885eed0..8c078137 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -173,7 +173,7 @@ export interface AcknowledgedDelivery { export const AcknowledgedMessageTypeId: unique symbol = Symbol("effect/Machine/AcknowledgedMessage") /** @internal */ -interface AcknowledgedMessage { +export interface AcknowledgedMessage { readonly [AcknowledgedMessageTypeId]: true readonly event: Event readonly deferred?: Deferred.Deferred, unknown> diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index d4f506d8..d5d48592 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -345,19 +345,16 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => return host } - const takeMessage = (state: Step.State<"Owned">, event: unknown, retain: boolean): OwnedStep => { - if (event instanceof Runtime.WorkMessage) { - const work = event.work as Step.Work - switch (event._tag) { - case "Settle": - return kernel.settle(state, work, event.value as Exit.Exit, retain) - case "Element": - return kernel.element(state, work, event.value, retain) - case "Report": - return kernel.report(state, work, event.value, retain) - } + const takeWork = (state: Step.State<"Owned">, message: Runtime.WorkMessage, retain: boolean): OwnedStep => { + const work = message.work as Step.Work + switch (message._tag) { + case "Settle": + return kernel.settle(state, work, message.value as Exit.Exit, retain) + case "Element": + return kernel.element(state, work, message.value, retain) + case "Report": + return kernel.report(state, work, message.value, retain) } - return kernel.sendDecoded(state, event as Machine.EventOf, retain) } const loop = (context: Context): Drain => Effect.suspend(() => drainSync(context) ?? noQueuedMessages) @@ -461,37 +458,38 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => message = pending.value } const acknowledged = Runtime.isAcknowledgedMessage(message) - const event = Runtime.messageEvent(message) + const event: unknown = acknowledged ? (message as Runtime.AcknowledgedMessage).event : message if (event instanceof Runtime.RefusedEvent) return failPlanning(event.error) const before = context.state() + const work = event instanceof Runtime.WorkMessage ? event : undefined // Only an acknowledged delivery reads the microsteps of its step. - const step = takeMessage(host.state, event, acknowledged) - host.state = step.state - const exit = step.exit - if (exit !== undefined && Exit.isFailure(exit)) return Effect.failCause(exit.cause) - const settled = event instanceof Runtime.WorkMessage && event._tag === "Settle" && step.planned && - step.exited.includes((event.work as Step.Work).path) - ? event.work as Step.Work - : undefined - if ( - exit === undefined && settled === undefined && step.commands.length === 0 && step.stop.length === 0 && - step.start.length === 0 && step.emitted.length === 0 - ) { + const step = work === undefined + ? kernel.sendDecoded(host.state, event as Machine.EventOf, acknowledged) + : takeWork(host.state, work, acknowledged) + const state = step.state + host.state = state + const exit = state.exit + if (exit === undefined && step.commands.length === 0 && step.emitted.length === 0) { if (!step.planned) { - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: before }) + if (step.stop.length === 0 && step.start.length === 0) { + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: before }) + continue + } + } else if (step.stop.length === 0 && step.start.length === 0 && !exitsWork(step, work)) { + const next = state.snapshot + const notification = context.commit(next) + if (notification !== undefined) { + return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => { + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) + return loop(context) + })))) + } + if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) continue } - const next = step.snapshot - const notification = context.commit(next) - if (notification !== undefined) { - return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => { - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) - return loop(context) - })))) - } - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) - continue } + if (exit !== undefined && Exit.isFailure(exit)) return Effect.failCause(exit.cause) + const settled = exitsWork(step, work) ? work!.work as Step.Work : undefined return continueEffectful(context, host, step, acknowledged, before, settled) } } @@ -506,6 +504,11 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => } } +/** Whether a step settled work whose state it exited, so the work stops before the state is entered again. */ +const exitsWork = (step: OwnedStep, message: Runtime.WorkMessage | undefined): boolean => + message !== undefined && message._tag === "Settle" && step.planned && + step.exited.includes((message.work as Step.Work).path) + /** The result of the first step of a process, as the compiled process takes it. */ const initialOf = ( step: OwnedStep, From b036e16e225b885a79a3d26244215780a2dbe58e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:27:55 +0000 Subject: [PATCH 09/11] Commit an event that only moves the machine without a step An event whose transitions start, stop and emit nothing now moves the owned state in place of building a Step, so a drain burst allocates as it did before the one driver. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- .../src/internal/machine/step.ts | 39 ++++++++++++++++++- .../src/internal/machine/stepHost.ts | 25 ++++++++++-- .../internal/machine/stepDifferential.test.ts | 36 +++++++++++++++++ 3 files changed, 94 insertions(+), 6 deletions(-) diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index 87083abc..eeab13a8 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -504,6 +504,14 @@ export interface Kernel * transition; the step still lists the paths it exited and entered. */ readonly sendDecoded: (state: State, event: Machine.EventOf, retain?: boolean) => Step + /** + * Plans a decoded event whose microsteps no one reads, as `sendDecoded` + * without `retain` does. A step that only moves the machine to a new state, + * with no command, emitted event, work or end, is returned as that state, so + * a host that applies it allocates no step: the state passed in when the + * event changed nothing, and a new state otherwise. + */ + readonly move: (state: State, event: Machine.EventOf) => State | Step readonly settle: (state: State, work: Work, exit: Exit.Exit, retain?: boolean) => Step readonly element: (state: State, work: Work, element: unknown, retain?: boolean) => Step readonly report: (state: State, work: Work, snapshot: unknown, retain?: boolean) => Step @@ -901,12 +909,26 @@ const build = ( * Plans one event on a state that runs `running`: a public event that `send` * decoded, or the invocation event of a result. */ - const advance = ( + function advance( state: State, running: ReadonlyArray, event: Machine.EventOf | InvocationEvent.InvocationEvent, retain: boolean - ): Step => { + ): Step + function advance( + state: State, + running: ReadonlyArray, + event: Machine.EventOf | InvocationEvent.InvocationEvent, + retain: false, + bare: true + ): State | Step + function advance( + state: State, + running: ReadonlyArray, + event: Machine.EventOf | InvocationEvent.InvocationEvent, + retain: boolean, + bare = false + ): State | Step { let planned: ExecutionPlan.ExecutionMacrostep try { // A step publishes its microsteps, so a plan retains them unless its host reads none. @@ -917,6 +939,7 @@ const build = ( return ended(endedFrom(state), latestFirst(running), exitOfThrow(error), { ...nothing, event: planning }) } if (planned.microsteps.length === 0) { + if (bare && running === state.running) return state return new Step( running === state.running ? state : state.withRunning(running), planned.event, @@ -930,6 +953,9 @@ const build = ( const commanded = planned.commands.length === 0 ? undefined : commandsOf(planned.commands, running) const commands = commanded === undefined ? empty : commanded.commands if (invoking.size === 0) { + if (bare && !planned.done && commands.length === 0 && planned.emittedEvents.length === 0) { + return new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined) + } return planned.done ? ended( reached(state.planning, planned.next, undefined, undefined, state.runs), @@ -1074,6 +1100,9 @@ const build = ( const sendDecoded = (state: State, event: Machine.EventOf, retain = true): Step => state.exit === undefined ? advance(state, state.running, event, retain) : unchanged(state) + const move = (state: State, event: Machine.EventOf): State | Step => + state.exit === undefined ? advance(state, state.running, event, false, true) : unchanged(state) + const settle = (state: State, work: Work, exit: Exit.Exit, retain = true): Step => { const settled = current(state, work) if (settled === undefined) return unchanged(state) @@ -1144,6 +1173,7 @@ const build = ( rest: (state) => state.resting(), send, sendDecoded, + move, settle, element, report, @@ -1165,6 +1195,11 @@ const build = ( }, sendDecoded: (state, event, retain) => givenBackIfUnchanged(state, sendDecoded(state.handOverNeverReuse(), event, retain)), + move: (state, event) => { + const moved = move(state.handOverNeverReuse(), event) + if (moved === state || (moved instanceof Step && moved.state === state)) state.giveBackUnchanged() + return moved + }, settle: (state, work, exit, retain) => givenBackIfUnchanged(state, settle(state.handOverNeverReuse(), work, exit, retain)), element: (state, work, value, retain) => diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index d5d48592..0e689952 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -462,10 +462,27 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => if (event instanceof Runtime.RefusedEvent) return failPlanning(event.error) const before = context.state() const work = event instanceof Runtime.WorkMessage ? event : undefined - // Only an acknowledged delivery reads the microsteps of its step. - const step = work === undefined - ? kernel.sendDecoded(host.state, event as Machine.EventOf, acknowledged) - : takeWork(host.state, work, acknowledged) + let step: OwnedStep + if (work !== undefined) { + step = takeWork(host.state, work, acknowledged) + } else if (acknowledged) { + // Only an acknowledged delivery reads the microsteps of its step. + step = kernel.sendDecoded(host.state, event as Machine.EventOf, true) + } else { + // An event that only moves the machine is committed without a step. + const moved = kernel.move(host.state, event as Machine.EventOf) + if (moved instanceof Step.Step) { + step = moved + } else { + if (moved === host.state) continue + host.state = moved + const notification = context.commit(moved.snapshot) + if (notification !== undefined) { + return context.runAfterChanges(notification.pipe(Effect.andThen(loop(context)))) + } + continue + } + } const state = step.state host.state = state const exit = state.exit diff --git a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts index 790a615d..64ba021b 100644 --- a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts +++ b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts @@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest" import { Cause, Duration, Effect, Exit, Schema, Stream } from "effect" import { Machine } from "../../../src/index.js" import * as ExecutionPlan from "../../../src/internal/machine/executionPlan.js" +import * as Protocol from "../../../src/internal/machine/protocol.js" import * as Step from "../../../src/internal/machine/step.js" import { children } from "../../conformance/scenarios/children.js" import { invocations } from "../../conformance/scenarios/invocations.js" @@ -321,6 +322,41 @@ describe("Machine.toStep planner and ownership", () => { assert.strictEqual(step.stop(stopped.state).state, done.state) }) + it("moves a state as its step would, and lists a step only for what a host must apply", () => { + const decoded = (event: unknown) => Protocol.decodeEventSync(Counter, event) + for (const planner of ["Compiled", "Reference"] as const) { + const kernel = Step.kernel(Counter, "Owned", planner) + const planning = () => new Step.Planning(Counter, kernel.plan, self, undefined, undefined) + let moved = success(kernel.start(planning(), [], false)).state + let stepped = success(kernel.start(planning(), [], false)).state + for (const event of [{ _tag: "Increment" }, { _tag: "Twice" }, { _tag: "Same" }, { _tag: "Again" }]) { + const result = kernel.move(moved, decoded(event)) + const step = kernel.sendDecoded(stepped, decoded(event), false) + assert.notInstanceOf(result, Step.Step) + const state = result as Step.State<"Owned"> + // An event that changes nothing returns the state passed in. + assert.strictEqual(state === moved, !step.planned) + assert.deepStrictEqual(state.snapshot, step.snapshot) + moved = state + stepped = step.state + } + // A state that a move replaced is not reused. + const before = moved + moved = kernel.move(moved, decoded({ _tag: "Increment" })) as Step.State<"Owned"> + assert.throws(() => kernel.move(before, decoded({ _tag: "Increment" })), /never reuse an owned state/) + // A step that ends the machine or fails is listed as a step. + const finished = kernel.move(moved, decoded({ _tag: "Finish" })) + assert.instanceOf(finished, Step.Step) + const exit = (finished as Step.Step<"Owned">).exit! + assert.ok(Exit.isSuccess(exit)) + // Increment, Twice, Again and the last Increment: (1 + 2) * 2 + 1. + assert.strictEqual(exit.value, 7) + const failed = kernel.move(success(kernel.start(planning(), [], false)).state, decoded({ _tag: "Overflow" })) + assert.instanceOf(failed, Step.Step) + assert.ok(Exit.isFailure((failed as Step.Step<"Owned">).exit!)) + } + }) + it("are not the states of the persistent step functions", () => { const owned: Step.OwnedMachineStep = counter() const persistent: Step.MachineStep = Step.make(Counter, { self }) From a260598c8a18e6e215ceabc3ada1ed6447506411 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:38:05 +0000 Subject: [PATCH 10/11] Keep the running work of a step in an array of its size An array that a push grows from empty reserves seventeen slots, and the running work stays on the machine's state while it is idle. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HendNdA7BM5kaFHqECsKFr --- packages/effect-machine/src/internal/machine/step.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index eeab13a8..833cb651 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -877,7 +877,10 @@ const build = ( ?.status if (status === "Ended") continue const work = describe(next.planning, invocation, run) - ;(added ??= []).push(work) + // A literal holds one entry where a push onto an empty array + // reserves seventeen, and the running work outlives this step. + if (added === undefined) added = [work] + else added.push(work) if (status !== "Running") (start ??= []).push(work) } } From 2beb1d9fa839ebe6a360b0eb0565d976f6559e47 Mon Sep 17 00:00:00 2001 From: SandroMaglione Date: Sun, 29 Nov 2026 09:04:11 +1300 Subject: [PATCH 11/11] Eliminate step-host perf regressions and move remaining protocol rules into step --- .changeset/local-rejects-refused-events.md | 2 + LLMS.md | 12 +- ai-docs/src/37_new-host/index.md | 12 +- packages/effect-machine/src/Machine.ts | 16 +- .../src/internal/machine/childRegistry.ts | 2 +- .../src/internal/machine/clusterInstance.ts | 15 +- .../src/internal/machine/executionPlan.ts | 19 +- .../internal/machine/invocationResolution.ts | 27 +- .../src/internal/machine/process.ts | 21 +- .../src/internal/machine/protocol.ts | 89 +++- .../src/internal/machine/runtimeCompiled.ts | 121 +++-- .../src/internal/machine/runtimeProtocol.ts | 198 ++++--- .../src/internal/machine/step.ts | 488 +++++++++++++----- .../src/internal/machine/stepHost.ts | 264 +++++----- .../test/conformance/matrix.txt | 1 + .../test/conformance/scenarios/invocations.ts | 59 +++ .../test/conformance/support/fixture.ts | 6 + .../test/conformance/support/hosts/step.ts | 6 + .../test/conformance/support/suite.ts | 7 + .../internal/machine/stepDifferential.test.ts | 209 +++++++- .../machine/support/stepDifferential.ts | 18 +- .../test/machine/MachineStep.test.ts | 37 +- scripts/check-architecture.mjs | 24 +- scripts/check-architecture.test.mjs | 9 + 24 files changed, 1198 insertions(+), 464 deletions(-) diff --git a/.changeset/local-rejects-refused-events.md b/.changeset/local-rejects-refused-events.md index 1dbe6453..4385144d 100644 --- a/.changeset/local-rejects-refused-events.md +++ b/.changeset/local-rejects-refused-events.md @@ -9,3 +9,5 @@ A timer that cannot start now has one failure mode: `Machine.MachineStep.Work.Ti A transition that throws follows one documented rule on every host: the error goes to the sender when one waits for the event to be processed, and otherwise the machine fails. Each host keeps its behaviour. Every machine and every `Machine.logic` that `LocalMachine` runs now shares one process. A `send` to logic whose stop was already requested fails with `StoppedError`, as it does for a machine, and the `Initialized` inspection event of an inspected machine lists its entry paths and microsteps in the order of the reference planner. + +`Machine.MachineStep.Step` now splits work stopped when reaching a final state into `stop` (work of exited states, interrupted before publishing `snapshot`) and `stopAfter` (remaining work of non-exited states, interrupted after delivering `emitted`, latest first). Hosts carry out a step in order: `commands`, `stop`, `snapshot`, `emitted`, `start`, `stopAfter`. On non-final, failed, or owner-stopped steps, `stopAfter` is empty. diff --git a/LLMS.md b/LLMS.md index a09d135f..daeee49e 100644 --- a/LLMS.md +++ b/LLMS.md @@ -1905,14 +1905,18 @@ The options are what the machine needs of its host: them, every operation on children fails the machine with `ProcessLocalError`. A host carries out each `Step` in this order: carry out `commands`, interrupt -`stop`, publish `snapshot`, deliver `emitted`, then start `start`. Pass -`step.state` to the next call. +`stop`, publish `snapshot`, deliver `emitted`, start `start`, then interrupt +`stopAfter`. Pass `step.state` to the next call. - A failed `Exit` from `send`, `start`, or `resume` means nothing happened. An event is rejected because its schema refused it or because the machine has ended, and the state you passed still holds. -- A machine that fails or ends still returns a `Step`. Its `exit` is set, and its - `stop` lists every piece of work that still runs. +- A machine that fails or ends still returns a `Step`. Its `exit` is set: when + it reaches a final state, `stop` lists the work of exited states (interrupted + before `snapshot` and `emitted`) and `stopAfter` lists the remaining work of + states that stayed active (interrupted after `emitted`, latest first); when it + fails or is stopped by its owner, `stop` lists every piece of work that still + runs and `stopAfter` is empty. - `commands` are `Send` (call `target.send(event)`), `SendToChild`, and `StopChild`. A command to a child names the running `Logic` or child machine it selects as `work`. A stopped one no longer runs, and reports nothing. With diff --git a/ai-docs/src/37_new-host/index.md b/ai-docs/src/37_new-host/index.md index 71d44806..86f88431 100644 --- a/ai-docs/src/37_new-host/index.md +++ b/ai-docs/src/37_new-host/index.md @@ -32,14 +32,18 @@ The options are what the machine needs of its host: them, every operation on children fails the machine with `ProcessLocalError`. A host carries out each `Step` in this order: carry out `commands`, interrupt -`stop`, publish `snapshot`, deliver `emitted`, then start `start`. Pass -`step.state` to the next call. +`stop`, publish `snapshot`, deliver `emitted`, start `start`, then interrupt +`stopAfter`. Pass `step.state` to the next call. - A failed `Exit` from `send`, `start`, or `resume` means nothing happened. An event is rejected because its schema refused it or because the machine has ended, and the state you passed still holds. -- A machine that fails or ends still returns a `Step`. Its `exit` is set, and its - `stop` lists every piece of work that still runs. +- A machine that fails or ends still returns a `Step`. Its `exit` is set: when + it reaches a final state, `stop` lists the work of exited states (interrupted + before `snapshot` and `emitted`) and `stopAfter` lists the remaining work of + states that stayed active (interrupted after `emitted`, latest first); when it + fails or is stopped by its owner, `stop` lists every piece of work that still + runs and `stopAfter` is empty. - `commands` are `Send` (call `target.send(event)`), `SendToChild`, and `StopChild`. A command to a child names the running `Logic` or child machine it selects as `work`. A stopped one no longer runs, and reports nothing. With diff --git a/packages/effect-machine/src/Machine.ts b/packages/effect-machine/src/Machine.ts index 28c01b2a..586e6cc3 100644 --- a/packages/effect-machine/src/Machine.ts +++ b/packages/effect-machine/src/Machine.ts @@ -7778,7 +7778,7 @@ export declare namespace MachineStep { * * A host carries a step out in this order, which is the order of * `LocalMachine`: it carries out `commands`, interrupts `stop`, publishes - * `snapshot`, delivers `emitted`, and then starts `start`. + * `snapshot`, delivers `emitted`, starts `start`, and interrupts `stopAfter`. * * `snapshot` and `microsteps` are built when they are first read, so a host * that publishes neither pays for neither. @@ -7808,7 +7808,11 @@ export declare namespace MachineStep { /** What transitions asked of the host with `enqueue.sendTo` and `enqueue.stop`, in order. */ readonly commands: ReadonlyArray> - /** Running work to interrupt, in order. Its `Exit` is not reported. */ + /** + * Running work to interrupt before publishing `snapshot`, in order: work of + * exited states, or all remaining work when the machine fails or is + * stopped. Its `Exit` is not reported. + */ readonly stop: ReadonlyArray> /** Events emitted to the observers of the machine, in order. */ @@ -7817,6 +7821,14 @@ export declare namespace MachineStep { /** Work to start, in order. Report its end with `settle`. */ readonly start: ReadonlyArray> + /** + * Running work of states that were not exited, to interrupt after + * publishing `snapshot` and delivering `emitted` when this step reaches a + * final state, latest first. Empty on every non-final, failed, or owner-stopped + * step. Its `Exit` is not reported. + */ + readonly stopAfter: ReadonlyArray> + /** * Every piece of work that runs once this step is carried out, in start * order: the work that runs on, and then `start`. After `resume`, it also diff --git a/packages/effect-machine/src/internal/machine/childRegistry.ts b/packages/effect-machine/src/internal/machine/childRegistry.ts index 1e08212e..95d62a72 100644 --- a/packages/effect-machine/src/internal/machine/childRegistry.ts +++ b/packages/effect-machine/src/internal/machine/childRegistry.ts @@ -130,7 +130,7 @@ export const registerChild = ( if (registry.closed || entry === undefined || entry._tag !== "Starting" || entry.token !== token) { return false } - registry.children.delete(key) + if (registry.children.size > 1) registry.children.delete(key) const started: ChildEntry = entry.ownerKey === undefined ? { _tag: "Started", token, descriptor, ref } : { diff --git a/packages/effect-machine/src/internal/machine/clusterInstance.ts b/packages/effect-machine/src/internal/machine/clusterInstance.ts index 0d5ef170..e39db84c 100644 --- a/packages/effect-machine/src/internal/machine/clusterInstance.ts +++ b/packages/effect-machine/src/internal/machine/clusterInstance.ts @@ -872,7 +872,7 @@ export const make = (options: Options): Effect.Effect, if (!exited.includes(work.path)) progress = ClusterProgress.settle(progress, work) } progress = ClusterProgress.exit(progress, exited) - const stops = stopsOf(before, planned.steps.flatMap((step) => step.stop)) + const stops = stopsOf(before, planned.steps.flatMap((step) => [...step.stop, ...step.stopAfter])) if (last.exit !== undefined) { return { progress: ClusterProgress.stopChildren(ClusterProgress.cancelTimers(progress)), stops, starts: [] } } @@ -1397,14 +1397,21 @@ export const make = (options: Options): Effect.Effect, ): Effect.Effect<{ readonly key: Checkpoint.InvocationKey; readonly cause: Cause.Cause } | undefined> => Effect.suspend(() => { if (work.current?.revision === current.revision) return Effect.succeed(undefined) - if (current._tag !== "Active" || current.step === undefined) return Effect.as(work.stopAll, undefined) - const state = current.step // A step from the state of the running work stops and starts what it - // lists. Any other state starts all of its work. + // lists, in the step's order (`stop`, then `stopAfter` when terminal). const continued = stored?.step !== undefined && stored.from !== undefined && work.current?.state === stored.from ? stored.step : undefined + if (current._tag !== "Active" || current.step === undefined) { + if (continued === undefined) return Effect.as(work.stopAll, undefined) + return work.stop(continued.stop).pipe( + Effect.andThen(work.stop(continued.stopAfter)), + Effect.andThen(work.stopAll), + Effect.as(undefined) + ) + } + const state = current.step return (continued === undefined ? work.stopAll : work.stop(continued.stop)).pipe( Effect.andThen(Effect.suspend(() => { work.current = { revision: current.revision, state } diff --git a/packages/effect-machine/src/internal/machine/executionPlan.ts b/packages/effect-machine/src/internal/machine/executionPlan.ts index 18129e7a..e460dfca 100644 --- a/packages/effect-machine/src/internal/machine/executionPlan.ts +++ b/packages/effect-machine/src/internal/machine/executionPlan.ts @@ -1332,6 +1332,7 @@ export interface CompiledExecutionPlan { } const executionPlanCache = new WeakMap() +const referenceExecutionPlanCache = new WeakMap() const makeActiveExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => ({ fromConfiguration: (configuration) => configuration, @@ -1480,6 +1481,22 @@ export const selectExecutionPlanForTesting = ( strategy: ExecutionPlanStrategy ): SelectedExecutionPlan => selectExecutionPlan(machine, strategy) +/** + * The reference execution plan of `machine`, which always plans on the generic + * planner without indexed compilation. Cached per machine. + * + * @internal + */ +export const referenceExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => { + const cached = referenceExecutionPlanCache.get(machine) + if (cached !== undefined) { + return cached + } + const reference = makeActiveExecutionPlan(machine) + referenceExecutionPlanCache.set(machine, reference) + return reference +} + export const compileExecutionPlan = (machine: Machine.Any): CompiledExecutionPlan => { const cached = executionPlanCache.get(machine) if (cached !== undefined) { @@ -1487,7 +1504,7 @@ export const compileExecutionPlan = (machine: Machine.Any): CompiledExecutionPla } const indexed = compileIndexedExecutionDescriptor(machine) const compiled = indexed === undefined - ? makeActiveExecutionPlan(machine) + ? referenceExecutionPlan(machine) : makeIndexedExecutionPlan(machine, indexed) executionPlanCache.set(machine, compiled) return compiled diff --git a/packages/effect-machine/src/internal/machine/invocationResolution.ts b/packages/effect-machine/src/internal/machine/invocationResolution.ts index 6e8bfaa2..644f80ac 100644 --- a/packages/effect-machine/src/internal/machine/invocationResolution.ts +++ b/packages/effect-machine/src/internal/machine/invocationResolution.ts @@ -149,6 +149,8 @@ const outcomeChannels = (definition: CapturedInvocation.CapturedInvocation): Out type CapturedChild = Extract +const staticChildInvocations = new WeakMap() + // A child without input does not depend on its entry context, so neither // building nor retaining one is worthwhile. const resolveChild = ( @@ -164,6 +166,14 @@ const resolveChild = ( input }) +const resolveStaticChild = (definition: CapturedChild, path: string): ChildInvocation => { + const cached = staticChildInvocations.get(definition) + if (cached !== undefined && cached.path === path) return cached + const resolved = resolveChild(definition, path, undefined) + if (cached === undefined) staticChildInvocations.set(definition, resolved) + return resolved +} + const resolveDefinition = ( definition: CapturedInvocation.CapturedInvocation, path: string, @@ -227,10 +237,12 @@ export const resolve = ( configuration: Configuration.ActiveConfiguration, entryPaths: ReadonlyArray, event: Machine.LifecycleEvent, - capabilities: InvocationCapabilities + capabilities: InvocationCapabilities | (() => InvocationCapabilities) ): ReadonlyArray => { let groups: Array | undefined - for (const path of Planner.sortEntryPaths(machine, entryPaths)) { + let resolvedCapabilities: InvocationCapabilities | undefined + const ordered = entryPaths.length <= 1 ? entryPaths : Planner.sortEntryPaths(machine, entryPaths) + for (const path of ordered) { if (!configuration.active.has(path)) continue const definitions = CapturedInvocation.list(Configuration.getStateConfigByPath(machine, path)?.invoke) if (definitions.length === 0) continue @@ -239,12 +251,12 @@ export const resolve = ( path, invocations: definitions.map((definition) => "child" in definition && !("input" in definition) - ? resolveChild(definition, path, undefined) + ? resolveStaticChild(definition, path) : resolveDefinition( definition, path, context ??= { - ...capabilities, + ...(resolvedCapabilities ??= typeof capabilities === "function" ? capabilities() : capabilities), state: configuration.values.get(path), containingState: Configuration.getParentValue(machine, configuration, path), ancestors: Configuration.getParentValues(machine, configuration, path), @@ -267,11 +279,14 @@ export const resolveEntries = ( machine: Machine.Any, configuration: Configuration.ActiveConfiguration, entries: Iterable, Machine.LifecycleEvent]>, - capabilities: InvocationCapabilities + capabilities: InvocationCapabilities | (() => InvocationCapabilities) ): ReadonlyArray => { let groups: Array | undefined + let resolvedCapabilities: InvocationCapabilities | undefined + const getCapabilities = (): InvocationCapabilities => + resolvedCapabilities ??= typeof capabilities === "function" ? capabilities() : capabilities for (const [paths, event] of entries) { - const resolved = resolve(machine, configuration, paths, event, capabilities) + const resolved = resolve(machine, configuration, paths, event, getCapabilities) if (resolved.length > 0) (groups ??= []).push(...resolved) } return groups ?? noGroups diff --git a/packages/effect-machine/src/internal/machine/process.ts b/packages/effect-machine/src/internal/machine/process.ts index 3046eab8..73b6218a 100644 --- a/packages/effect-machine/src/internal/machine/process.ts +++ b/packages/effect-machine/src/internal/machine/process.ts @@ -6,8 +6,9 @@ import * as Effect from "effect/Effect" import type { Machine } from "../../Machine.js" +import * as ExecutionPlan from "./executionPlan.js" import { type CapturedStateConfig, toImpl } from "./implementation.js" -import { decodeEventSync } from "./protocol.js" +import { makeEventDecoderSync } from "./protocol.js" import * as ProcessRuntime from "./runtime.js" import * as internalRuntimeProtocol from "./runtimeProtocol.js" import * as StepHost from "./stepHost.js" @@ -29,29 +30,27 @@ const hasInvokeCapability = (machine: Machine.Any): boolean => { const eventDecoders = new WeakMap() // One decoder per machine, so a started process holds no closure of its own -// for it. What work reports is the runtime's own message and is not decoded. +// for it. const eventDecoderOf = (machine: Machine.Any): internalRuntimeProtocol.EventDecoder => { let decoder = eventDecoders.get(machine) if (decoder === undefined) { - decoder = (event) => event instanceof internalRuntimeProtocol.WorkMessage ? event : decodeEventSync(machine, event) + decoder = makeEventDecoderSync(machine) eventDecoders.set(machine, decoder) } return decoder } -type Planner = "Compiled" | "Reference" - // Process logic executes erased machine definitions. The public `LocalMachine` // module owns the typed contract that specializes this boundary. const makeProcessLogic = ( machine: Machine.Any, entry: StepHost.Entry, - planner: Planner + plan: ExecutionPlan.CompiledExecutionPlan ): internalRuntimeProtocol.ProcessLogic => { const execution = StepHost.makeExecution( machine, entry, - planner, + plan, !hasInvokeCapability(machine), eventDecoderOf(machine) ) @@ -74,7 +73,7 @@ export const toProcessLogic = ( ...args: ReadonlyArray ): internalRuntimeProtocol.ProcessLogic => { if (args.length > 0) { - return makeProcessLogic(machine, { _tag: "Initial", args }, "Compiled") + return makeProcessLogic(machine, { _tag: "Initial", args }, ExecutionPlan.compileExecutionPlan(machine)) } // The execution descriptor stores process-local invoke sessions by each // runtime address and evaluates initialization/services on every start. A @@ -85,7 +84,7 @@ export const toProcessLogic = ( if (cached !== undefined) { return cached as any } - const logic = makeProcessLogic(machine, { _tag: "Initial", args }, "Compiled") + const logic = makeProcessLogic(machine, { _tag: "Initial", args }, ExecutionPlan.compileExecutionPlan(machine)) initialProcessLogicCache.set(machine, logic as any) return logic } @@ -94,7 +93,7 @@ const toResumedProcessLogic = ( machine: Machine.Any, snapshot: Machine.Snapshot ): internalRuntimeProtocol.ProcessLogic => - makeProcessLogic(machine, { _tag: "Resume", snapshot }, "Compiled") + makeProcessLogic(machine, { _tag: "Resume", snapshot }, ExecutionPlan.compileExecutionPlan(machine)) const toChildProcessLogic: internalRuntimeProtocol.MakeChildLogic = (machine, input) => machine.input === undefined ? toProcessLogic(machine) : toProcessLogic(machine, input) @@ -109,7 +108,7 @@ const strategyLogic = ( entry: StepHost.Entry ): internalRuntimeProtocol.ProcessLogic => strategy === "generic" - ? makeProcessLogic(machine, entry, "Reference") + ? makeProcessLogic(machine, entry, ExecutionPlan.referenceExecutionPlan(machine)) : entry._tag === "Initial" ? toProcessLogic(machine, ...entry.args) : toResumedProcessLogic(machine, entry.snapshot) diff --git a/packages/effect-machine/src/internal/machine/protocol.ts b/packages/effect-machine/src/internal/machine/protocol.ts index b0201344..a375c48e 100644 --- a/packages/effect-machine/src/internal/machine/protocol.ts +++ b/packages/effect-machine/src/internal/machine/protocol.ts @@ -25,6 +25,8 @@ interface MachineProtocolSchemas { readonly emit: Schema.Top readonly eventConstructors: ReadonlySet readonly emissionConstructors: ReadonlySet + eventResultDecoder?: BoundaryResultDecoder + emitResultDecoder?: BoundaryResultDecoder } interface EventProtocolDefinition { @@ -209,7 +211,10 @@ const makeEventConstruction = ( } const isEventConstruction = (value: unknown): value is EventConstruction => - typeof value === "object" && value !== null && eventConstructionDefinitions.has(value) + typeof value === "object" && + value !== null && + (value as { readonly [EventConstructionTypeId]?: unknown })[EventConstructionTypeId] === EventConstructionTypeId && + eventConstructionDefinitions.has(value) const eventConstructors = ( kind: Machine.EventProtocolKind, @@ -469,21 +474,53 @@ export const decodeEvent = { + if (isEventConstruction(event)) { + return decodeEventConstructionSync(machine, protocol, event, "event") + } + const decoded = decoder(event) + if (Result.isFailure(decoded)) { + const eventName = getEventName(event) + throw new MachineSchemaDecodeError({ + machineId: machine.id, + boundary: "event", + cause: decoded.failure, + ...(eventName === undefined ? {} : { event: eventName }) + }) + } + return decoded.success +} + +export const makeEventDecoderSync = ( + machine: Machine.Any +): (event: unknown) => Machine.EventOf => { + const protocol = getProtocolSchemas(machine) + let decoder = protocol.eventResultDecoder + return (event: unknown) => + decodeEventWith( + machine, + protocol, + decoder ??= protocol.eventResultDecoder ??= getBoundaryResultDecoder(protocol.event), + event + ) as Machine.EventOf +} + export const decodeEventSync = >( machine: Machine.Any, event: unknown ): Machine.EventOf => { const protocol = getProtocolSchemas(machine) - if (isEventConstruction(event)) { - return decodeEventConstructionSync(machine, protocol, event, "event") as Machine.EventOf - } - const eventName = getEventName(event) - return decodeBoundarySync>( + return decodeEventWith( machine, - protocol.event, - event, - eventName === undefined ? { boundary: "event" } : { boundary: "event", event: eventName } - ) + protocol, + protocol.eventResultDecoder ??= getBoundaryResultDecoder(protocol.event), + event + ) as Machine.EventOf } export const decodeEmit = >( @@ -514,13 +551,17 @@ export const decodeEmitSync = } - const eventName = getEventName(event) - return decodeBoundarySync>( - machine, - protocol.emit, - event, - eventName === undefined ? { boundary: "emission" } : { boundary: "emission", event: eventName } - ) + const decoded = (protocol.emitResultDecoder ??= getBoundaryResultDecoder(protocol.emit))(event) + if (Result.isFailure(decoded)) { + const eventName = getEventName(event) + throw new MachineSchemaDecodeError({ + machineId: machine.id, + boundary: "emission", + cause: decoded.failure, + ...(eventName === undefined ? {} : { event: eventName }) + }) + } + return decoded.success as Machine.EmittedEventOf } export const decodeInputSync = ( @@ -552,10 +593,20 @@ export const decodeStateValueSync = ( node: Machine.StateNode, value: unknown ): unknown => { + const schema = getStateNodeSchema(node) if (!isStateInput(value)) { - return decodeBoundarySync(machine, getStateNodeSchema(node), value, { boundary: "state", state: node.path }) + const decoded = getBoundaryResultDecoder(schema)(value) + if (Result.isFailure(decoded)) { + throw new MachineSchemaDecodeError({ + machineId: machine.id, + boundary: "state", + state: node.path, + cause: decoded.failure + }) + } + return decoded.success } - return makeBoundarySync(machine, getStateNodeSchema(node), value.input, { + return makeBoundarySync(machine, schema, value.input, { boundary: "state", state: node.path }) diff --git a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts index 0ec70dbc..46e8ca20 100644 --- a/packages/effect-machine/src/internal/machine/runtimeCompiled.ts +++ b/packages/effect-machine/src/internal/machine/runtimeCompiled.ts @@ -77,7 +77,8 @@ import { type StartProcess, stopAcknowledgedMessage, succeedAcknowledgedMessage, - type VersionedSnapshot + type VersionedSnapshot, + WorkMessage } from "./runtimeProtocol.js" const CompiledStoppedCompletion: unique symbol = Symbol("effect/Machine/CompiledStoppedCompletion") @@ -92,20 +93,22 @@ type CompiledRunState = "Initializing" | "Idle" | "Draining" /** * The endpoint of a compiled process: what its work, its children and its * parent send to. It delivers, so a refused event fails the machine when it is - * planned. `send` and `sendInspected` live on the prototype, so an endpoint - * costs no closure; an endpoint copied by spreading keeps only its fields and - * replaces both. + * planned. Prototype getters and methods keep an endpoint to one reference + * slot with no eager `stop` Effect or closure. */ class CompiledAddress implements ProcessEndpoint { - readonly id: string - readonly sessionId: string - declare readonly inspectionSubject?: Inspection.Subject - constructor(private readonly process: LocalProcess, readonly stop: Effect.Effect) { - this.id = process.id - this.sessionId = process.sessionId - if (process.inspectionSubject !== undefined) { - ;(this as { inspectionSubject?: Inspection.Subject }).inspectionSubject = process.inspectionSubject - } + constructor(private readonly process: LocalProcess) {} + get id(): string { + return this.process.id + } + get sessionId(): string { + return this.process.sessionId + } + get inspectionSubject(): Inspection.Subject | undefined { + return this.process.inspectionSubject + } + get stop(): Effect.Effect { + return Effect.suspend(() => this.process.stopFromProcess()) } send(event: unknown): Effect.Effect { return this.process.deliver(event, undefined, undefined) @@ -207,7 +210,7 @@ abstract class LocalProcess implements MachineRef { this.send = inspector === undefined ? (event) => this.offerMessage(event, "Sent") : (event) => this.sendPublic(event) - this.address = new CompiledAddress(this, Effect.suspend(() => this.stopFromProcess())) + this.address = new CompiledAddress(this) } protected get inspector(): InspectionRuntime.Runtime | undefined { @@ -281,7 +284,7 @@ abstract class LocalProcess implements MachineRef { return execution?._tag === "Compiled" ? execution.decodeEvent : undefined } - private get childless(): boolean { + protected get childless(): boolean { return executionIsChildless(this.logic.execution) } @@ -311,11 +314,12 @@ abstract class LocalProcess implements MachineRef { protected abstract run(): Effect.Effect /** The run state of an initialized process that does not run yet. */ - protected abstract readonly initializedRunState: CompiledRunState + protected abstract get initializedRunState(): CompiledRunState initializeCompiledSync(): Effect.Effect, unknown> { this.publishCreated() - if (!this.childless) this.childRuntime = this.makeChildRuntime() + const childless = this.childless + if (!childless) this.childRuntime = this.makeChildRuntime() const parent = this.options.parent const sendParent = this.options.sendParent ?? (parent === undefined ? noParentSend @@ -373,7 +377,7 @@ abstract class LocalProcess implements MachineRef { this.requestTerminationSync({ _tag: "Done", output: initialized.output }) } if ( - initialized.done === false && this.childless && + initialized.done === false && childless && this.lifecycle === "Active" && this.mailbox.items === undefined ) { @@ -557,7 +561,7 @@ abstract class LocalProcess implements MachineRef { return snapshot } - protected stopFromProcess(): Effect.Effect { + stopFromProcess(): Effect.Effect { const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid) return this.runState === "Initializing" ? request : request.pipe(Effect.andThen(Effect.interrupt)) } @@ -627,7 +631,8 @@ abstract class LocalProcess implements MachineRef { return Effect.suspend(() => { const inspector = this.inspector const subject = this.inspectionSubject - const message: ProcessMessage = inspector?.isActive() === true && subject !== undefined + const message: ProcessMessage = inspector?.isActive() === true && subject !== undefined && + !(event instanceof WorkMessage && sent === undefined) ? makeInspectedMessage( inspector, subject, @@ -659,32 +664,37 @@ abstract class LocalProcess implements MachineRef { if (this.mailbox.closed || this.lifecycle !== "Active") { return Effect.fail(new StoppedError()) } + const execution = this.logic.execution + const compiled = execution?._tag === "Compiled" ? execution : undefined let message = offered - const decode = this.decodeEvent - if (decoding !== "Decoded" && decode !== undefined) { - // Decoded inline, so a send allocates nothing more than before. - try { - message = decode(offered) - } catch (error) { - if (decoding === "Sent" && error instanceof MachineSchemaDecodeError) return Effect.fail(error) - message = new RefusedEvent(error) + if (decoding !== "Decoded") { + const decode = compiled?.decodeEvent + if (decode !== undefined && (decoding === "Sent" || !(offered instanceof WorkMessage))) { + // Decoded inline, so a send allocates nothing more than before. + try { + message = decode(offered) + } catch (error) { + if (decoding === "Sent" && error instanceof MachineSchemaDecodeError) return Effect.fail(error) + message = new RefusedEvent(error) + } } } - const inspector = this.inspector const subject = this.inspectionSubject - if (inspector !== undefined && subject !== undefined) publishInspectedSent(inspector, subject, message) + if (subject !== undefined) { + const inspector = this.inspector + if (inspector !== undefined) publishInspectedSent(inspector, subject, message) + } this.offerRevision += 1 // Initialization drains whatever it queued once it finishes, and an // idle machine has an empty mailbox, so it receives the message directly. - const context = this.compiledContext - const drain = this.runState === "Idle" && context !== undefined ? this.execution.drain : undefined - const runSync = drain?._tag === "Owned" ? drain.runSync : undefined - if (runSync === undefined) { - this.enqueue(message) - } if (this.runState !== "Idle") { + this.enqueue(message) return Effect.void } + const context = this.compiledContext + const runSync = context !== undefined && compiled !== undefined && compiled.drain._tag === "Owned" + ? compiled.drain.runSync + : undefined // An idle machine drains in the sender's turn, so a transition that // completes synchronously is committed before `send` returns. Sends // that arrive while draining only enqueue. @@ -704,6 +714,7 @@ abstract class LocalProcess implements MachineRef { this.scheduleChangesFlush(fiber.currentDispatcher) return Effect.void } + this.enqueue(message) return this.startWorker(undefined) }) ) @@ -1109,8 +1120,13 @@ abstract class LocalProcess implements MachineRef { return message } - beginCompiledMessage(message: ProcessMessage): void { - this.inFlightMessage = isAcknowledgedMessage(message) ? message : undefined + beginCompiledMessage(message: ProcessMessage): boolean { + if (isAcknowledgedMessage(message)) { + this.inFlightMessage = message + return true + } + this.inFlightMessage = undefined + return false } completeCompiledMessage(delivery: AcknowledgedDelivery): void { @@ -1279,6 +1295,19 @@ abstract class LocalProcess implements MachineRef { /** A machine: its compiled execution drains its mailbox. */ class MachineProcess extends LocalProcess { + constructor( + logic: ProcessLogic, + options: StartInternalOptions, + services: Context.Context, + sessionId: string + ) { + super(logic, options, services, sessionId) + } + + protected override get childless(): boolean { + return this.execution.childless + } + [acknowledgedSend]( event: unknown ): Effect.Effect, unknown | StoppedError> { @@ -1291,7 +1320,9 @@ class MachineProcess extends LocalProcess { }) } - protected readonly initializedRunState: CompiledRunState = "Idle" + protected get initializedRunState(): CompiledRunState { + return "Idle" + } protected makeChildRuntime(): ChildRuntime { return makeChildRuntimeSync( @@ -1334,7 +1365,9 @@ class MachineProcess extends LocalProcess { class LogicProcess extends LocalProcess { // A resident program runs from the end of its startup until it exits, so // the process never rests idle and every send only enqueues. - protected readonly initializedRunState: CompiledRunState = "Initializing" + protected get initializedRunState(): CompiledRunState { + return "Initializing" + } protected override readonly mailbox: ProcessMailbox = makeProcessMailbox() private updates: Semaphore.Semaphore | undefined @@ -1356,7 +1389,7 @@ class LogicProcess extends LocalProcess { * running, the process that stops itself never continues: the program is * interrupted, and the caller waits until it is. */ - protected override stopFromProcess(): Effect.Effect { + override stopFromProcess(): Effect.Effect { const request = this.requestTermination({ _tag: "Stopped" }).pipe(Effect.asVoid) return this.runState === "Initializing" ? request @@ -1465,8 +1498,8 @@ class CompiledProcessContextImpl implements CompiledProcessContext): void { - this.process.beginCompiledMessage(message) + beginMessage(message: ProcessMessage): boolean { + return this.process.beginCompiledMessage(message) } state(): unknown { @@ -1491,7 +1524,7 @@ export const startCompactCompiledInternal: StartProcess = Effect.fnUntraced(func logic: ProcessLogic, options: StartInternalOptions ) { - const sessionId = options.sessionId ?? (yield* options.runtime.nextSessionId) + const sessionId = options.sessionId ?? options.runtime.nextSessionIdSync() const services = yield* Effect.context() const execution = logic.execution?._tag === "Compiled" ? logic.execution : undefined const process = logic.execution?._tag === "Compiled" diff --git a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts index 8c078137..c7e40dea 100644 --- a/packages/effect-machine/src/internal/machine/runtimeProtocol.ts +++ b/packages/effect-machine/src/internal/machine/runtimeProtocol.ts @@ -152,7 +152,7 @@ export const decodeSent = ( * @internal */ export const decodeDelivered = (decode: EventDecoder | undefined, event: unknown): unknown => { - if (decode === undefined) return event + if (decode === undefined || event instanceof WorkMessage) return event try { return decode(event) } catch (error) { @@ -285,7 +285,7 @@ export interface PreparedProcess< export interface ProcessEndpoint { readonly id: string readonly sessionId: string - readonly inspectionSubject?: Inspection.Subject + readonly inspectionSubject?: Inspection.Subject | undefined readonly stop: Effect.Effect readonly send: (event: Event) => Effect.Effect readonly sendInspected?: ( @@ -293,9 +293,9 @@ export interface ProcessEndpoint { source: Inspection.Subject | undefined, causedBy: Inspection.Causation | undefined ) => Effect.Effect - readonly [acknowledgedSend]?: ( - event: Event - ) => Effect.Effect, unknown | StoppedError> + readonly [acknowledgedSend]?: + | ((event: Event) => Effect.Effect, unknown | StoppedError>) + | undefined } export const isMachineTarget = (value: unknown): value is MachineTarget => @@ -392,8 +392,8 @@ export interface CompiledProcessContext { readonly ownedChildren: OwnedChildRuntime readonly poll: () => Option.Option readonly pollMessage: () => Option.Option> - /** Marks a message delivered without the mailbox as the one in flight. */ - readonly beginMessage: (message: ProcessMessage) => void + /** Marks a message delivered without the mailbox as the one in flight, and reports whether it is acknowledged. */ + readonly beginMessage: (message: ProcessMessage) => boolean readonly state: () => State readonly completeMessage: (delivery: AcknowledgedDelivery) => void readonly commit: (state: State) => Effect.Effect | undefined @@ -686,6 +686,7 @@ export interface ProcessRuntime { ) => Effect.Effect, any, any> readonly makeChildLogic: MakeChildLogic readonly nextSessionId: Effect.Effect + readonly nextSessionIdSync: () => string inspection?: InspectionRuntime.Runtime } @@ -698,11 +699,15 @@ export const makeProcessRuntime = ( // session counter and optional inspection runtime, independent of other roots. class Runtime implements ProcessRuntime { declare inspection?: InspectionRuntime.Runtime - readonly nextSessionId: Effect.Effect + private sessionIdCounter = 0 + private _nextSessionId: Effect.Effect | undefined = undefined + + nextSessionIdSync(): string { + return `machine:${this.sessionIdCounter++}` + } - constructor() { - let sessionIdCounter = 0 - this.nextSessionId = Effect.sync(() => `machine:${sessionIdCounter++}`) + get nextSessionId(): Effect.Effect { + return this._nextSessionId ??= Effect.sync(() => this.nextSessionIdSync()) } get start(): StartProcess { @@ -814,7 +819,7 @@ export interface StartInternalOptions { ref: MachineRef, requestStop: Effect.Effect ) => Effect.Effect - readonly onReadySync?: (ref: MachineRef) => boolean + readonly onReadySync?: ((ref: MachineRef) => boolean) | undefined readonly onStop?: Effect.Effect /** Runs synchronously once the process has terminated, with its reference. */ readonly onStopSync?: (ref: MachineRef) => void @@ -860,10 +865,6 @@ interface OwnedChildSpawnOptions { isCurrent: () => boolean, snapshot: Extract, { readonly status: "active" }> ) => Effect.Effect - readonly sendParent: ( - isCurrent: () => boolean, - event: unknown - ) => Effect.Effect readonly programKind?: Inspection.ProgramInvocation["kind"] } @@ -896,15 +897,76 @@ export interface ChildRuntime { readonly owned: OwnedChildRuntime } +/** + * Parent endpoint exposed to an owned invocation. Prototype getters and methods + * keep each running child free of per-child parent endpoint closures. + */ +class OwnedChildParent implements ProcessEndpoint { + startedChild: MachineRef | undefined = undefined + + constructor( + readonly owner: OwnedChildRuntimeImpl, + readonly childId: string, + readonly token: symbol, + readonly ownerKey: string + ) {} + + get id(): string { + return this.owner.self.id + } + + get sessionId(): string { + return this.owner.self.sessionId + } + + get inspectionSubject(): Inspection.Subject | undefined { + return this.owner.self.inspectionSubject + } + + get stop(): Effect.Effect { + return this.owner.self.stop + } + + isCurrent(): boolean { + const entry = this.owner.registry.children.get(this.childId) + return entry?.token === this.token && entry.ownerKey === this.ownerKey && entry.ownerActive === true + } + + unregister(): void { + unregisterChild(this.owner.registry, this.childId, this.token) + } + + send(event: unknown): Effect.Effect { + return this.isCurrent() ? this.owner.self.send(event) : Effect.void + } + + sendInspected( + event: unknown, + source: Inspection.Subject | undefined, + causedBy: Inspection.Causation | undefined + ): Effect.Effect { + return this.isCurrent() ? sendEndpoint(this.owner.self, event, source, causedBy) : Effect.void + } + + get [acknowledgedSend](): + | ((event: unknown) => Effect.Effect, unknown | StoppedError>) + | undefined + { + const send = this.owner.sendAcknowledged + if (send === undefined) return undefined + return (event: unknown) => this.isCurrent() ? send(event) : Effect.interrupt + } +} + class OwnedChildRuntimeImpl implements OwnedChildRuntime { private scopedServices: Context.Context | undefined constructor( - private readonly registry: ChildRegistry, - private readonly self: ProcessEndpoint, + readonly registry: ChildRegistry, + readonly self: ProcessEndpoint, private readonly runtime: ProcessRuntime, private readonly services?: Context.Context, - private readonly sendAcknowledged?: ( + readonly sendAcknowledged?: ( event: unknown ) => Effect.Effect, unknown | StoppedError> ) {} @@ -926,96 +988,78 @@ class OwnedChildRuntimeImpl implements OwnedChildRuntime { options: OwnedChildSpawnOptions ): Effect.Effect { const token = Symbol() - let startedChild: MachineRef | undefined - const isCurrent = (): boolean => { - const entry = this.registry.children.get(options.id) - return entry?.token === token && entry.ownerKey === options.key && entry.ownerActive === true - } + const id = options.id + const key = options.key + const onOutcome = options.onOutcome + const onSnapshot = options.onSnapshot + const parent = new OwnedChildParent(this, id, token, key) return Effect.suspend(() => { if (this.registry.closed) return Effect.interrupt - if (this.has(options.key) || this.registry.children.has(options.id)) { + if (this.registry.children.size > 0 && (this.has(key) || this.registry.children.has(id))) { return Effect.fail(new ChildAlreadyExistsError({ id: options.duplicateId })) } const logic = typeof source === "function" ? source() : this.runtime.makeChildLogic(source.child.machine, source.input?.()) + const descriptor = typeof source === "function" ? undefined : source.child const scope = this.registry.scope ??= Scope.makeUnsafe("parallel") - this.registry.children.set(options.id, { + this.registry.children.set(id, { _tag: "Starting", token, - ownerKey: options.key, + ownerKey: key, ownerActive: true }) - const parent: ProcessEndpoint = { - ...this.self, - send: (event) => options.sendParent(isCurrent, event), - sendInspected: (event, source, causedBy) => - isCurrent() ? sendEndpoint(this.self, event, source, causedBy) : Effect.void, - ...(this.sendAcknowledged === undefined - ? undefined - : { - [acknowledgedSend]: (event: unknown) => - isCurrent() - ? this.sendAcknowledged!(event) - : Effect.interrupt - }) - } - const startOptions: StartInternalOptions = { + const isCurrent = () => parent.isCurrent() + const startOptions: { -readonly [K in keyof StartInternalOptions]: StartInternalOptions[K] } = { detached: true, - id: options.id, - sendParent: (event) => options.sendParent(isCurrent, event), - onOutcome: (outcome) => options.onOutcome(isCurrent, outcome, startedChild?.sessionId), - ...(options.onSnapshot === undefined + id, + sendParent: (event) => parent.send(event), + onOutcome: (outcome) => onOutcome(isCurrent, outcome, parent.startedChild?.sessionId), + ...(onSnapshot === undefined ? undefined - : { onSnapshot: (snapshot) => options.onSnapshot!(isCurrent, snapshot) }), + : { onSnapshot: (snapshot) => onSnapshot(isCurrent, snapshot) }), onReadySync: (child) => { - startedChild = child - return registerChild( - this.registry, - options.id, - token, - child, - typeof source === "function" ? undefined : source.child - ) + parent.startedChild = child + startOptions.onReadySync = undefined + return registerChild(this.registry, id, token, child, descriptor) }, - onStopSync: () => unregisterChild(this.registry, options.id, token), + onStopSync: () => parent.unregister(), skipStoppedOutcome: true, parent, runtime: this.runtime, - origin: { _tag: "Invoke", ownerPath: options.path, invokeId: options.duplicateId }, - ...(options.programKind === undefined || this.runtime.inspection === undefined || - this.self.inspectionSubject === undefined + ...(this.runtime.inspection === undefined ? undefined : { - programInvocation: { - id: options.duplicateId, - owner: this.self.inspectionSubject, - ownerPath: options.path, - kind: options.programKind - } + origin: { _tag: "Invoke" as const, ownerPath: options.path, invokeId: options.duplicateId }, + ...(options.programKind === undefined || this.self.inspectionSubject === undefined + ? undefined + : { + programInvocation: { + id: options.duplicateId, + owner: this.self.inspectionSubject, + ownerPath: options.path, + kind: options.programKind + } + }) }) } const execution = logic.execution - const synchronous = this.services !== undefined && options.onSnapshot === undefined && + const synchronous = this.services !== undefined && onSnapshot === undefined && execution?._tag === "Compiled" && execution.childless && execution.drain._tag === "Owned" && execution.initialSync !== undefined const start = synchronous - ? Effect.flatMap( - this.runtime.nextSessionId, - (sessionId) => - this.runtime.startCompiledSync( - logic, - startOptions, - this.scopedServices ??= Context.add(this.services!, Scope.Scope, scope), - sessionId - ) + ? this.runtime.startCompiledSync( + logic, + startOptions, + this.scopedServices ??= Context.add(this.services, Scope.Scope, scope), + this.runtime.nextSessionIdSync() ) : this.runtime.start(logic, startOptions) const guarded = start.pipe( Effect.onExit((exit) => { if (Exit.isSuccess(exit)) return Effect.void - unregisterChild(this.registry, options.id, token) - return startedChild === undefined ? Effect.void : startedChild.stop + parent.unregister() + return parent.startedChild === undefined ? Effect.void : parent.startedChild.stop }) ) return (synchronous ? guarded : Scope.provide(guarded, scope)).pipe(Effect.asVoid) diff --git a/packages/effect-machine/src/internal/machine/step.ts b/packages/effect-machine/src/internal/machine/step.ts index 833cb651..c59a006f 100644 --- a/packages/effect-machine/src/internal/machine/step.ts +++ b/packages/effect-machine/src/internal/machine/step.ts @@ -10,22 +10,25 @@ * reports, so work of an earlier entry, of a step that was not kept, or of a * machine before it resumed, is never taken for the work that runs. * - * A step plans with the execution plan of its machine, `compileExecutionPlan`, - * which the compiled local runtime uses too: an indexed kernel for the machines - * and events it covers, and the reference planner for anything else. The choice - * is made once per machine. + * A step plans with the execution plan passed to its kernel — normally + * `compileExecutionPlan` (an indexed kernel for the machines and events it + * covers, and the reference planner for anything else), or + * `referenceExecutionPlan` when a caller forces the reference planner. * * A step function has an {@link Ownership}. A `"Persistent"` step, which * `Machine.toStep` returns, takes and returns immutable state values. An * `"Owned"` step, for a host that keeps only its latest state, takes each state - * over and may update its storage in place. Both are one implementation, which - * differs only in whether a plan copies or updates what it writes. + * over and may update its storage in place. See `build` for the full list of + * differences between the two ownerships. * * A host applies a step in one order, as the local host in `stepHost.ts` - * does: commands, the work of exited states, the new state, emitted events, and - * the work of entered states. A step calls no user code for the work it lists: - * each piece of work evaluates its source and its input mapper when its host - * starts it, at most once, inside its own startup failure boundary. + * does: commands, `stop` (the work of exited states, or all work when the + * machine fails or is stopped), the new state, emitted events, `start` (the + * work of entered states), and `stopAfter` (remaining work of states that + * stayed active when the machine reached a final state). A step calls no user + * code for the work it lists: each piece of work evaluates its source and its + * input mapper when its host starts it, at most once, inside its own startup + * failure boundary. * * @since 0.48.0 */ @@ -199,6 +202,41 @@ interface PublishedMicrostep { readonly changed: boolean } +/** + * Shared planning host base: holds only the machine and execution plan, so + * subclasses such as the local host can expose their scope's targets and + * children from the prototype without duplicating own slots. + * + * @internal + */ +export abstract class PlanningBase implements Configuration.PlanningMachineReferences { + constructor( + readonly machine: Machine.Any, + readonly plan: ExecutionPlan.CompiledExecutionPlan + ) {} + + abstract readonly self: MachineTarget + abstract readonly parent: MachineTarget | undefined + abstract readonly children: Children + abstract readonly ambient: boolean + abstract readonly services: Context.Context; + + // A host is compared by identity: hashing a state, as a failure that holds one + // may be hashed, never reads the targets of the host. + [Hash.symbol](): number { + return Hash.random(this) + } + + [Equal.symbol](that: unknown): boolean { + return this === that + } + + /** What the source and input mapper of work receive, built for each entry that resolves work. */ + get capabilities(): InvocationResolution.InvocationCapabilities { + return { self: this.self, parent: this.parent, children: childOwnerOf(this.children) } + } +} + /** * The machine of a step function, the plan it steps with, and the host it runs * on: what its transitions address, and the children its work acts on. A host @@ -208,12 +246,13 @@ interface PublishedMicrostep { * * @internal */ -export class Planning implements Configuration.PlanningMachineReferences { +export class Planning extends PlanningBase { #services: Context.Context | undefined + readonly children: Children constructor( - readonly machine: Machine.Any, - readonly plan: ExecutionPlan.CompiledExecutionPlan, + machine: Machine.Any, + plan: ExecutionPlan.CompiledExecutionPlan, readonly self: MachineTarget, readonly parent: MachineTarget | undefined, /** The children of the machine, or `undefined` for a host that owns them itself. */ @@ -225,26 +264,10 @@ export class Planning implements Configuration.PlanningMachineReferences { */ readonly ambient = false ) { + super(machine, plan) this.children = children ?? (this as unknown as Children) } - readonly children: Children; - - // A host is compared by identity: hashing a state, as a failure that holds one - // may be hashed, never reads the targets of the host. - [Hash.symbol](): number { - return Hash.random(this) - } - - [Equal.symbol](that: unknown): boolean { - return this === that - } - - /** What the source and input mapper of work receive, built for each entry that resolves work. */ - get capabilities(): InvocationResolution.InvocationCapabilities { - return { self: this.self, parent: this.parent, children: childOwnerOf(this.children) } - } - /** The services through which work acts on the children of this machine. */ get services(): Context.Context { return this.#services ??= servicesOf(this.children) @@ -279,7 +302,7 @@ export class State { #handedOver = false constructor( - readonly planning: Planning, + readonly planning: PlanningBase, /** The execution state of the plan, or `undefined` for a state that rests. */ execution: unknown, configuration: Configuration.ActiveConfiguration | undefined, @@ -301,17 +324,23 @@ export class State { /** The execution state of the plan. Building it again from the snapshot may throw. */ get execution(): unknown { - return this.#execution ??= this.planning.plan.fromConfiguration(this.configuration) + const execution = this.#execution + return execution !== undefined + ? execution + : (this.#execution = this.planning.plan.fromConfiguration(this.configuration)) } get configuration(): Configuration.ActiveConfiguration { - return this.#configuration ??= this.#execution === undefined + const configuration = this.#configuration + if (configuration !== undefined) return configuration + return this.#configuration = this.#execution === undefined ? Configuration.normalizeConfigurationSync(this.planning.machine, this.#snapshot!) : this.planning.plan.toConfiguration(this.#execution) } get snapshot(): Machine.Snapshot { - return this.#snapshot ??= this.planning.plan.snapshot(this.#execution) + const snapshot = this.#snapshot + return snapshot !== undefined ? snapshot : (this.#snapshot = this.planning.plan.snapshot(this.#execution)) } /** This state with other running work, keeping what was read of it. */ @@ -324,22 +353,47 @@ export class State { return new State(this.planning, undefined, undefined, this.snapshot, this.running, this.runs, this.exit) } + /** Updates an owned state in place to rest without allocating a new wrapper. */ + restInPlace(): this { + if (this.#handedOver) { + throw new Error( + "An owned MachineStep state was reused after it was handed over to a step: never reuse an owned state after passing it" + ) + } + this.#snapshot ??= this.planning.plan.snapshot(this.#execution) + this.#execution = undefined + this.#configuration = undefined + return this + } + + /** Updates an owned state's execution and snapshot in place when a move needs no new state wrapper. */ + replaceExecution(execution: unknown, snapshot: Machine.Snapshot): void { + this.#execution = execution + this.#configuration = undefined + this.#snapshot = snapshot + } + /** What was built of this state, without building anything. */ get built(): { readonly execution: unknown; readonly configuration: Configuration.ActiveConfiguration | undefined } { return { execution: this.#execution, configuration: this.#configuration } } + /** Checks that an owned state has not been handed over, without marking it handed over. */ + assertNotHandedOver(): void { + if (this.#handedOver) { + throw new Error( + "An owned MachineStep state was reused after it was handed over to a step: never reuse an owned state after passing it" + ) + } + } + /** * Hands an owned state over to one step. From this call on, the caller * promises never to reuse this state, nor any step that returned it: the step * may write it in place. Handing over a state twice throws. */ handOverNeverReuse(): this { - if (this.#handedOver) { - throw new Error( - "An owned MachineStep state was reused after it was handed over to a step: never reuse an owned state after passing it" - ) - } + this.assertNotHandedOver() this.#handedOver = true return this } @@ -365,9 +419,15 @@ const noPaths: Paths = { exited: empty, entered: empty } class InitialPaths implements Paths { #entered: ReadonlyArray | undefined readonly exited: ReadonlyArray = empty - constructor(private readonly machine: Machine.Any, private readonly paths: () => ReadonlyArray) {} + constructor( + private readonly machine: Machine.Any, + private readonly paths: ReadonlyArray | (() => ReadonlyArray) + ) {} get entered(): ReadonlyArray { - return this.#entered ??= Planner.sortEntryPaths(this.machine, this.paths()) + return this.#entered ??= Planner.sortEntryPaths( + this.machine, + typeof this.paths === "function" ? this.paths() : this.paths + ) } } @@ -396,6 +456,7 @@ export class Step { readonly commands: ReadonlyArray, readonly stop: ReadonlyArray, readonly start: ReadonlyArray, + readonly stopAfter: ReadonlyArray = empty, /** The paths of an initial step, which its microsteps do not list. Read from the microsteps otherwise. */ paths?: Paths ) { @@ -487,10 +548,23 @@ export interface MachineStep { export type OwnedMachineStep = MachineStep<"Owned"> /** - * The step functions of a machine, built once for each machine, ownership and - * planner, for every host that runs it. A state carries the {@link Planning} - * of its host, so only `start` and `resume`, which take no state, are passed - * one. + * The step functions of a machine, built once for each `(ownership, plan)` + * pair, for every host that runs it. A state carries the {@link PlanningBase} + * of its host, so only `start`, `resume`, and `fromSnapshot`, which take no + * state, are passed one. + * + * Host-level optimizations on this kernel: + * - `retain`: passing `retain: false` to `start`, `sendDecoded`, `settle`, + * `element`, or `report` tells the step that its host reads no microstep + * (only `snapshot`, `exited`, `entered`, `commands`, `emitted`, work, and + * `exit`). An `"Owned"` plan may write in place without retaining + * transitions, and `start` takes `plan.initial` when available. + * - `ambient`: on {@link PlanningBase}, `ambient: true` tells work accessors + * that the host runs work inside the machine's own services already, so work + * does not wrap effects/streams/logic with `planning.services` again. + * - `move`: unretained fast path for a host that commits snapshots directly. + * - `rest` and `fromSnapshot`: let an idle host drop execution storage and + * rebuild it from the published snapshot when the next message arrives. * * @internal */ @@ -505,27 +579,57 @@ export interface Kernel */ readonly sendDecoded: (state: State, event: Machine.EventOf, retain?: boolean) => Step /** - * Plans a decoded event whose microsteps no one reads, as `sendDecoded` - * without `retain` does. A step that only moves the machine to a new state, - * with no command, emitted event, work or end, is returned as that state, so - * a host that applies it allocates no step: the state passed in when the - * event changed nothing, and a new state otherwise. + * Plans a decoded event whose microsteps no one reads, as `sendDecoded` with + * `retain: false` does, for a host that commits snapshots directly. + * + * - Returns `undefined` when the event changed nothing or the machine has + * already ended (an `"Owned"` state remains live). + * - When a childless machine only moves to a new state (no commands, + * emissions, or end): an `"Owned"` kernel updates `state` in place and + * returns the new snapshot with no `State` or `Step` allocation (keeping + * `state` live); a `"Persistent"` kernel leaves `state` untouched and + * returns a `Step` holding the new state. + * - Otherwise (invoking machine, commands, emissions, completion, or throw) + * returns a `Step`, handing an `"Owned"` `state` over unless the step + * returned `state` unchanged. */ - readonly move: (state: State, event: Machine.EventOf) => State | Step + readonly move: ( + state: State, + event: Machine.EventOf + ) => Machine.Snapshot | Step | undefined readonly settle: (state: State, work: Work, exit: Exit.Exit, retain?: boolean) => Step readonly element: (state: State, work: Work, element: unknown, retain?: boolean) => Step readonly report: (state: State, work: Work, snapshot: unknown, retain?: boolean) => Step + /** Whether `work` observes active snapshots (so a host subscribes to them). */ + readonly observesSnapshots: (work: Work) => boolean /** - * Starts the machine with `input`. Without `retain`, a machine that the - * execution plan starts itself starts there, and its step lists no microstep. + * The invocation event that `settle` will plan for `exit`, for a host that + * attaches inspection causation to its mailbox message, or `undefined` when + * `settle` fails the machine directly or ignores the result. + */ + readonly settleEvent: (work: Work, exit: Exit.Exit) => unknown + /** + * The invocation event that `element` will plan for `value`, for inspection + * causation, or `undefined` when ignored. + */ + readonly elementEvent: (work: Work, value: unknown) => unknown + /** + * The invocation event that `report` will plan for `snapshot`, for inspection + * causation, or `undefined` when ignored. + */ + readonly snapshotEvent: (work: Work, snapshot: unknown) => unknown + /** + * Starts the machine with `input`. With `retain: false`, a machine that + * `plan.initial` covers starts directly on the plan and its step lists no + * microsteps; `exited`, `entered`, `snapshot`, work, and `exit` stay equal. */ readonly start: ( - planning: Planning, + planning: PlanningBase, input: ReadonlyArray, retain?: boolean ) => Exit.Exit, unknown> readonly resume: ( - planning: Planning, + planning: PlanningBase, snapshot: Machine.Snapshot, progress?: ReadonlyArray ) => Exit.Exit, unknown> @@ -536,11 +640,12 @@ export interface Kernel * invokes work, whose work a snapshot does not hold, and for a snapshot that * does not normalize. */ - readonly fromSnapshot: (planning: Planning, snapshot: Machine.Snapshot) => State + readonly fromSnapshot: (planning: PlanningBase, snapshot: Machine.Snapshot) => State /** * The state as it rests, for a host that keeps a machine idle: its snapshot, * its work and its runs. A later step builds its execution state again from - * the snapshot. An owned state is handed over. + * the snapshot. `"Persistent"` returns a new resting state; `"Owned"` clears + * execution and configuration storage in place and returns the same state. */ readonly rest: (state: State) => State } @@ -560,7 +665,7 @@ class WorkOf { constructor( invocation: InvocationResolution.ResolvedInvocation, readonly run: number, - private readonly planning: Planning + private readonly planning: PlanningBase | undefined ) { this[WorkTypeId] = invocation } @@ -615,7 +720,7 @@ class WorkOf { /** Work acts on the children of its machine through the services of its host. */ private provide(effect: Effect.Effect): Effect.Effect { const planning = this.planning - return planning.ambient + return planning === undefined || planning.ambient ? effect : Effect.updateContext(effect, (context: Context.Context) => Context.merge(context, planning.services)) } @@ -637,7 +742,7 @@ class WorkOf { return this.evaluate((invocation: InvocationResolution.StreamInvocation) => { const planning = this.planning const stream = Stream.scoped(invocation.stream()) - return planning.ambient + return planning === undefined || planning.ambient ? stream : Stream.updateContext(stream, (context: Context.Context) => Context.merge(context, planning.services)) }) @@ -646,7 +751,7 @@ class WorkOf { logic(): Exit.Exit { return this.evaluate((invocation: InvocationResolution.LogicInvocation) => { const scoped = LogicScope.scoped(invocation.logic()) - if (this.planning.ambient) return scoped + if (this.planning === undefined || this.planning.ambient) return scoped return { initial: (context) => this.provide(scoped.initial(context)), run: (context) => this.provide(scoped.run(context)) @@ -734,11 +839,50 @@ const invokingPaths = (machine: Machine.Any): ReadonlySet => { return paths } +const observesSnapshots = (work: Work): boolean => work[WorkTypeId].channels.snapshot + +const settleEvent = (work: Work, exit: Exit.Exit): unknown => { + const decision = InvocationOutcome.decide(work[WorkTypeId], { current: true }, InvocationOutcome.fromExit(exit)) + return decision._tag === "Deliver" ? decision.event : undefined +} + +const elementEvent = (work: Work, value: unknown): unknown => { + const invocation = work[WorkTypeId] + if (invocation._tag !== "Stream") return undefined + const decision = InvocationOutcome.decideElement(invocation, { current: true }, value) + return decision._tag === "Deliver" ? decision.event : undefined +} + +const snapshotEvent = (work: Work, snapshot: unknown): unknown => { + const invocation = work[WorkTypeId] + if (invocation._tag !== "Logic" && invocation._tag !== "Child") return undefined + const decision = InvocationOutcome.decideSnapshot(invocation, { current: true }, { + status: "active", + state: snapshot + }) + return decision._tag === "Deliver" ? decision.event : undefined +} + /** * The step functions of `machine`, which plan with `plan` and take states of - * `ownership`. The ownership is passed to every plan, which copies what it - * writes in a persistent state and writes an owned one in place: that is the - * only difference between the two. + * `ownership`. Every difference between `"Owned"` and `"Persistent"` lives here: + * + * 1. **Execution-state writes**: `ownership` is passed to `plan.planDecoded` + * (a `"Persistent"` plan copies what it writes; an `"Owned"` flat indexed + * plan writes active values in place, restoring them on throw). + * 2. **Handover enforcement**: `"Owned"` marks a passed state handed over so + * reusing it throws, giving it back only when a step returns that exact + * state unchanged or refuses the event. + * 3. **Retained configuration in `enter`**: `"Owned"` drops the resolved + * `ActiveConfiguration` after resolving invocations so idle or subsequent + * steps do not retain it; `"Persistent"` keeps it on the state. + * 4. **Resting (`rest`)**: `"Owned"` clears execution and configuration storage + * in place on the state (`restInPlace`); `"Persistent"` allocates a new + * resting `State`. + * 5. **Unretained childless moves (`move`)**: when a childless machine only + * moves to a new state (no commands, emissions, or end), `"Owned"` updates + * `state` in place and returns its new `Snapshot` directly; `"Persistent"` + * returns a `Step` with a fresh `State`. */ const build = ( machine: Machine.Any, @@ -747,13 +891,14 @@ const build = ( ): Kernel => { // A machine that invokes no work runs none, so its steps track none. const invoking = invokingPaths(machine) + const decodeEvent = Protocol.makeEventDecoderSync(machine) /** Describes one invocation, without calling any of its user code. */ const describe = ( - planning: Planning, + planning: PlanningBase, invocation: InvocationResolution.ResolvedInvocation, run: number - ): Work => new WorkOf(invocation, run, planning) as unknown as Work + ): Work => new WorkOf(invocation, run, planning.ambient ? undefined : planning) as unknown as Work /** * Commands of a transition, as data, in order. A command that selects a @@ -803,7 +948,7 @@ const build = ( /** The logical state that a step reached, and what was built of it already. */ interface Reached { - readonly planning: Planning + readonly planning: PlanningBase readonly execution: unknown readonly configuration: Configuration.ActiveConfiguration | undefined readonly snapshot: Machine.Snapshot | undefined @@ -811,7 +956,7 @@ const build = ( } const reached = ( - planning: Planning, + planning: PlanningBase, execution: unknown, configuration: Configuration.ActiveConfiguration | undefined, snapshot: Machine.Snapshot | undefined, @@ -819,14 +964,17 @@ const build = ( ): Reached => ({ planning, execution, configuration, snapshot, runs }) /** - * A machine that ends in a step stops all of its work. `next` is the state the - * step reached, or the state before it when the step could not be applied. + * A machine that ends in a step stops all of its work: `stop` before + * publishing the final state, and `stopAfter` after publishing and delivering + * emitted events. `next` is the state the step reached, or the state before + * it when the step could not be applied. */ const ended = ( next: Reached, stop: ReadonlyArray, exit: Exit.Exit, - published: Published = nothing + published: Published = nothing, + stopAfter: ReadonlyArray = empty ): Step => new Step( new State(next.planning, next.execution, next.configuration, next.snapshot, empty, next.runs, exit), @@ -836,6 +984,7 @@ const build = ( published.commands, stop, empty, + stopAfter, published.paths ) @@ -869,7 +1018,12 @@ const build = ( if (entered.some(([paths]) => paths.some((path) => invoking.has(path)))) { configuration ??= plan.toConfiguration(next.execution) for ( - const group of InvocationResolution.resolveEntries(machine, configuration, entered, next.planning.capabilities) + const group of InvocationResolution.resolveEntries( + machine, + configuration, + entered, + () => next.planning.capabilities + ) ) { const run = runs++ for (const invocation of group.invocations) { @@ -904,6 +1058,7 @@ const build = ( published.commands, stop, start ?? empty, + empty, published.paths ) } @@ -912,26 +1067,12 @@ const build = ( * Plans one event on a state that runs `running`: a public event that `send` * decoded, or the invocation event of a result. */ - function advance( + const advance = ( state: State, running: ReadonlyArray, event: Machine.EventOf | InvocationEvent.InvocationEvent, retain: boolean - ): Step - function advance( - state: State, - running: ReadonlyArray, - event: Machine.EventOf | InvocationEvent.InvocationEvent, - retain: false, - bare: true - ): State | Step - function advance( - state: State, - running: ReadonlyArray, - event: Machine.EventOf | InvocationEvent.InvocationEvent, - retain: boolean, - bare = false - ): State | Step { + ): Step => { let planned: ExecutionPlan.ExecutionMacrostep try { // A step publishes its microsteps, so a plan retains them unless its host reads none. @@ -942,7 +1083,6 @@ const build = ( return ended(endedFrom(state), latestFirst(running), exitOfThrow(error), { ...nothing, event: planning }) } if (planned.microsteps.length === 0) { - if (bare && running === state.running) return state return new Step( running === state.running ? state : state.withRunning(running), planned.event, @@ -956,9 +1096,6 @@ const build = ( const commanded = planned.commands.length === 0 ? undefined : commandsOf(planned.commands, running) const commands = commanded === undefined ? empty : commanded.commands if (invoking.size === 0) { - if (bare && !planned.done && commands.length === 0 && planned.emittedEvents.length === 0) { - return new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined) - } return planned.done ? ended( reached(state.planning, planned.next, undefined, undefined, state.runs), @@ -986,7 +1123,7 @@ const build = ( const next = reached(state.planning, planned.next, undefined, undefined, state.runs) const { kept, stop } = InvocationChanges.partition(commanded === undefined ? running : commanded.running, changes) if (planned.done) { - return ended(next, [...stop, ...latestFirst(kept)], Exit.succeed(planned.output), published) + return ended(next, stop, Exit.succeed(planned.output), published, latestFirst(kept)) } return enter(next, InvocationChanges.entries(changes), kept, stop, published) } @@ -1005,7 +1142,7 @@ const build = ( /** The state a step starts in, from a configuration that the reference planner built. */ const initial = ( - planning: Planning, + planning: PlanningBase, configuration: Configuration.ActiveConfiguration, snapshot: Machine.Snapshot ): Reached => reached(planning, plan.fromConfiguration(configuration), configuration, snapshot, 0) @@ -1047,7 +1184,7 @@ const build = ( } const startUnretained = ( - planning: Planning, + planning: PlanningBase, initialOf: NonNullable, input: ReadonlyArray ): Exit.Exit, unknown> => { @@ -1063,7 +1200,7 @@ const build = ( microsteps: empty, emitted: empty, commands: empty, - paths: new InitialPaths(machine, () => planned.initialEntryPaths) + paths: new InitialPaths(machine, planned.initialEntryPaths) } const next = reached(planning, planned.configuration, configuration, planned.state, 0) if (planned.done) { @@ -1072,7 +1209,7 @@ const build = ( return Exit.succeed( enter( next, - invoking.size === 0 ? empty : InvocationResolution.initialEntries(machine, configuration), + invoking.size === 0 ? empty : [[planned.initialEntryPaths, Planner.InitialEvent]], empty, empty, published @@ -1089,7 +1226,7 @@ const build = ( if (state.exit !== undefined) return Exit.fail(new StoppedError()) let decoded: Machine.EventOf try { - decoded = Protocol.decodeEventSync(machine, event) + decoded = decodeEvent(event) } catch (error) { // Only an event that its schema refuses is rejected. Any other throw is // a defect of the machine, as it is when the planner decodes the event. @@ -1103,8 +1240,91 @@ const build = ( const sendDecoded = (state: State, event: Machine.EventOf, retain = true): Step => state.exit === undefined ? advance(state, state.running, event, retain) : unchanged(state) - const move = (state: State, event: Machine.EventOf): State | Step => - state.exit === undefined ? advance(state, state.running, event, false, true) : unchanged(state) + const moveChildlessOwned = ( + state: State, + event: Machine.EventOf + ): Machine.Snapshot | Step | undefined => { + state.assertNotHandedOver() + if (state.exit !== undefined) return undefined + let planned: ExecutionPlan.ExecutionMacrostep + try { + planned = plan.planDecoded(state.execution, event, "Owned", false, state.planning) + } catch (error) { + state.handOverNeverReuse() + return ended(endedFrom(state), empty, exitOfThrow(error), { ...nothing, event }) + } + if (planned.microsteps.length === 0) return undefined + if (!planned.done && planned.commands.length === 0 && planned.emittedEvents.length === 0) { + const snapshot = plan.snapshot(planned.next) + state.replaceExecution(planned.next, snapshot) + return snapshot + } + state.handOverNeverReuse() + const commands = planned.commands.length === 0 ? empty : commandsOf(planned.commands, empty).commands + return planned.done + ? ended( + reached(state.planning, planned.next, undefined, undefined, state.runs), + empty, + Exit.succeed(planned.output), + { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } + ) + : new Step( + new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), + planned.event, + planned.microsteps, + planned.emittedEvents, + commands, + empty, + empty + ) + } + + const move = ( + state: State, + event: Machine.EventOf + ): Machine.Snapshot | Step | undefined => { + if (state.exit !== undefined) return undefined + if (invoking.size > 0) { + const step = advance(state, state.running, event, false) + return step.state === state && !step.planned && step.exit === undefined ? undefined : step + } + let planned: ExecutionPlan.ExecutionMacrostep + try { + planned = plan.planDecoded(state.execution, event, ownership, false, state.planning) + } catch (error) { + return ended(endedFrom(state), empty, exitOfThrow(error), { ...nothing, event }) + } + if (planned.microsteps.length === 0) return undefined + if (!planned.done && planned.commands.length === 0 && planned.emittedEvents.length === 0) { + const snapshot = plan.snapshot(planned.next) + return new Step( + new State(state.planning, planned.next, undefined, snapshot, empty, state.runs, undefined), + planned.event, + planned.microsteps, + empty, + empty, + empty, + empty + ) + } + const commands = planned.commands.length === 0 ? empty : commandsOf(planned.commands, empty).commands + return planned.done + ? ended( + reached(state.planning, planned.next, undefined, undefined, state.runs), + empty, + Exit.succeed(planned.output), + { event: planned.event, microsteps: planned.microsteps, emitted: planned.emittedEvents, commands } + ) + : new Step( + new State(state.planning, planned.next, undefined, undefined, empty, state.runs, undefined), + planned.event, + planned.microsteps, + planned.emittedEvents, + commands, + empty, + empty + ) + } const settle = (state: State, work: Work, exit: Exit.Exit, retain = true): Step => { const settled = current(state, work) @@ -1180,6 +1400,10 @@ const build = ( settle, element, report, + observesSnapshots, + settleEvent, + elementEvent, + snapshotEvent, stop, resume } @@ -1190,7 +1414,7 @@ const build = ( plan, start, fromSnapshot, - rest: (state) => state.handOverNeverReuse().resting(), + rest: (state) => state.restInPlace(), send: (state, event) => { const exit = send(state.handOverNeverReuse(), event) if (Exit.isFailure(exit) || exit.value.state === state) state.giveBackUnchanged() @@ -1198,17 +1422,23 @@ const build = ( }, sendDecoded: (state, event, retain) => givenBackIfUnchanged(state, sendDecoded(state.handOverNeverReuse(), event, retain)), - move: (state, event) => { - const moved = move(state.handOverNeverReuse(), event) - if (moved === state || (moved instanceof Step && moved.state === state)) state.giveBackUnchanged() - return moved - }, + move: invoking.size === 0 + ? moveChildlessOwned + : (state, event) => { + const moved = move(state.handOverNeverReuse(), event) + if (!(moved instanceof Step) || moved.state === state) state.giveBackUnchanged() + return moved + }, settle: (state, work, exit, retain) => givenBackIfUnchanged(state, settle(state.handOverNeverReuse(), work, exit, retain)), element: (state, work, value, retain) => givenBackIfUnchanged(state, element(state.handOverNeverReuse(), work, value, retain)), report: (state, work, snapshot, retain) => givenBackIfUnchanged(state, report(state.handOverNeverReuse(), work, snapshot, retain)), + observesSnapshots, + settleEvent, + elementEvent, + snapshotEvent, stop: (state) => givenBackIfUnchanged(state, stop(state.handOverNeverReuse())), resume } @@ -1222,32 +1452,28 @@ const givenBackIfUnchanged = (state: State, step: Step>>> +const kernels: Record>> = { + Persistent: new WeakMap(), + Owned: new WeakMap() +} /** * The step functions of `machine` that take states of `ownership` and plan - * with `planner`: the execution plan of the machine, which `compileExecutionPlan` - * selects, or always the reference planner. They are built once per machine. + * with `plan`. Cached per `(ownership, plan)`, since execution plans are + * cached per machine. * * @internal */ -export const kernel = (machine: Machine.Any, ownership: O, planner: PlannerKind): Kernel => { - const cache = kernels[ownership][planner] as WeakMap> - let built = cache.get(machine) +export const kernel = ( + machine: Machine.Any, + ownership: O, + plan: ExecutionPlan.CompiledExecutionPlan +): Kernel => { + const cache = kernels[ownership] as WeakMap> + let built = cache.get(plan) if (built === undefined) { - built = build( - machine, - ownership, - planner === "Compiled" - ? ExecutionPlan.compileExecutionPlan(machine) - : ExecutionPlan.selectExecutionPlanForTesting(machine, "generic").plan - ) - cache.set(machine, built) + built = build(machine, ownership, plan) + cache.set(plan, built) } return built } @@ -1279,7 +1505,7 @@ const bind = (machine: Machine.Any, kernel: Kernel, opti * @internal */ export const make = (machine: Machine.Any, options: Options): MachineStep<"Persistent"> => - bind(machine, kernel(machine, "Persistent", "Compiled"), options) + bind(machine, kernel(machine, "Persistent", ExecutionPlan.compileExecutionPlan(machine)), options) /** * Step functions that take each state over and may update it in place, for a @@ -1290,12 +1516,10 @@ export const make = (machine: Machine.Any, options: Options): MachineStep<"Persi * @internal */ export const makeOwned = (machine: Machine.Any, options: Options): OwnedMachineStep => - bind(machine, kernel(machine, "Owned", "Compiled"), options) + bind(machine, kernel(machine, "Owned", ExecutionPlan.compileExecutionPlan(machine)), options) /** - * Step functions of either ownership that plan with the planner of `planner`: - * the execution plan of the machine, as `make` and `makeOwned` use, or always - * the reference planner. + * Step functions of either ownership that plan with `plan`. * * @internal */ @@ -1303,5 +1527,5 @@ export const makeForTesting = ( machine: Machine.Any, options: Options, ownership: O, - planner: PlannerKind -): MachineStep => bind(machine, kernel(machine, ownership, planner), options) + plan: ExecutionPlan.CompiledExecutionPlan +): MachineStep => bind(machine, kernel(machine, ownership, plan), options) diff --git a/packages/effect-machine/src/internal/machine/stepHost.ts b/packages/effect-machine/src/internal/machine/stepHost.ts index 0e689952..d9eef206 100644 --- a/packages/effect-machine/src/internal/machine/stepHost.ts +++ b/packages/effect-machine/src/internal/machine/stepHost.ts @@ -2,12 +2,12 @@ * Runs a machine on its owned step, as a compiled process of the local runtime. * * The step decides everything a machine does: its next state, its commands and - * emissions, the work it starts and stops, and what the result of that work - * means. This module only carries a step out, in the order of the step: the - * commands, the work of exited states, the new state, the emitted events, then - * the work of entered states. Work runs as an owned process of the machine, so - * it starts in the turn of the event that entered its state, and its result - * reaches the step through the mailbox of the machine, in a later turn. + * emissions, the work it starts and stops (before and after commit), and what + * the result of that work means. This module only carries a step out, in the + * order of the step: `commands`, `stop`, the new state, `emitted`, then `start` + * and `stopAfter`. Work runs as an owned process of the machine, so it starts + * in the turn of the event that entered its state, and its result reaches the + * step through the mailbox of the machine, in a later turn. * * @since 0.48.0 */ @@ -21,9 +21,8 @@ import type { Inspection } from "../../LocalMachine.js" import type { ChildMachine, Machine } from "../../Machine.js" import * as ChildRegistry from "./childRegistry.js" import * as CommandRuntime from "./commandRuntime.js" -import { ChildAlreadyExistsError, failPlanning } from "./errors.js" -import type * as InvocationEvent from "./invocationEvent.js" -import * as InvocationOutcome from "./invocationOutcome.js" +import { ChildAlreadyExistsError, failPlanning, toStartupFailure } from "./errors.js" +import type * as ExecutionPlan from "./executionPlan.js" import type * as InvocationResolution from "./invocationResolution.js" import * as Runtime from "./runtimeProtocol.js" import * as Step from "./step.js" @@ -48,13 +47,28 @@ export type Entry = * of the runtime provides them. The children of the machine are the children * its process owns. */ -class Host extends Step.Planning implements Step.Children { +class Host extends Step.PlanningBase implements Step.Children { + readonly self: Scope["self"] state!: Step.State<"Owned"> - pending: OwnedStep | undefined - liveRuntime: CommandRuntime.LiveRuntime | undefined + pending: OwnedStep | undefined = undefined + liveRuntime: CommandRuntime.LiveRuntime | undefined = undefined constructor(machine: Machine.Any, kernel: Kernel, private readonly scope: Scope) { - super(machine, kernel.plan, scope.self, scope.parent, undefined, true) + super(machine, kernel.plan) + this.self = scope.self + } + + get parent() { + return this.scope.parent + } + get children(): Step.Children { + return this + } + get ambient(): boolean { + return true + } + get services(): never { + throw new Error("Local host runs work inside ambient machine services") } spawn(child: ChildMachine.Any, options: { readonly input: unknown } | undefined) { @@ -142,15 +156,10 @@ const valueOf = (exit: Exit.Exit): A => { throw Cause.squash(exit.cause) } -// The planner reads currency from a generation. The registry of the process -// decides currency for the work it hosts, so each decision gets a current one. -const current = (): InvocationEvent.Generation => ({ current: true }) - /** The exit of work as its step settles it. */ -const exitOf = (outcome: InvocationOutcome.Outcome): Exit.Exit => - outcome._tag === "Done" - ? Exit.succeed(outcome.output) - : Exit.failCause((outcome as { cause: Cause.Cause }).cause) +const exitOf = ( + outcome: Exclude, { readonly _tag: "Stopped" }> +): Exit.Exit => outcome._tag === "Done" ? Exit.succeed(outcome.output) : Exit.failCause(outcome.cause) const traced = (scope: Scope, invocation: ProgramInvocation, logic: AnyProcessLogic): AnyProcessLogic => ({ ...logic, @@ -174,7 +183,12 @@ const traced = (scope: Scope, invocation: ProgramInvocation, logic: AnyProcessLo }) /** The process that runs a program, built when its process starts. */ -const programLogic = (scope: Scope, work: Step.Work, invocation: ProgramInvocation): AnyProcessLogic => { +const programLogic = ( + scope: Scope, + kernel: Kernel, + work: Step.Work, + invocation: ProgramInvocation +): AnyProcessLogic => { switch (work._tag) { case "Effect": { const effect = valueOf(work.effect()) @@ -203,13 +217,7 @@ const programLogic = (scope: Scope, work: Step.Work, invocation: ProgramInvocati "Element", work, element, - inspected - ? (InvocationOutcome.decideElement( - invocation as InvocationResolution.StreamInvocation, - current(), - element - ) as InvocationOutcome.Deliver).event - : undefined + inspected ? kernel.elementEvent(work, element) : undefined ) ).pipe( Effect.asVoid, @@ -239,76 +247,85 @@ const report = ( )).pipe(Effect.catchTag("StoppedError", () => Effect.void)) /** Starts one piece of work that a step listed, as an owned process of the machine. */ -const startWork = (context: Context, work: Step.Work): Effect.Effect => { +const startWork = (context: Context, kernel: Kernel, work: Step.Work): Effect.Effect => { const scope = context.scope const invocation = work[Step.WorkTypeId] const program = isProgram(invocation) + const id = childId(invocation) // Keep caller-chosen ids out of the namespace reserved for runtime-owned // invocation ids; runtime-owned ids skip this check. - if (!program && ChildRegistry.isReservedChildId(childId(invocation))) { + if (!program && ChildRegistry.isReservedChildId(id)) { return Effect.fail(new ChildAlreadyExistsError({ id: invocation.id })) } - return Effect.suspend(() => - context.ownedChildren.spawn( - program - ? () => programLogic(scope, work, invocation) - : work._tag === "Logic" - ? () => valueOf(work.logic()) as AnyProcessLogic - // The runtime builds the child's logic from this description, so a - // running parent retains no closure for it. - : invocation as Extract, - { - key: makeKey(work.path, work.id), - path: work.path, - id: childId(invocation), - duplicateId: work.id, - ...(program ? { programKind: invocation._tag } : undefined), - sendParent: (isCurrent, event) => isCurrent() ? scope.self.send(event) : Effect.void, - // The work starts while the event that entered its state is processed, - // and its outcome is handled in a later turn, even when the work - // completes without suspending. The entered state is therefore always - // observed before the outcome leaves it, and the outcome of a state that - // was exited in between is discarded. - onOutcome: (isCurrent, outcome, invocationSessionId) => - Effect.andThen( - Effect.yieldNow, - Effect.suspend(() => { - if (!isCurrent()) return Effect.void - // The step decides what the outcome means. A failure fails the - // machine at once, as the step would when it settles the work. - const decision = InvocationOutcome.decide(invocation, current(), outcome) - switch (decision._tag) { - case "Deliver": - return report( - scope, - new Runtime.WorkMessage("Settle", work, exitOf(outcome), decision.event), - program ? invocationSessionId : undefined - ) - case "Fail": - return scope.failCause(decision.cause) - case "Ignore": - return Effect.void - } - }) - ), - ...(invocation.channels.snapshot - ? { - onSnapshot: (isCurrent: () => boolean, snapshot: { readonly state: unknown }) => { - if (!isCurrent()) return Effect.void - const decision = InvocationOutcome.decideSnapshot(invocation, current(), snapshot) - return decision._tag === "Ignore" - ? Effect.void - : report(scope, new Runtime.WorkMessage("Report", work, snapshot.state, decision.event), undefined) - } + return context.ownedChildren.spawn( + program + ? () => programLogic(scope, kernel, work, invocation) + : work._tag === "Logic" + ? () => valueOf(work.logic()) as AnyProcessLogic + // The runtime builds the child's logic from this description, so a + // running parent retains no closure for it. + : invocation as Extract, + { + key: makeKey(work.path, work.id), + path: work.path, + id, + duplicateId: work.id, + ...(program ? { programKind: invocation._tag } : undefined), + // The work starts while the event that entered its state is processed, + // and its outcome is handled in a later turn, even when the work + // completes without suspending. The entered state is therefore always + // observed before the outcome leaves it, and the outcome of a state that + // was exited in between is discarded. The step decides what the exit + // means when the mailbox delivers it. + onOutcome: (isCurrent, outcome, invocationSessionId) => + Effect.andThen( + Effect.yieldNow, + Effect.suspend(() => { + if (!isCurrent() || outcome._tag === "Stopped") return Effect.void + const exit = exitOf(outcome) + return report( + scope, + new Runtime.WorkMessage( + "Settle", + work, + exit, + isInspected(scope) ? kernel.settleEvent(work, exit) : undefined + ), + program ? invocationSessionId : undefined + ) + }) + ), + ...(kernel.observesSnapshots(work) + ? { + onSnapshot: (isCurrent: () => boolean, snapshot: { readonly state: unknown }) => { + if (!isCurrent()) return Effect.void + return report( + scope, + new Runtime.WorkMessage( + "Report", + work, + snapshot.state, + isInspected(scope) ? kernel.snapshotEvent(work, snapshot.state) : undefined + ), + undefined + ) } - : undefined) - } - ) + } + : undefined) + } ) } -const startAll = (context: Context, work: ReadonlyArray): Effect.Effect | undefined => - work.length === 0 ? undefined : runSequentialDiscard(work.map((one) => startWork(context, one))) +const startAll = ( + context: Context, + kernel: Kernel, + work: ReadonlyArray +): Effect.Effect | undefined => + work.length === 0 + ? undefined + : work.length === 1 + ? startWork(context, kernel, work[0]!) + : Effect.all(work.map((one) => startWork(context, kernel, one)), { discard: true }) /** The plan of a step, as an acknowledged delivery reports it. */ const planOf = (step: OwnedStep): unknown => { @@ -362,7 +379,7 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => /** Starts the work of the first step of the process, then drains. */ const startPending = (context: Context, host: Host, step: OwnedStep): Drain => { host.pending = undefined - const starting = startAll(context, step.start) + const starting = startAll(context, kernel, step.start) return starting === undefined ? loop(context) : starting.pipe(Effect.andThen(loop(context))) } @@ -378,17 +395,10 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => const scope = context.scope const exit = step.exit const done = exit !== undefined - // A machine that ends stops the work of the states it exited before its - // new state, and then the rest of its work, after its emitted events. - // Work that ended in a state the step exits is awaited with the rest, so - // its process has stopped before the state is entered again. - let stopBefore: ReadonlyArray = settled === undefined ? step.stop : [settled, ...step.stop] - let stopAfter: ReadonlyArray = [] - if (done && step.stop.length > 0) { - const exited = new Set(step.exited) - stopBefore = stopBefore.filter((work) => exited.has(work.path)) - stopAfter = step.stop.filter((work) => !exited.has(work.path)) - } + // Work that ended in a state the step exits is awaited with `step.stop`, so + // its process has stopped before the state is entered again. Remaining work + // of non-exited states on a final step is in `step.stopAfter`. + const stopBefore: ReadonlyArray = settled === undefined ? step.stop : [settled, ...step.stop] const beforeCommit: Array> = [] if (step.commands.length > 0) beforeCommit.push(runCommands(step.commands, scope)) const stopping = stopWork(context, stopBefore) @@ -402,13 +412,14 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => ) ) } - if (done) { - const stopped = stopWork(context, stopAfter) - if (stopped !== undefined) afterCommit.push(stopped) - } else { - const starting = startAll(context, step.start) + if (step.start.length > 0) { + const starting = startAll(context, kernel, step.start) if (starting !== undefined) afterCommit.push(starting) } + if (step.stopAfter.length > 0) { + const stopped = stopWork(context, step.stopAfter) + if (stopped !== undefined) afterCommit.push(stopped) + } const planned = step.planned const after = planned ? step.snapshot : before const continueAfterCommit = (): Drain => { @@ -436,17 +447,18 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => // mailbox is empty. const drainSync = (context: Context, first?: Runtime.ProcessMessage): Drain | undefined => { const host = hostOf(context) - if (host.pending !== undefined) { + if (!childless && host.pending !== undefined) { if (first !== undefined) context.beginMessage(first) return startPending(context, host, host.pending) } let delivered = first while (true) { let message: Runtime.ProcessMessage + let acknowledged: boolean if (delivered !== undefined) { message = delivered delivered = undefined - context.beginMessage(message) + acknowledged = context.beginMessage(message) } else { const pending = context.pollMessage() if (Option.isNone(pending)) { @@ -456,12 +468,11 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => return undefined } message = pending.value + acknowledged = Runtime.isAcknowledgedMessage(message) } - const acknowledged = Runtime.isAcknowledgedMessage(message) const event: unknown = acknowledged ? (message as Runtime.AcknowledgedMessage).event : message if (event instanceof Runtime.RefusedEvent) return failPlanning(event.error) - const before = context.state() - const work = event instanceof Runtime.WorkMessage ? event : undefined + const work = !childless && event instanceof Runtime.WorkMessage ? event : undefined let step: OwnedStep if (work !== undefined) { step = takeWork(host.state, work, acknowledged) @@ -469,27 +480,27 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => // Only an acknowledged delivery reads the microsteps of its step. step = kernel.sendDecoded(host.state, event as Machine.EventOf, true) } else { - // An event that only moves the machine is committed without a step. + // An event that only moves the machine is committed without a step or new state wrapper. const moved = kernel.move(host.state, event as Machine.EventOf) + if (moved === undefined) continue if (moved instanceof Step.Step) { step = moved } else { - if (moved === host.state) continue - host.state = moved - const notification = context.commit(moved.snapshot) + const notification = context.commit(moved) if (notification !== undefined) { return context.runAfterChanges(notification.pipe(Effect.andThen(loop(context)))) } continue } } + const before = acknowledged || !step.planned ? context.state() : undefined const state = step.state host.state = state const exit = state.exit if (exit === undefined && step.commands.length === 0 && step.emitted.length === 0) { if (!step.planned) { if (step.stop.length === 0 && step.start.length === 0) { - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: before }) + if (acknowledged) context.completeMessage({ before: before!, plan: planOf(step), after: before! }) continue } } else if (step.stop.length === 0 && step.start.length === 0 && !exitsWork(step, work)) { @@ -497,17 +508,17 @@ const makeDrain = (machine: Machine.Any, kernel: Kernel, childless: boolean) => const notification = context.commit(next) if (notification !== undefined) { return context.runAfterChanges(notification.pipe(Effect.andThen(Effect.suspend(() => { - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) + if (acknowledged) context.completeMessage({ before: before!, plan: planOf(step), after: next }) return loop(context) })))) } - if (acknowledged) context.completeMessage({ before, plan: planOf(step), after: next }) + if (acknowledged) context.completeMessage({ before: before!, plan: planOf(step), after: next }) continue } } if (exit !== undefined && Exit.isFailure(exit)) return Effect.failCause(exit.cause) const settled = exitsWork(step, work) ? work!.work as Step.Work : undefined - return continueEffectful(context, host, step, acknowledged, before, settled) + return continueEffectful(context, host, step, acknowledged, before ?? context.state(), settled) } } @@ -544,18 +555,18 @@ const initialOf = ( } /** - * The execution of a machine on its owned step, which plans with `planner`. + * The execution of a machine on its owned step, which plans with `plan`. * * @internal */ export const makeExecution = ( machine: Machine.Any, entry: Entry, - planner: "Compiled" | "Reference", + plan: ExecutionPlan.CompiledExecutionPlan, childless: boolean, decodeEvent: Runtime.EventDecoder ): Runtime.CompiledProcessExecution, unknown, any, any, any, any> => { - const kernel = Step.kernel(machine, "Owned", planner) + const kernel = Step.kernel(machine, "Owned", plan) const drain = makeDrain(machine, kernel, childless) const first = (scope: Scope): Exit.Exit => @@ -576,6 +587,17 @@ export const makeExecution = ( // when it starts, so it starts without an Effect. const initialSync = entry._tag === "Initial" && kernel.plan.initial !== undefined ? (scope: Scope): Runtime.CompiledProcessInitial, unknown> => { + if (childless && !isInspected(scope)) { + let planned: ReturnType> + try { + planned = kernel.plan.initial!(entry.args, scope) + } catch (error) { + throw toStartupFailure(error) + } + return planned.done + ? { state: planned.state, done: true, output: planned.output } + : { state: planned.state, done: false, output: undefined } + } const started = first(scope) if (Exit.isFailure(started)) throw Cause.squash(started.cause) const step = started.value diff --git a/packages/effect-machine/test/conformance/matrix.txt b/packages/effect-machine/test/conformance/matrix.txt index a7818a90..396ac17a 100644 --- a/packages/effect-machine/test/conformance/matrix.txt +++ b/packages/effect-machine/test/conformance/matrix.txt @@ -46,6 +46,7 @@ starts no work for a state it only passes through maps the input of work from the state and the event that entered it | runs | runs | runs | runs | runs stops and starts the work of every level that a step exits and enters | runs | runs | runs | runs | runs stops all work when it ends, also that of states that stay active | runs | runs | runs | differs | runs +stops work of states that stay active after publishing the final state and emissions | runs | runs | runs | runs | runs retries work through a choice, and finishes with its output | runs | runs | runs | runs | runs emits and raises events from the outcome of work | runs | runs | runs | runs | runs starts the work of its initial state before any event | runs | runs | runs | differs | runs diff --git a/packages/effect-machine/test/conformance/scenarios/invocations.ts b/packages/effect-machine/test/conformance/scenarios/invocations.ts index 87432d96..696db0e6 100644 --- a/packages/effect-machine/test/conformance/scenarios/invocations.ts +++ b/packages/effect-machine/test/conformance/scenarios/invocations.ts @@ -616,6 +616,64 @@ const finish: Scenario = { ] } +const finishStopOrder: Scenario = { + name: "stops work of states that stay active after publishing the final state and emissions", + machine: (fixture) => { + const observed = (name: string) => + Effect.onInterrupt( + Effect.orDie(fixture.work(name)), + () => + Effect.sync(() => { + const { emitted, state } = fixture.hostState() + fixture.note(`${name} at ${state ?? "none"} emitted=${emitted}`) + }) + ) + return Machine.make({ + root: Machine.state({ + states: { + Idle: {}, + Active: { states: { Open: {}, Closed: { type: "final" } } } + } + }), + events: Machine.events({ Go: {}, Finish: {} }), + emittedEvents: Machine.emittedEvents({ Finished: {} }), + effects: { outer: observed("outer"), inner: Effect.orDie(fixture.work("inner")) } + }).handle({ + initial: { target: "Idle" }, + states: { + Idle: { on: { Go: { target: "Active" } } }, + Active: { + invoke: { src: "outer", onDone: { stay: true } }, + initial: { target: "Active.Open" }, + states: { + Open: { + invoke: { src: "inner", onDone: { stay: true } }, + on: { + Finish: { + target: "Active.Closed", + commands: (_, enqueue) => enqueue.emit({ _tag: "Finished" }) + } + } + }, + Closed: {} + } + } + } + }) + }, + start, + steps: [ + send({ _tag: "Go" }, { happens: [{ "Active.Open": {} }, started("outer"), started("inner")] }), + send({ _tag: "Finish" }, { + happens: [{ "Active.Closed": {} }], + stopped: ["inner", "outer"], + emits: [{ _tag: "Finished" }], + log: ["outer at Active.Closed emitted=1"], + outcome: final() + }) + ] +} + const retries: Scenario = { name: "retries work through a choice, and finishes with its output", machine: (fixture) => @@ -1079,6 +1137,7 @@ export const invocations: ReadonlyArray = [ inputs, nested, finish, + finishStopOrder, retries, effects, initialWork, diff --git a/packages/effect-machine/test/conformance/support/fixture.ts b/packages/effect-machine/test/conformance/support/fixture.ts index 01474f8c..55fcc006 100644 --- a/packages/effect-machine/test/conformance/support/fixture.ts +++ b/packages/effect-machine/test/conformance/support/fixture.ts @@ -46,6 +46,12 @@ export class Fixture { /** Called synchronously when a run starts. */ onStart: (run: Run) => void = () => {} + /** Reads the host's currently published state and emitted count, when supported by the suite runner. */ + hostState: () => { readonly state: string | undefined; readonly emitted: number } = () => ({ + state: undefined, + emitted: 0 + }) + /** Records that model code ran. */ readonly note = (text: string): undefined => { this.log.push(text) diff --git a/packages/effect-machine/test/conformance/support/hosts/step.ts b/packages/effect-machine/test/conformance/support/hosts/step.ts index ba05eac7..37622544 100644 --- a/packages/effect-machine/test/conformance/support/hosts/step.ts +++ b/packages/effect-machine/test/conformance/support/hosts/step.ts @@ -437,6 +437,12 @@ export const stepHost: Host = { if (runner.state !== done.state) break yield* startWork(runner, work) } + if (done.stopAfter.length > 0) { + yield* Effect.all(done.stopAfter.map((work) => stopWork(runner, work)), { + concurrency: "unbounded", + discard: true + }) + } if (done.exit !== undefined) { const spawned = Array.from(runner.spawned.values()) runner.spawned.clear() diff --git a/packages/effect-machine/test/conformance/support/suite.ts b/packages/effect-machine/test/conformance/support/suite.ts index e9b04e68..ddb00662 100644 --- a/packages/effect-machine/test/conformance/support/suite.ts +++ b/packages/effect-machine/test/conformance/support/suite.ts @@ -171,6 +171,13 @@ const runScenario = Effect.fnUntraced(function*( const held = instance === undefined ? "Unknown" : current === undefined ? "None" : normalize(current) starts.push({ label: `start ${label}`, held }) } + fixture.hostState = () => { + const current = instance?.current() + return { + state: current === undefined ? undefined : Object.keys(normalize(current)).join(","), + emitted: instance?.emitted.length ?? 0 + } + } const sent: Array> = [] const pending = () => sent.some((fiber) => fiber.pollUnsafe() === undefined) diff --git a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts index 64ba021b..526fa137 100644 --- a/packages/effect-machine/test/internal/machine/stepDifferential.test.ts +++ b/packages/effect-machine/test/internal/machine/stepDifferential.test.ts @@ -322,41 +322,194 @@ describe("Machine.toStep planner and ownership", () => { assert.strictEqual(step.stop(stopped.state).state, done.state) }) - it("moves a state as its step would, and lists a step only for what a host must apply", () => { - const decoded = (event: unknown) => Protocol.decodeEventSync(Counter, event) - for (const planner of ["Compiled", "Reference"] as const) { - const kernel = Step.kernel(Counter, "Owned", planner) - const planning = () => new Step.Planning(Counter, kernel.plan, self, undefined, undefined) - let moved = success(kernel.start(planning(), [], false)).state - let stepped = success(kernel.start(planning(), [], false)).state - for (const event of [{ _tag: "Increment" }, { _tag: "Twice" }, { _tag: "Same" }, { _tag: "Again" }]) { - const result = kernel.move(moved, decoded(event)) - const step = kernel.sendDecoded(stepped, decoded(event), false) - assert.notInstanceOf(result, Step.Step) - const state = result as Step.State<"Owned"> - // An event that changes nothing returns the state passed in. - assert.strictEqual(state === moved, !step.planned) - assert.deepStrictEqual(state.snapshot, step.snapshot) - moved = state - stepped = step.state + it("moves a state as its step would across every planner and ownership", () => { + const plansOf = (machine: Machine.Machine.Any) => [ + ExecutionPlan.compileExecutionPlan(machine), + ExecutionPlan.referenceExecutionPlan(machine) + ] + const compareMove = ( + machine: Machine.Machine.Any, + events: ReadonlyArray, + childless: boolean + ) => { + const decoded = (event: unknown) => Protocol.decodeEventSync(machine, event) + for (const plan of plansOf(machine)) { + for (const ownership of ["Owned", "Persistent"] as const) { + const kernel = Step.kernel(machine, ownership, plan) + const planning = () => new Step.Planning(machine, kernel.plan, self, undefined, undefined) + let state = success(kernel.start(planning(), [], false)).state + let stepped = success(kernel.start(planning(), [], false)).state + for (const event of events) { + const previousSnapshot = ownership === "Persistent" ? structuredClone(state.snapshot) : undefined + const result = kernel.move(state, decoded(event)) + const step = kernel.sendDecoded(stepped, decoded(event), false) + if (!step.planned) { + assert.strictEqual(result, undefined) + } else if (result instanceof Step.Step) { + assert.deepStrictEqual(result.snapshot, step.snapshot) + assert.deepStrictEqual(result.commands, step.commands) + assert.deepStrictEqual(result.emitted, step.emitted) + assert.strictEqual(result.stop.length, step.stop.length) + assert.strictEqual(result.start.length, step.start.length) + assert.strictEqual(result.running.length, step.running.length) + assert.strictEqual(result.exit === undefined, step.exit === undefined) + if (result.exit !== undefined && step.exit !== undefined) { + assert.strictEqual(Exit.isSuccess(result.exit), Exit.isSuccess(step.exit)) + if (Exit.isSuccess(result.exit) && Exit.isSuccess(step.exit)) { + assert.deepStrictEqual(result.exit.value, step.exit.value) + } + } + if (ownership === "Persistent") { + assert.deepStrictEqual(state.snapshot, previousSnapshot) + } + state = result.state + } else { + // Only childless owned steps return a snapshot directly without allocating a Step. + assert.strictEqual(ownership, "Owned") + assert.strictEqual(childless, true) + assert.strictEqual(step.commands.length, 0) + assert.strictEqual(step.emitted.length, 0) + assert.strictEqual(step.exit, undefined) + assert.deepStrictEqual(result, step.snapshot) + assert.deepStrictEqual(state.snapshot, step.snapshot) + } + stepped = step.state + } + } } - // A state that a move replaced is not reused. - const before = moved - moved = kernel.move(moved, decoded({ _tag: "Increment" })) as Step.State<"Owned"> - assert.throws(() => kernel.move(before, decoded({ _tag: "Increment" })), /never reuse an owned state/) - // A step that ends the machine or fails is listed as a step. - const finished = kernel.move(moved, decoded({ _tag: "Finish" })) + } + + // Flat indexed + reference, Owned + Persistent: in-place updates, raised events, no-op, reentry, completion. + compareMove( + Counter, + [{ _tag: "Increment" }, { _tag: "Twice" }, { _tag: "Same" }, { _tag: "Again" }, { _tag: "Finish" }, { + _tag: "Increment" + }], + true + ) + // Hierarchical parallel + reference, Owned + Persistent: simultaneous transitions, raised events, completion. + compareMove(Regions, [{ _tag: "Tick" }, { _tag: "Both" }, { _tag: "Tick" }, { _tag: "Finish" }], true) + // Invoking machine + reference, Owned + Persistent: entering/exiting/reentering invoking states. + compareMove(Worker, [{ _tag: "Start" }, { _tag: "Bump" }, { _tag: "Cancel" }], false) + + // Handover and throw-rollback invariants on Owned move for both planners. + const decodedCounter = (event: unknown) => Protocol.decodeEventSync(Counter, event) + for (const plan of plansOf(Counter)) { + const kernel = Step.kernel(Counter, "Owned", plan) + const planning = () => new Step.Planning(Counter, kernel.plan, self, undefined, undefined) + const state = success(kernel.start(planning(), [], false)).state + assert.notInstanceOf(kernel.move(state, decodedCounter({ _tag: "Increment" })), Step.Step) + const finished = kernel.move(state, decodedCounter({ _tag: "Finish" })) assert.instanceOf(finished, Step.Step) - const exit = (finished as Step.Step<"Owned">).exit! - assert.ok(Exit.isSuccess(exit)) - // Increment, Twice, Again and the last Increment: (1 + 2) * 2 + 1. - assert.strictEqual(exit.value, 7) - const failed = kernel.move(success(kernel.start(planning(), [], false)).state, decoded({ _tag: "Overflow" })) + assert.throws(() => kernel.move(state, decodedCounter({ _tag: "Increment" })), /never reuse an owned state/) + const failing = success(kernel.start(planning(), [], false)).state + kernel.move(failing, decodedCounter({ _tag: "Increment" })) + const failed = kernel.move(failing, decodedCounter({ _tag: "Overflow" })) assert.instanceOf(failed, Step.Step) assert.ok(Exit.isFailure((failed as Step.Step<"Owned">).exit!)) + assert.strictEqual(((failed as Step.Step<"Owned">).snapshot as any).state.value.value, 1) } }) + it("matches retain: false and rest/fromSnapshot across every planner and ownership", () => { + for (const machine of [Counter, Regions, Worker]) { + const plans = [ExecutionPlan.compileExecutionPlan(machine), ExecutionPlan.referenceExecutionPlan(machine)] + const events = machine === Counter + ? [{ _tag: "Increment" }, { _tag: "Twice" }, { _tag: "Same" }, { _tag: "Again" }, { _tag: "Finish" }] + : machine === Regions + ? [{ _tag: "Tick" }, { _tag: "Both" }, { _tag: "Finish" }] + : [{ _tag: "Start" }, { _tag: "Bump" }, { _tag: "Cancel" }] + const decoded = (event: unknown) => Protocol.decodeEventSync(machine, event) + for (const plan of plans) { + for (const ownership of ["Owned", "Persistent"] as const) { + const kernel = Step.kernel(machine, ownership, plan) + const planning = () => new Step.Planning(machine, kernel.plan, self, undefined, undefined) + const retainedStart = success(kernel.start(planning(), [], true)) + const unretainedStart = success(kernel.start(planning(), [], false)) + assert.deepStrictEqual(unretainedStart.snapshot, retainedStart.snapshot) + assert.deepStrictEqual(unretainedStart.entered, retainedStart.entered) + assert.deepStrictEqual(unretainedStart.exited, retainedStart.exited) + assert.strictEqual(unretainedStart.start.length, retainedStart.start.length) + let retainedState = retainedStart.state + let unretainedState = kernel.rest(unretainedStart.state) + if (machine !== Worker) { + unretainedState = kernel.fromSnapshot(planning(), unretainedState.snapshot) + } + for (const event of events) { + const retainedStep = kernel.sendDecoded(retainedState, decoded(event), true) + const unretainedStep = kernel.sendDecoded(unretainedState, decoded(event), false) + assert.deepStrictEqual(unretainedStep.snapshot, retainedStep.snapshot) + assert.deepStrictEqual(unretainedStep.exited, retainedStep.exited) + assert.deepStrictEqual(unretainedStep.entered, retainedStep.entered) + assert.deepStrictEqual(unretainedStep.commands, retainedStep.commands) + assert.deepStrictEqual(unretainedStep.emitted, retainedStep.emitted) + assert.strictEqual(unretainedStep.planned, retainedStep.planned) + assert.strictEqual(unretainedStep.stop.length, retainedStep.stop.length) + assert.strictEqual(unretainedStep.start.length, retainedStep.start.length) + assert.strictEqual(unretainedStep.exit === undefined, retainedStep.exit === undefined) + retainedState = retainedStep.state + unretainedState = kernel.rest(unretainedStep.state) + } + } + } + } + }) + + it.effect("matches ambient: true and ambient: false across every planner and ownership", () => + Effect.gen(function*() { + const calls: Array = [] + const children: Step.Children = { + spawn: () => Effect.die("unused"), + spawnLogic: () => Effect.die("unused"), + sendTo: (child, event) => + Effect.sync(() => { + calls.push(`sendTo:${typeof child === "string" ? child : child.id}:${JSON.stringify(event)}`) + }), + stop: (child) => + Effect.sync(() => { + calls.push(`stop:${typeof child === "string" ? child : child.id}`) + }) + } + const WorkerAddr = Machine.childAddress("worker") + const hostMachine = Machine.make({ + root: Machine.state({ states: { Active: {} } }), + events: Machine.events({}), + effects: { + act: Effect.andThen(Machine.stopChild(WorkerAddr), Effect.succeed("ok")) + } + }).handle({ + initial: { target: "Active" }, + states: { Active: { invoke: { src: "act", onDone: { stay: true } } } } + }) + for ( + const plan of [ + ExecutionPlan.compileExecutionPlan(hostMachine), + ExecutionPlan.referenceExecutionPlan(hostMachine) + ] + ) { + for (const ownership of ["Owned", "Persistent"] as const) { + const kernel = Step.kernel(hostMachine, ownership, plan) + const provided = new Step.Planning(hostMachine, kernel.plan, self, undefined, children, false) + const ambient = new Step.Planning(hostMachine, kernel.plan, self, undefined, children, true) + const providedWork = success(kernel.start(provided, [], false)).start[0]! + const ambientWork = success(kernel.start(ambient, [], false)).start[0]! + assert.strictEqual(providedWork._tag, "Effect") + assert.strictEqual(ambientWork._tag, "Effect") + if (providedWork._tag !== "Effect" || ambientWork._tag !== "Effect") continue + calls.length = 0 + const providedResult = yield* success(providedWork.effect()) as Effect.Effect + const providedCalls = calls.slice() + calls.length = 0 + const ambientResult = yield* Effect.provide( + success(ambientWork.effect()) as Effect.Effect, + provided.services + ) + assert.strictEqual(ambientResult, providedResult) + assert.deepStrictEqual(calls, providedCalls) + } + } + })) + it("are not the states of the persistent step functions", () => { const owned: Step.OwnedMachineStep = counter() const persistent: Step.MachineStep = Step.make(Counter, { self }) diff --git a/packages/effect-machine/test/internal/machine/support/stepDifferential.ts b/packages/effect-machine/test/internal/machine/support/stepDifferential.ts index 6a2d521b..6411330b 100644 --- a/packages/effect-machine/test/internal/machine/support/stepDifferential.ts +++ b/packages/effect-machine/test/internal/machine/support/stepDifferential.ts @@ -17,6 +17,7 @@ import { assert } from "@effect/vitest" import { Cause, Duration, Effect, Exit } from "effect" import { Machine } from "../../../../src/index.js" +import * as ExecutionPlan from "../../../../src/internal/machine/executionPlan.js" import * as Step from "../../../../src/internal/machine/step.js" /** Selects one running piece of work, by the same rule in every variant. */ @@ -107,6 +108,7 @@ const stepData = (step: Step.Step): unknown => ({ ), stop: step.stop.map(workKey), start: step.start.map(workKey), + stopAfter: step.stopAfter.map(workKey), running: step.running.map(workKey), exit: step.exit === undefined ? undefined : renderExit(step.exit) }) @@ -133,14 +135,14 @@ const makeVariant = ( options: Options, name: string, ownership: Step.Ownership, - planner: "Compiled" | "Reference", + selectPlan: (machine: Machine.Machine.Any) => ExecutionPlan.CompiledExecutionPlan, replays: boolean ): Variant => { const subject = options.make() return { name, subject, - step: Step.makeForTesting(subject.machine, { self }, ownership, planner), + step: Step.makeForTesting(subject.machine, { self }, ownership, selectPlan(subject.machine)), replays, latest: undefined, pending: undefined, @@ -254,12 +256,12 @@ const flush = (variants: ReadonlyArray): void => { */ export const verifyStepStrategies = (options: Options): number => { const variants = [ - makeVariant(options, "compiled persistent", "Persistent", "Compiled", false), - makeVariant(options, "reference persistent", "Persistent", "Reference", false), - makeVariant(options, "compiled owned", "Owned", "Compiled", false), - makeVariant(options, "reference owned", "Owned", "Reference", false), - makeVariant(options, "compiled persistent, kept", "Persistent", "Compiled", true), - makeVariant(options, "reference persistent, kept", "Persistent", "Reference", true) + makeVariant(options, "compiled persistent", "Persistent", ExecutionPlan.compileExecutionPlan, false), + makeVariant(options, "reference persistent", "Persistent", ExecutionPlan.referenceExecutionPlan, false), + makeVariant(options, "compiled owned", "Owned", ExecutionPlan.compileExecutionPlan, false), + makeVariant(options, "reference owned", "Owned", ExecutionPlan.referenceExecutionPlan, false), + makeVariant(options, "compiled persistent, kept", "Persistent", ExecutionPlan.compileExecutionPlan, true), + makeVariant(options, "reference persistent, kept", "Persistent", ExecutionPlan.referenceExecutionPlan, true) ] let now = 0 let taken = 0 diff --git a/packages/effect-machine/test/machine/MachineStep.test.ts b/packages/effect-machine/test/machine/MachineStep.test.ts index d7a34b6a..f406319a 100644 --- a/packages/effect-machine/test/machine/MachineStep.test.ts +++ b/packages/effect-machine/test/machine/MachineStep.test.ts @@ -9,6 +9,7 @@ const dataOf = (step: Machine.MachineStep.Step) => ({ commands: step.commands, stop: step.stop.map(keyOf), start: step.start.map(keyOf), + stopAfter: step.stopAfter.map(keyOf), exit: step.exit }) @@ -163,7 +164,8 @@ describe("Machine.toStep", () => { emitted: [], commands: [], stop: [], - start: [] + start: [], + stopAfter: [] }) }) }) @@ -351,10 +353,43 @@ describe("Machine.toStep", () => { const loading = success(step.send(success(step.start()).state, Events.Load({ id: "a" }))) const stopped = step.stop(loading.state) assert.deepStrictEqual(stopped.stop.map(keyOf), loading.start.map(keyOf)) + assert.deepStrictEqual(stopped.stopAfter, []) assert.deepStrictEqual(stopped.exit, Exit.fail(new Machine.StoppedError())) assert.strictEqual(step.stop(stopped.state).state, stopped.state) }) + it("splits exited and remaining work into stop and stopAfter when reaching a final state", () => { + const ending = Machine.make({ + root: Machine.state({ + states: { + Open: {}, + Closed: { type: "final", output: Schema.String } + } + }), + events: Machine.events({ Finish: {} }), + effects: { first: Effect.void, second: Effect.void, open: Effect.void } + }).handle({ + invoke: [ + { src: "first", onDone: { stay: true } }, + { src: "second", onDone: { stay: true } } + ], + initial: { target: "Open" }, + on: { Finish: { target: "Closed" } }, + states: { + Open: { invoke: { src: "open", onDone: { stay: true } } }, + Closed: { output: () => "closed" } + } + }) + const steps = Machine.toStep(ending, { self }) + const started = success(steps.start()) + assert.deepStrictEqual(started.start.map(({ id }) => id), ["first", "second", "open"]) + const finished = success(steps.send(started.state, { _tag: "Finish" })) + assert.deepStrictEqual(finished.stop.map(({ id }) => id), ["open"]) + assert.deepStrictEqual(finished.stopAfter.map(({ id }) => id), ["second", "first"]) + assert.deepStrictEqual(finished.running, []) + assert.deepStrictEqual(finished.exit, Exit.succeed("closed")) + }) + describe("streams", () => { const counter = Machine.make({ root: Machine.state({ states: { Idle: {}, Counting: { fields: { total: Schema.Number } }, Done: {} } }), diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs index ada65e8a..a0126373 100644 --- a/scripts/check-architecture.mjs +++ b/scripts/check-architecture.mjs @@ -15,7 +15,8 @@ const ruleDescriptions = { ARCH011: "Internal directories may not use barrel modules", ARCH012: "Internal filenames must describe their responsibility without a machine prefix", ARCH013: "Public implementation bindings must declare their API signature", - ARCH014: "The model and the Cluster host may not depend on the local runtime, directly or transitively" + ARCH014: "The model and the Cluster host may not depend on the local runtime, directly or transitively", + ARCH015: "Hosts may not decide invocation outcomes directly; only the step may" } const normalizePath = (path) => path.split(sep).join("/") @@ -261,6 +262,15 @@ export const checkArchitecture = ({ "src/internal/machine/stepHost.ts", "src/internal/machine/process.ts" ]) + // Hosts carry steps out and must never decide invocation outcomes directly. + const hostModules = new Set([ + "src/internal/machine/stepHost.ts", + "src/internal/machine/process.ts", + "src/internal/machine/atom.ts", + "src/internal/machine/cluster.ts", + "src/internal/machine/clusterInstance.ts", + "src/internal/machine/clusterWork.ts" + ]) // Hosts a local machine, so it depends on the local runtime by design. const atomHostModules = new Set(["src/internal/machine/atom.ts"]) // Every other machine internal is independent of the local runtime, so a new @@ -477,6 +487,18 @@ export const checkArchitecture = ({ `Runtime depends on higher-level module ${edge.target}` )) } + if ( + hostModules.has(edge.source) && + edge.target === "src/internal/machine/invocationOutcome.ts" + ) { + diagnostics.push(diagnostic( + "ARCH015", + edge.sourceFile, + edge.node, + edge.source, + `Host module depends on invocation outcome decisions in ${edge.target}` + )) + } if ( edge.source.startsWith("src/") && !edge.source.startsWith("src/testing/") && diff --git a/scripts/check-architecture.test.mjs b/scripts/check-architecture.test.mjs index 3b80356d..a9cb8db7 100644 --- a/scripts/check-architecture.test.mjs +++ b/scripts/check-architecture.test.mjs @@ -272,6 +272,15 @@ test("keeps invocation semantics outside the planner and the runtime", () => { assert.deepEqual(rules(root), ["ARCH005", "ARCH006"]) }) +test("keeps invocation outcome decisions out of host modules", () => { + const root = makeProject({ + "src/internal/machine/stepHost.ts": 'import type { Outcome } from "./invocationOutcome.js"\nexport type HostOutcome = Outcome', + "src/internal/machine/clusterInstance.ts": 'import { decide } from "./invocationOutcome.js"\nexport const cluster = decide', + "src/internal/machine/invocationOutcome.ts": "export type Outcome = 1\nexport const decide = () => 1" + }) + assert.deepEqual(rules(root), ["ARCH015", "ARCH015"]) +}) + test("detects runtime cycles while permitting type-only cycles", () => { const cyclic = makeProject({ "src/a.ts": 'import { b } from "./b.js"\nexport const a = b',