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
13 changes: 13 additions & 0 deletions .changeset/local-rejects-refused-events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@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.

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.
26 changes: 19 additions & 7 deletions LLMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1897,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
Expand All @@ -1918,9 +1930,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,
Expand Down
8 changes: 8 additions & 0 deletions ai-docs/src/10_modeling/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 11 additions & 7 deletions ai-docs/src/37_new-host/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -53,9 +57,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,
Expand Down
12 changes: 9 additions & 3 deletions packages/effect-machine/src/LocalMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
*
Expand Down
74 changes: 54 additions & 20 deletions packages/effect-machine/src/Machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,8 +632,12 @@ export interface MachineTarget<in Event> {
/** 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<void, StoppedError>
/**
* 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<void, StoppedError | MachineSchemaDecodeError>
}

/**
Expand Down Expand Up @@ -1319,8 +1323,19 @@ export interface MachineRef<out State, in Event, out Error = never, out Output =
/** Stops this machine instance and the children it owns. */
readonly stop: Effect.Effect<void>

/** Accepts an event for delivery. When the machine processes it is up to its host. */
readonly send: (event: Event) => Effect.Effect<void, StoppedError>
/**
* 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<void, StoppedError | MachineSchemaDecodeError>

/**
* Returns the current directly owned child for a typed descriptor.
Expand Down Expand Up @@ -1450,9 +1465,17 @@ export declare namespace Logic {
/** Starts a child process owned by this process. */
readonly spawn: Spawn<Event>

/** 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: {
<TargetEvent>(target: MachineTarget<TargetEvent>, event: TargetEvent): Effect.Effect<void, StoppedError>
<TargetEvent>(target: Endpoint<TargetEvent>, event: TargetEvent): Effect.Effect<void, StoppedError>
<TargetEvent>(
target: MachineTarget<TargetEvent>,
event: TargetEvent
): Effect.Effect<void, StoppedError | MachineSchemaDecodeError>
<Address extends ChildAddress<never>>(
id: Address,
event: ChildAddress.Event<Address>
Expand Down Expand Up @@ -7755,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.
Expand Down Expand Up @@ -7785,7 +7808,11 @@ export declare namespace MachineStep {
/** What transitions asked of the host with `enqueue.sendTo` and `enqueue.stop`, in order. */
readonly commands: ReadonlyArray<Command<M>>

/** 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<Work<M>>

/** Events emitted to the observers of the machine, in order. */
Expand All @@ -7794,6 +7821,14 @@ export declare namespace MachineStep {
/** Work to start, in order. Report its end with `settle`. */
readonly start: ReadonlyArray<Work<M>>

/**
* 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<Work<M>>

/**
* 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
Expand Down Expand Up @@ -7992,17 +8027,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
Expand All @@ -8011,7 +8045,7 @@ export declare namespace MachineStep {
readonly _tag: "Timer"

/** Evaluates how long the timer waits, at most once. */
readonly duration: () => Exit.Exit<Exit.Exit<Duration.Duration>>
readonly duration: () => Exit.Exit<Duration.Duration>

/** Evaluates the timer as an Effect that waits for its duration. */
readonly effect: () => Exit.Exit<StepEffect<void, never>>
Expand Down Expand Up @@ -8305,7 +8339,7 @@ type UnsupportedCapability<R, Capabilities> = 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**
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export type ChildEntry =
readonly _tag: "Starting"
readonly token: symbol
readonly ownerKey?: string
readonly ownerPath?: string
ownerActive?: boolean
}
| {
Expand All @@ -24,7 +23,6 @@ export type ChildEntry =
readonly descriptor: ChildDescriptor | undefined
readonly ref: MachineRef<any, any, any, any>
readonly ownerKey?: string
readonly ownerPath?: string
ownerActive?: boolean
}

Expand Down Expand Up @@ -132,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 }
: {
Expand All @@ -141,7 +139,6 @@ export const registerChild = (
descriptor,
ref,
ownerKey: entry.ownerKey,
ownerPath: entry.ownerPath!,
ownerActive: entry.ownerActive === true
}
registry.children.set(key, started)
Expand Down
15 changes: 11 additions & 4 deletions packages/effect-machine/src/internal/machine/clusterInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,7 @@ export const make = <R>(options: Options<R>): Effect.Effect<ClusterInstance<R>,
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: [] }
}
Expand Down Expand Up @@ -1397,14 +1397,21 @@ export const make = <R>(options: Options<R>): Effect.Effect<ClusterInstance<R>,
): Effect.Effect<{ readonly key: Checkpoint.InvocationKey; readonly cause: Cause.Cause<unknown> } | 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 }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading