From f24a768baaef458f28498fa8ef47f03fc5fcb1d4 Mon Sep 17 00:00:00 2001 From: Cristian Date: Mon, 9 Nov 2026 00:35:38 +0000 Subject: [PATCH] fix(runtime): drop task and timeout events of an ended state entry A task result or a fired .timeout entered the mailbox as a plain send. When it was queued behind an event that left the state, a later entry of the same state (reenter, or A -> B -> A) processed it. The task wrapper now sends through an internal owned send tagged with its state scope, and the loop drops an owned event whose scope is no longer the current state scope, before any hook and before postpone. --- .changeset/stale-task-signals.md | 5 + AGENTS.md | 1 + docs/async-work.md | 2 + src/internal/runtime.ts | 45 ++++- src/machine.ts | 21 ++- test/stale-signal.property.test.ts | 212 ++++++++++++++++++++++++ test/stale-signal.test.ts | 258 +++++++++++++++++++++++++++++ 7 files changed, 540 insertions(+), 4 deletions(-) create mode 100644 .changeset/stale-task-signals.md create mode 100644 test/stale-signal.property.test.ts create mode 100644 test/stale-signal.test.ts diff --git a/.changeset/stale-task-signals.md b/.changeset/stale-task-signals.md new file mode 100644 index 0000000..e7c8f4d --- /dev/null +++ b/.changeset/stale-task-signals.md @@ -0,0 +1,5 @@ +--- +"effect-machine": patch +--- + +A task's success or failure event and a `.timeout` event now belong to the state entry that started them. The actor drops such an event when that entry has ended before the event leaves the mailbox. Before this change, a task that completed (or a timer that fired) while another event left the state queued its event behind that event, and a later entry of the same state processed it: after `.reenter`, or after a round trip such as `A -> B -> A`. Handlers had to compare a lease or an entry id in the event with the state to ignore it. An entry ends on a change of state tag or on `.reenter`. A same-tag `.on` transition keeps the entry, so its task and timer events still arrive. A stale event is dropped before any hook sees it, and it is never postponed. Events that a `.spawn` handler sends with `self.send` are not owned and are delivered as before. diff --git a/AGENTS.md b/AGENTS.md index 0f59890..bf5c3f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -321,6 +321,7 @@ const count = yield* actor.ask(Event.GetCount); // number - Publish Active only while the same generation is still Starting. A terminal lifecycle must never return to Active. - `actor.start` shares one startup result across concurrent and repeated calls, including failure or interruption. Stop the actor and spawn a new actor to retry initialization. It cannot restart a terminal actor. - ActorScope cleanup must match the registered actor identity before removing an ID. A later actor can reuse that ID. +- Task and timeout events are owned by their state entry. The task wrapper in `src/machine.ts` reads its state scope with `Effect.scope` before `run` and sends through the `@internal` `MachineRef._sendOwned`, which tags the queued `send` with that scope. The loop in `src/internal/runtime.ts` drops an owned event whose scope is no longer `stateScopeRef.current`, before any hook and before postpone. The state scope is the entry identity: keep one new scope per lifecycle run. `test/stale-signal.test.ts` and `test/stale-signal.property.test.ts` guard this. - `Machine.spawn` returns an **unstarted** actor — must call `yield* actor.start`. `system.spawn` auto-starts. - Never `throw` in Effect.gen — use `yield* Effect.fail()` - `yield* Effect.yieldNow` after `send()` to let effects run diff --git a/docs/async-work.md b/docs/async-work.md index b422e3b..9308095 100644 --- a/docs/async-work.md +++ b/docs/async-work.md @@ -23,6 +23,8 @@ machine.task(State.Loading, ({ state }) => load(state.id), { A task sends `onFailure` only for a typed Effect error. A defect stops the actor or starts supervision. A state exit interrupts the task. An interruption does not emit a failure event. +The success or failure event of a task belongs to the state entry that started the task. The same holds for the event of a `.timeout`. If that entry ends before the actor takes the event from its mailbox, the actor drops the event. An entry ends on a change of state tag or on `.reenter`; a same-tag `.on` transition keeps the entry. So a result that completes while a transition leaves the state never reaches a later entry of the same state, and the handler needs no lease or "is current" check. A `self.send` call in a `.spawn` handler is not owned: its events stay in the mailbox after the entry ends. To read a child's output, await the child in a task and map it with `onSuccess`. + The types require each handler that the run needs: | `run` succeeds with | `run` can fail | The options must give | diff --git a/src/internal/runtime.ts b/src/internal/runtime.ts index 52c37df..45d0fa9 100644 --- a/src/internal/runtime.ts +++ b/src/internal/runtime.ts @@ -49,7 +49,15 @@ import type { DefectPhase } from "../supervision.js"; /** @internal */ export type RuntimeQueuedEvent = - | { readonly _tag: "send"; readonly event: E } + | { + readonly _tag: "send"; + readonly event: E; + /** + * The state scope of the entry that sent this event (a task result or a fired + * timeout). The loop drops the event if that entry has ended at dequeue. + */ + readonly owner?: Scope.Scope; + } | { readonly _tag: "sendWait"; readonly event: E; @@ -390,6 +398,15 @@ export const createRuntime = Effect.fn("effect-machine.runtime.create")(function yield* Queue.offer(eventQueue, { _tag: "send", event }); } }); + const sendOwned = Effect.fn("effect-machine.runtime.self.sendOwned")(function* ( + owner: Scope.Scope, + event: E, + ) { + const stopped = yield* Ref.get(stoppedRef); + if (!stopped) { + yield* Queue.offer(eventQueue, { _tag: "send", event, owner }); + } + }); const childPrefix = config.childIdPrefix ?? ""; const defaultSpawn: MachineRef["spawn"] = (childId, childMachine) => system @@ -413,6 +430,7 @@ export const createRuntime = Effect.fn("effect-machine.runtime.create")(function subscribe: (listener) => subscribeToState(stateRef, listeners, listener), }, spawn, + _sendOwned: sendOwned, reply: (value: unknown) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () { @@ -1009,10 +1027,32 @@ const runtimeEventLoop = Effect.fn("effect-machine.runtime.eventLoop")(function* }; }); + /** An owned event whose state entry has ended. Only `send` entries carry an owner. */ + const isStale = (queued: EventQueued): boolean => + queued._tag === "send" && queued.owner !== undefined && queued.owner !== stateScopeRef.current; + const processQueued = (currentState: S, queued: EventQueued) => Effect.gen(function* () { const event = queued.event; + // A task result or a fired timeout of an ended state entry: drop it before any + // hook sees it. The entry's fiber was interrupted after it queued the event. + if (isStale(queued)) { + const dropped: ProcessEventResult = { + newState: currentState, + previousState: currentState, + transitioned: false, + lifecycleRan: false, + isFinal: false, + hasReply: false, + deferReply: false, + reply: undefined, + postponed: false, + transitions: [], + }; + return { shouldStop: false, stateChanged: false, result: dropped }; + } + if (queued._tag === "ask" && deferredReplyRef !== undefined) { deferredReplyRef.current = { deferred: queued.reply, @@ -1135,8 +1175,9 @@ const runtimeEventLoop = Effect.fn("effect-machine.runtime.eventLoop")(function* makeEventAdvancement({ initial: initialState, isFinal: (state: S) => machine._isFinal(state._tag), + // A stale owned event is never postponed: process drops it. shouldPostpone: (state: S, queued: EventQueued) => - shouldPostpone(machine, state._tag, queued.event._tag), + !isStale(queued) && shouldPostpone(machine, state._tag, queued.event._tag), postpone: postponeQueued, process: (state: S, queued: EventQueued, _draining: boolean) => processQueued(state, queued).pipe( diff --git a/src/machine.ts b/src/machine.ts index db31924..708c6f3 100644 --- a/src/machine.ts +++ b/src/machine.ts @@ -90,6 +90,14 @@ export interface MachineRef { * Returns true if a pending reply was settled, false if none was pending. */ readonly reply: (value: Reply) => Effect.Effect; + /** + * Send an event that belongs to one state entry. `owner` is the state scope of that + * entry. The runtime drops the event at dequeue when its entry has ended, so a task + * result or a fired timeout never reaches a later entry of the same state. + * + * @internal + */ + readonly _sendOwned?: (owner: Scope.Scope, event: Event) => Effect.Effect; } const isStateResolver = ( @@ -1321,6 +1329,15 @@ export class Machine< // eslint-disable-next-line @typescript-eslint/no-explicit-any ctx: StateHandlerContext, ) { + // The state scope that the runtime forks this handler into names its entry. + // Read it before `run`, which can provide a scope of its own. + const owner = yield* Effect.scope; + const sendOwned = ctx.self._sendOwned; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const send = (event: any) => { + if (sendOwned === undefined) return ctx.self.send(event); + return sendOwned(owner, event); + }; yield* emitTaskInspection({ actorId: ctx.actorId, generation: ctx.generation, @@ -1344,7 +1361,7 @@ export class Machine< if (options.onSuccess !== undefined) { successEvent = options.onSuccess(exit.value, ctx); } - yield* ctx.self.send(successEvent); + yield* send(successEvent); yield* Effect.yieldNow; return; } @@ -1382,7 +1399,7 @@ export class Machine< error: Cause.pretty(cause), }); if (options.onFailure !== undefined) { - yield* ctx.self.send(options.onFailure(error, ctx)); + yield* send(options.onFailure(error, ctx)); yield* Effect.yieldNow; return; } diff --git a/test/stale-signal.property.test.ts b/test/stale-signal.property.test.ts new file mode 100644 index 0000000..e3bedba --- /dev/null +++ b/test/stale-signal.property.test.ts @@ -0,0 +1,212 @@ +// @effect-diagnostics strictEffectProvide:off - tests are entry points +// Seeded property: over generated interleavings of reentries, round trips, +// same-tag updates, slow transition handlers, task completions and clock steps, +// every task result and every fired timeout that a handler sees comes from the +// state entry that is current when it is processed. The current entry's own +// signals still arrive. The seeds are fixed, so a failure replays exactly. +import { Deferred, Duration, Effect, Schema } from "effect"; +import { TestClock } from "effect/testing"; + +import { Event, Machine, State } from "../src/index.js"; +import { describe, expect, it, yieldFibers } from "effect-bun-test"; + +const S = State({ + Active: { entry: Schema.Finite, edits: Schema.Finite }, + Away: { entry: Schema.Finite }, +}); + +const E = Event({ + Kick: {}, + SlowKick: {}, + Leave: {}, + SlowLeave: {}, + Back: {}, + Edit: {}, + Result: { entry: Schema.Finite }, + Failed: { entry: Schema.Finite }, + Timeout: { entry: Schema.Finite }, +}); + +type Step = + | { + readonly _tag: "send"; + readonly event: "Kick" | "SlowKick" | "Leave" | "SlowLeave" | "Back" | "Edit"; + } + | { readonly _tag: "open"; readonly entry: number } + | { readonly _tag: "tick"; readonly millis: number }; + +/** mulberry32: a small seeded PRNG, so a failing seed replays exactly. */ +const prng = (seed: number) => { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +}; + +const sendEvents = ["Kick", "SlowKick", "Leave", "SlowLeave", "Back", "Edit"] as const; +const ticks = [250, 1000, 3000] as const; + +const generate = (seed: number): ReadonlyArray => { + const next = prng(seed); + const pick = (values: ReadonlyArray): A => values[Math.floor(next() * values.length)]!; + const length = 6 + Math.floor(next() * 20); + const steps: Step[] = []; + let entries = 1; + for (let i = 0; i < length; i++) { + const roll = next(); + if (roll < 0.45) { + const event = pick(sendEvents); + if (event === "Kick" || event === "SlowKick" || event === "Back") entries += 1; + steps.push({ _tag: "send", event }); + } else if (roll < 0.75) { + steps.push({ _tag: "open", entry: Math.floor(next() * entries) }); + } else { + steps.push({ _tag: "tick", millis: pick(ticks) }); + } + } + return steps; +}; + +const describeStep = (step: Step): string => { + if (step._tag === "send") return step.event; + if (step._tag === "open") return `open(${step.entry})`; + return `tick(${step.millis}ms)`; +}; + +interface Seen { + readonly signal: "Result" | "Failed" | "Timeout"; + readonly eventEntry: number; + readonly state: "Active" | "Away"; + readonly stateEntry: number; +} + +const settle = Effect.gen(function* () { + for (let i = 0; i < 4; i++) yield* yieldFibers; +}); + +const runOne = (seed: number) => + Effect.gen(function* () { + const seen: Seen[] = []; + const gates = new Map>(); + const gate = (entry: number) => { + let found = gates.get(entry); + if (found === undefined) { + found = Deferred.makeUnsafe(); + gates.set(entry, found); + } + return found; + }; + const record = ( + signal: Seen["signal"], + eventEntry: number, + state: { readonly _tag: Seen["state"]; readonly entry: number }, + ) => seen.push({ signal, eventEntry, state: state._tag, stateEntry: state.entry }); + + let nextEntry = 1; + const fresh = () => nextEntry++; + const slow = Duration.seconds(1); + const machine = Machine.make({ state: S, event: E, initial: S.Active({ entry: 0, edits: 0 }) }) + .reenter(S.Active, E.Kick, () => S.Active({ entry: fresh(), edits: 0 })) + .reenter(S.Active, E.SlowKick, () => + Effect.sleep(slow).pipe(Effect.as(S.Active({ entry: fresh(), edits: 0 }))), + ) + .on(S.Active, E.Leave, ({ state }) => S.Away({ entry: state.entry })) + .on(S.Active, E.SlowLeave, ({ state }) => + Effect.sleep(slow).pipe(Effect.as(S.Away({ entry: state.entry }))), + ) + .on(S.Away, E.Back, () => S.Active({ entry: fresh(), edits: 0 })) + // A same-tag `.on` keeps the entry: its signals must still arrive. + .on(S.Active, E.Edit, ({ state }) => S.Active.with(state, { edits: state.edits + 1 })) + .onAny(E.Result, ({ state, event }) => { + record("Result", event.entry, state); + return state; + }) + .onAny(E.Failed, ({ state, event }) => { + record("Failed", event.entry, state); + return state; + }) + .onAny(E.Timeout, ({ state, event }) => { + record("Timeout", event.entry, state); + return state; + }) + .task( + S.Active, + ({ state }) => + Deferred.await(gate(state.entry)).pipe( + Effect.andThen(() => { + // Even entries succeed, odd entries fail: both handlers send owned events. + if (state.entry % 2 === 0) return Effect.succeed(state.entry); + return Effect.fail(state.entry); + }), + ), + { + onSuccess: (entry) => E.Result({ entry }), + onFailure: (entry) => E.Failed({ entry }), + }, + ) + .timeout(S.Active, { + duration: Duration.seconds(3), + event: (state) => E.Timeout({ entry: state.entry }), + }); + + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + const steps = generate(seed); + for (const step of steps) { + if (step._tag === "send") yield* actor.send(E[step.event]); + else if (step._tag === "open") yield* Deferred.succeed(gate(step.entry), undefined); + else yield* TestClock.adjust(Duration.millis(step.millis)); + yield* settle; + } + // Let slow handlers finish, then release the current entry's task. + for (let i = 0; i < steps.length + 2; i++) { + yield* TestClock.adjust(slow); + yield* settle; + } + const last = yield* actor.snapshot; + if (last._tag === "Active") { + yield* Deferred.succeed(gate(last.entry), undefined); + yield* settle; + } + yield* actor.stop; + + const context = `seed ${seed}: ${steps.map(describeStep).join(" ")}`; + for (const signal of seen) { + // Away runs no task and no timer, so every signal it sees is stale. + let ownEntry = signal.stateEntry; + if (signal.state === "Away") ownEntry = -1; + expect({ context, ...signal, stateEntry: ownEntry }).toEqual({ + context, + ...signal, + stateEntry: signal.eventEntry, + }); + } + if (last._tag === "Active") { + // The current entry's own task result arrives. + const own = seen.filter( + (signal) => signal.signal !== "Timeout" && signal.eventEntry === last.entry, + ); + expect({ context, own: own.length }).toEqual({ context, own: 1 }); + } + }); + +// Change these to replay a failing seed (the failure message names it). +// At the unfixed runtime, 45 of the 150 default seeds deliver a stale signal. +const runs = 150; +const firstSeed = 1; + +describe("stale state-entry signals (property)", () => { + it.scoped(`${runs} generated interleavings from seed ${firstSeed}`, () => + Effect.gen(function* () { + for (let seed = firstSeed; seed < firstSeed + runs; seed++) { + yield* Effect.scoped(runOne(seed)); + } + }), + ); +}); diff --git a/test/stale-signal.test.ts b/test/stale-signal.test.ts new file mode 100644 index 0000000..c8f37e4 --- /dev/null +++ b/test/stale-signal.test.ts @@ -0,0 +1,258 @@ +// @effect-diagnostics strictEffectProvide:off - tests are entry points +// A task result, a fired state timeout or a spawn handler's send belongs to the +// state entry that started it. After that entry ends, the signal must not reach a +// later entry of the same state (reenter, or a round trip A -> B -> A). +import { Deferred, Duration, Effect, Schema } from "effect"; +import { TestClock } from "effect/testing"; + +import { Event, Machine, State } from "../src/index.js"; +import { describe, expect, it, yieldFibers } from "effect-bun-test"; + +const S = State({ + Active: { entry: Schema.Finite }, + Away: { entry: Schema.Finite }, + Done: { eventEntry: Schema.Finite, stateEntry: Schema.Finite }, + TimedOut: { stateEntry: Schema.Finite }, +}); +type S = typeof S.Type; + +const E = Event({ + Kick: {}, + SlowKick: {}, + Leave: {}, + SlowLeave: {}, + Back: {}, + Result: { entry: Schema.Finite }, + Failed: { entry: Schema.Finite }, + Timeout: {}, +}); + +const settle = Effect.gen(function* () { + for (let i = 0; i < 5; i++) yield* yieldFibers; +}); + +/** One gate per entry: the task of entry n waits on gates[n]. */ +const makeGates = (count: number) => + Effect.forEach(Array.from({ length: count }), () => Deferred.make()); + +const baseMachine = () => + Machine.make({ state: S, event: E, initial: S.Active({ entry: 0 }) }) + .reenter(S.Active, E.Kick, ({ state }) => S.Active({ entry: state.entry + 1 })) + .reenter(S.Active, E.SlowKick, ({ state }) => + Effect.sleep(Duration.seconds(2)).pipe(Effect.as(S.Active({ entry: state.entry + 1 }))), + ) + .on(S.Active, E.Leave, ({ state }) => S.Away({ entry: state.entry })) + .on(S.Active, E.SlowLeave, ({ state }) => + Effect.sleep(Duration.seconds(2)).pipe(Effect.as(S.Away({ entry: state.entry }))), + ) + .on(S.Away, E.Back, ({ state }) => S.Active({ entry: state.entry + 1 })) + .on(S.Active, E.Result, ({ state, event }) => + S.Done({ eventEntry: event.entry, stateEntry: state.entry }), + ) + .on(S.Active, E.Failed, ({ state, event }) => + S.Done({ eventEntry: event.entry, stateEntry: state.entry }), + ) + .on(S.Active, E.Timeout, ({ state }) => S.TimedOut({ stateEntry: state.entry })) + .final(S.Done) + .final(S.TimedOut); + +describe("stale state-entry signals", () => { + it.scopedLive("task result of an old entry is dropped after reenter", () => + Effect.gen(function* () { + const gates = yield* makeGates(3); + const machine = baseMachine().task( + S.Active, + ({ state }) => Deferred.await(gates[state.entry]!).pipe(Effect.as(state.entry)), + { onSuccess: (entry) => E.Result({ entry }) }, + ); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + // Same tick: the Kick is queued first, then the old task completes and + // queues its Result behind the Kick. + yield* actor.send(E.Kick); + yield* Deferred.succeed(gates[0]!, undefined); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + + // The current entry's own result still lands. + yield* Deferred.succeed(gates[1]!, undefined); + yield* settle; + expect(yield* actor.snapshot).toEqual(S.Done({ eventEntry: 1, stateEntry: 1 })); + }), + ); + + it.scopedLive("task result of an old entry is dropped after a round trip", () => + Effect.gen(function* () { + const gates = yield* makeGates(3); + const machine = baseMachine().task( + S.Active, + ({ state }) => Deferred.await(gates[state.entry]!).pipe(Effect.as(state.entry)), + { onSuccess: (entry) => E.Result({ entry }) }, + ); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + yield* actor.send(E.Leave); + yield* actor.send(E.Back); + yield* Deferred.succeed(gates[0]!, undefined); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + }), + ); + + it.scopedLive("task failure event of an old entry is dropped after reenter", () => + Effect.gen(function* () { + const gates = yield* makeGates(3); + const machine = baseMachine().task( + S.Active, + ({ state }) => + Deferred.await(gates[state.entry]!).pipe(Effect.andThen(Effect.fail(state.entry))), + { + onSuccess: () => E.Kick, + onFailure: (entry) => E.Failed({ entry }), + }, + ); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + yield* actor.send(E.Kick); + yield* Deferred.succeed(gates[0]!, undefined); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + }), + ); + + it.scopedLive("an interrupted task sends no failure event", () => + Effect.gen(function* () { + // The run turns its own interruption into a typed failure. + const machine = baseMachine().task( + S.Active, + ({ state }) => + Effect.never.pipe( + Effect.onInterrupt(() => Effect.void), + Effect.catchCause(() => Effect.fail(state.entry)), + ), + { + onSuccess: () => E.Kick, + onFailure: (entry) => E.Failed({ entry }), + }, + ); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + yield* actor.send(E.Kick); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + }), + ); + + it.scoped("state timeout of an old entry is dropped after reenter", () => + Effect.gen(function* () { + const machine = baseMachine().timeout(S.Active, { + duration: Duration.seconds(5), + event: E.Timeout, + }); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + // The SlowKick handler runs from t=4s to t=6s. The old timer fires at + // t=5s, while the handler runs, so its Timeout is queued behind the reentry. + yield* TestClock.adjust("4 seconds"); + yield* settle; + yield* actor.send(E.SlowKick); + yield* settle; + yield* TestClock.adjust("1 second"); + yield* settle; + yield* TestClock.adjust("1 second"); + yield* settle; + + // The new entry's timer started at t=6s, so it fires at t=11s. + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + yield* TestClock.adjust("5 seconds"); + yield* settle; + expect(yield* actor.snapshot).toEqual(S.TimedOut({ stateEntry: 1 })); + }), + ); + + it.scoped("state timeout of an old entry is dropped after a round trip", () => + Effect.gen(function* () { + const machine = baseMachine().timeout(S.Active, { + duration: Duration.seconds(5), + event: E.Timeout, + }); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + // The old timer fires while the SlowLeave handler runs; Back is queued + // before it, so the stale Timeout is queued behind the round trip. + yield* TestClock.adjust("4 seconds"); + yield* settle; + yield* actor.send(E.SlowLeave); + yield* actor.send(E.Back); + yield* settle; + yield* TestClock.adjust("1 second"); + yield* settle; + yield* TestClock.adjust("1 second"); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + }), + ); + + // A child's output read by a task is owned by the task's entry. (A `.spawn` + // handler that calls `self.send` itself is not owned: see the report of M46.) + it.scopedLive("a child's output read by a task of an old entry is dropped after reenter", () => + Effect.gen(function* () { + const ChildState = State({ Working: {}, Finished: {} }); + const ChildEvent = Event({ Finish: {} }); + const child = Machine.make({ + state: ChildState, + event: ChildEvent, + initial: ChildState.Working, + }) + .on(ChildState.Working, ChildEvent.Finish, () => ChildState.Finished) + .final(ChildState.Finished); + + const gates = yield* makeGates(3); + const delivered = yield* makeGates(3); + const machine = baseMachine().task( + S.Active, + ({ state, self }) => + Effect.gen(function* () { + const ref = yield* self.spawn(`child-${state.entry}`, child).pipe(Effect.orDie); + yield* Deferred.await(gates[state.entry]!); + yield* ref.send(ChildEvent.Finish); + yield* ref.awaitFinal.pipe(Effect.orDie); + // The task maps the child's output; `delivered` pins when it sends. + yield* Deferred.await(delivered[state.entry]!); + return state.entry; + }), + { onSuccess: (entry) => E.Result({ entry }) }, + ); + const actor = yield* Machine.spawn(machine); + yield* actor.start; + yield* settle; + + // The child finishes. Then, in one tick, the Kick is queued and the parent + // handler sends the child's output behind it. + yield* Deferred.succeed(gates[0]!, undefined); + yield* settle; + yield* actor.send(E.Kick); + yield* Deferred.succeed(delivered[0]!, undefined); + yield* settle; + + expect(yield* actor.snapshot).toEqual(S.Active({ entry: 1 })); + }), + ); +});