Skip to content

RFC: Restructure the engine as an explicit CESK-style machine with a functional core #405

Open

Description

@asukaminato0721

Problem

The engine's machine state has no explicit shape. It is spread across:

  • node and edge states stored on Graph / Node objects;
  • 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:

There are also unreproduced hazards with the same root cause:

  • A worker that raises before _current_node is set exits its thread and leaves the node unfinished forever, so the engine hangs.
  • GraphExecution is written from more than one thread without a lock.
  • The same Node instance 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

  1. 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 Machine and use the trace for observation and debugging, not to rebuild state. Streaming chunks should not go through step: they do not change machine state, so they can pass straight through to consumers as effects.

  2. Most of the migration cost is in the node API, not the engine. 23 files under nodes/ read variable_pool directly (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.

  3. Avoid a rewrite. Migrate incrementally, in dependency order:

    1. Move node and edge states off Graph / Node into frame state, so Scheduler becomes a pure function (it is already close).
    2. 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.
    3. Unify container invocations as K records.
    4. Introduce env/store with persistent data structures.
    5. Derive public events from the trace.

    Each step can be merged on its own with the existing tests kept green.

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 ContainerHandler methods (handle_request, complete_frame_if_ready, ...).

Activity

  1. asukaminato0721 commented on Nov 17, 2026

    @asukaminato0721
    Author

    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:

    Effect: AwaitExternal(token, request)      # issue a form
    Input:  ExternalResolved(token, value)     # the human submitted an answer
            TimerFired(token)                  # timeout, i.e. today's Expired
    
    Machine.waiting: Map[Token, WaitRecord]    # token derived from (frame, exec, attempt)

    This has three consequences:

    • Pause is derived, not a special state. When the machine has no ready nodes and no running effects, only waiting entries, the shell can persist the Machine and exit. Resuming just feeds an ExternalResolved input; there is no separate resume path.
    • Waits inside Iteration or Loop compose naturally. Tokens carry the frame, and K records are data, so nesting needs no special handling.
    • A timeout is a SetTimer effect 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:

    1. Journal and replay (the Temporal model). Record the result of every effect the node yields, keyed by (exec, attempt). On resume, rerun the node from the start and send the recorded value back at each yield that 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.
    2. An explicit state machine. The node serializes its own state at the wait point. This is more controllable but puts more burden on node authors.

    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 HumanInputNode is already a simplified option 1. hitl_callback first returns PauseRequested. On resume the node reruns from the start and asks the callback again, and the host remembers the answer by session_id and returns Completed. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions