Repository navigation
Description
Problem
The engine's machine state has no explicit shape. It is spread across:
- node and edge states stored on
Graph/Nodeobjects; - the unfinished-node set inside each
Scheduler; - flags on
GraphExecution; - container runs and frames stored in the root
RuntimeState; - open-frame tracking inside
FrameRegistry.
Three kinds of threads (the consumer, the dispatcher, and the workers) change this state through side effects. As a result, pause, snapshot, and completion detection have to reassemble state ad hoc, and several bugs come from this structure:
- Retry interval blocks the dispatcher and stalls all parallel branches #402: the retry interval is slept on the dispatcher thread and stalls every branch;
- A node that succeeds on retry makes the graph PartialSucceeded #403: a node that succeeds on retry is still counted as an exception;
- Closing Engine.run() early marks the execution as successfully completed #404: closing
Engine.run()early marks the execution as successfully completed.
There are also unreproduced hazards with the same root cause:
- A worker that raises before
_current_nodeis set exits its thread and leaves the node unfinished forever, so the engine hangs. GraphExecutionis written from more than one thread without a lock.- The same
Nodeinstance can be used by two workers around a retry. - Every collected event is deep-copied, and every frame baseline copies the whole variable pool.
Proposal: an explicit CESK-style machine with a functional core
1. Use CESK rather than CEK: the store is required
Iteration already has these semantics: "inherited node variables are private to each round, while host variables are written back to the parent". This is exactly what separating the environment from the store gives you in CESK:
- E (bindings): selector → address. A child frame extends its parent's environment. Private variables are rebound to fresh addresses, and host variables keep pointing at the parent's address.
- S (store): address → value. Variable assigners,
UpdateVariablesCommand, and Loop write-back become plain assignments to a shared address.
This removes hand-written write-back logic such as _write_back_host_variable. It also forces us to define conflict semantics when parallel iterations write the same host address. Today, the later write in dispatch order wins.
2. Control is not a single point: use a dataflow token model inside a frame
CEK describes sequential evaluation of one term. A DAG has parallel branches, joins, and dead-path elimination (the current TAKEN / SKIPPED edge propagation). Inside a frame, a workflow-net / dataflow token model fits better: each frame tracks its edge states, join counts, and ready set. CEK structure is used for nesting: container invocations are continuations (K), and subgraph scopes are environments (E).
resume_container plus the container run state is already a defunctionalized continuation, but only as a special case. Making it uniform data (IterK / LoopK / CustomK) means pause/resume no longer depends on suspended Python generators.
3. Functional core, imperative shell; tracing derived from transitions
@dataclass(frozen=True)
class Machine:
frames: Map[FrameId, Frame] # C: per-frame edge states / join counts / ready set
store: Map[Addr, Value] # S
conts: Map[InvocationId, Cont] # K: IterK / LoopK / CustomK, plain data
inflight: Map[ExecId, Attempt] # effects issued but not yet answered
status: Running | Paused | Aborted | Failed | Done
@dataclass(frozen=True)
class Frame:
env: Map[Selector, Addr] # E
edge_state: Map[EdgeId, EdgeState]
ready: frozenset[NodeId]
parent: InvocationId | None
def step(m: Machine, inp: Input) -> tuple[Machine, list[Effect], list[Trace]]: ...
# Input: NodeFinished(exec, attempt, result) | Command | TimerFired
# Effect: RunNode(exec, attempt, node, resolved_inputs) | SetTimer(delay, input)A single shell thread owns the Machine, and the worker pool only executes RunNode effects. Here is how each current issue would be handled:
| Issue | In the new model |
|---|---|
| #402 retry blocks dispatcher | A retry becomes a SetTimer effect; no thread sleeps |
| #403 retry counted as exception | One pure rule in step, unit-testable without threads |
| #404 early close counted as success | The shell sends Abort on close; only step can reach Done |
| Worker thread dies and the engine hangs | The shell guarantees exactly one completion input per RunNode (try/finally); inflight is owned by the core |
Two workers share a Node during retry |
Results are keyed by (exec, attempt); late results from stale attempts are dropped |
Multi-threaded writes to GraphExecution |
A single owner removes the race |
| Deep copies of events and frame baselines | A persistent store with structural sharing makes a baseline a reference |
| Snapshots | A snapshot is a serialized Machine; nothing to reassemble at pause |
Tracing: public events (node, frame, and edge events) become projections of state transitions instead of ad hoc collect calls. The existing public event shapes can be kept as projections for compatibility.
Caveats
-
Do not make event sourcing the only persistence. LLM nodes are not deterministic, so replay would depend on recorded results, and streaming chunks make the log grow fast. Instead, snapshot the
Machineand use the trace for observation and debugging, not to rebuild state. Streaming chunks should not go throughstep: they do not change machine state, so they can pass straight through to consumers as effects. -
Most of the migration cost is in the node API, not the engine. 23 files under
nodes/readvariable_pooldirectly (only one writes to it directly). For bindings to control what a node sees, nodes need resolved inputs or a read-only environment view. A read-only pool adapter backed by env + store can bridge the transition. -
Avoid a rewrite. Migrate incrementally, in dependency order:
- Move node and edge states off
Graph/Nodeinto frame state, soSchedulerbecomes a pure function (it is already close). - Make the dispatcher the single state owner, and replace sleeps with timer effects. This also fixes Retry interval blocks the dispatcher and stalls all parallel branches #402–Closing Engine.run() early marks the execution as successfully completed #404.
- Unify container invocations as K records.
- Introduce env/store with persistent data structures.
- Derive public events from the trace.
Each step can be merged on its own with the existing tests kept green.
- Move node and edge states off
Open questions
- Conflict semantics for concurrent writes to the same host address from parallel iterations: keep "later dispatch order wins", or make it explicit?
- Persistent map implementation: a new dependency versus an in-repo implementation.
- The shape of the custom container protocol as pure transitions, replacing the current
ContainerHandlermethods (handle_request,complete_frame_if_ready, ...).
Activity
asukaminato0721 commentedon Nov 17, 2026
Human-in-the-loop in this model
Coroutines are fine as a node authoring style, but a live coroutine must not be part of machine state. A human-in-the-loop wait can span process restarts and last for days, and Python generators/coroutines cannot be serialized. The continuation at a wait point has to be data, for the same reason container invocations become K records.
Proposal: human-in-the-loop is an external effect, not a separate mechanism
The machine already handles "issue an effect, receive its result later". A human is just a slow, external executor:
This has three consequences:
waitingentries, the shell can persist theMachineand exit. Resuming just feeds anExternalResolvedinput; there is no separate resume path.SetTimereffect racing the human answer; whichever arrives first wins.The simplest form is node-boundary waiting: the human input node itself is the effect, and its result comes from a human instead of a worker. No coroutine is needed at all.
When a coroutine is actually needed
Waiting in the middle of a node, for example an agent asking a human during its tool loop and then continuing, requires writing the node as a coroutine (
answer = yield Ask(form)). There are two ways to persist it:sendthe recorded value back at eachyieldthat already has one. The cost: side effects before the wait point must also go through journaled effects, otherwise resuming calls the LLM again and may get a different result.Default to node-boundary waiting, and offer option 1 only to the few nodes that need to wait mid-run (e.g. agents).
Comparison with the current implementation
The current
HumanInputNodeis already a simplified option 1.hitl_callbackfirst returnsPauseRequested. On resume the node reruns from the start and asks the callback again, and the host remembers the answer bysession_idand returnsCompleted. The journal lives in the host instead of the engine.There is also a behavior difference that needs a decision. Today one human input node triggers
graph_execution.pause, after which the dispatcher stops every branch from acquiring new tasks, so one branch waiting on a human stops all parallel branches. In the effect model only that token is blocked, and other branches keep running until no runnable work remains. If graph-wide pause is an intended product behavior, it can be kept as a shell policy; if not, it is another design issue to fix.