Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stale-task-signals.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/async-work.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
45 changes: 43 additions & 2 deletions src/internal/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,15 @@ import type { DefectPhase } from "../supervision.js";

/** @internal */
export type RuntimeQueuedEvent<S, E> =
| { 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;
Expand Down Expand Up @@ -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<E, S>["spawn"] = (childId, childMachine) =>
system
Expand All @@ -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* () {
Expand Down Expand Up @@ -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<S, E> = {
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,
Expand Down Expand Up @@ -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(
Expand Down
21 changes: 19 additions & 2 deletions src/machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ export interface MachineRef<Event, State = never> {
* Returns true if a pending reply was settled, false if none was pending.
*/
readonly reply: <Reply>(value: Reply) => Effect.Effect<boolean>;
/**
* 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<void>;
}

const isStateResolver = <State, Value>(
Expand Down Expand Up @@ -1321,6 +1329,15 @@ export class Machine<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ctx: StateHandlerContext<any, any>,
) {
// 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,
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand Down
212 changes: 212 additions & 0 deletions test/stale-signal.property.test.ts
Original file line number Diff line number Diff line change
@@ -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<Step> => {
const next = prng(seed);
const pick = <A>(values: ReadonlyArray<A>): 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<number, Deferred.Deferred<void>>();
const gate = (entry: number) => {
let found = gates.get(entry);
if (found === undefined) {
found = Deferred.makeUnsafe<void>();
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));
}
}),
);
});
Loading
Loading