Skip to content

long running tasks taskflow

sherry-wiki edited this page Nov 17, 2026 · 10 revisions

TaskFlow — Durable Multi-Step Task Flows with DAG Dependencies

Sherry Wiki · English · 中文 · 日本語 · 한국어

← Back to index

TaskFlow provides durable, cross-turn task flows persisted in SQLite with optimistic locking, detached subagent step dispatch, DAG-based dependency management, parallel batch dispatch, bounded-poll waiting, and idempotent result injection. Three grouped tools cover the sixteen-action lifecycle API, mirroring the openclaw managedFlows surface: taskflow_flow(action="create") → taskflow_step(action="run_task") → taskflow_step(action="dispatch") / taskflow_step(action="wait_all") → taskflow_step(action="resume") → taskflow_flow(action="finish") / taskflow_flow(action="fail") / taskflow_flow(action="cancel"), with taskflow_inspect(action="summary") for read-only re-read, taskflow_flow(action="set_waiting") for parking, taskflow_inspect(action="progress") for progress reports, taskflow_flow(action="budget") for token/cost budgets, taskflow_step(action="update_steps") for full steps replacement, and taskflow_inspect(action="list") for the session-scoped board.

Source of truth: agent/tools/taskflow/tools/*.py, agent/tools/taskflow/registry/store_sqlite.py, agent/tools/taskflow/config.py. Skill reference: skills/builtin/core/taskflow/SKILL.md.


Table of Contents


Overview

TaskFlow (agent/tools/taskflow/) is a durable task-flow system built on SQLite with WAL mode. It manages multi-step work that spans multiple conversation turns: each flow has a lifecycle (running → waiting → done/failed/cancelled), steps that can declare dependencies on each other, and results injected by detached child subagent sessions.

Key design choices:

  • Optimistic locking: every mutation bumps expected_revision by 1; concurrent writers are detected via revision conflicts, not last-write-wins.

  • DAG in state_json: step dependencies (depends_on), step status, and results all live inside the flow's state_json column — no DB schema migration needed for DAG features.

  • Detached dispatch: steps are executed by spawning detached child subagent sessions via the existing spawn pipeline; results flow back through the announce/settle-wake pipeline.

  • Idempotent resume: a (child_session_key, result) pair is fingerprinted; duplicate deliveries never inject twice.

  • Error-as-text contract: tools never raise business errors to the LLM; they return human-readable strings prefixed with Error:.


Architecture


agent/tools/taskflow/

├── __init__.py              # Package exports (builders + 11 module functions)

├── config.py                # TaskFlowStatus, StepStatus enums, TERMINAL_STATUSES, TABLE_NAME

├── step_judge.py            # StepJudge — auxiliary-LLM pass/retry/block discriminator

├── evidence_collector.py    # Session/flow evidence summary rendered for judge prompts

├── registry/

│   ├── __init__.py

│   └── store_sqlite.py      # SQLite persistence: create/get/update, WAL, busy_timeout,

│                            #   FlowConflictError/FlowNotFoundError/FlowExistsError,

│                            #   sync path (get_flow_sync)

└── tools/

    ├── __init__.py           # build_taskflow_tools() → 3 tools, scope=main_only

    ├── _dispatch.py          # Monkeypatchable dispatch seam (spawn_subagent_direct)

    ├── _shared.py            # DAG helpers + conflict-retry persistence

    ├── taskflow_merged.py    # Model-facing dispatchers: taskflow_flow / taskflow_step / taskflow_inspect

    ├── taskflow_create.py    # Create flow at revision 1

    ├── taskflow_run_task.py  # Register step + dispatch (or block on unsatisfied deps)

    ├── taskflow_dispatch.py  # Batch dispatch multiple ready steps

    ├── taskflow_wait_all.py  # Bounded-poll wait for dispatched steps to settle

    ├── taskflow_resume.py    # Inject result, mark done, unlock dependents (idempotent)

    ├── taskflow_set_waiting.py # Park flow in waiting state

    ├── taskflow_summary.py   # Read-only re-read (also post-conflict re-read)

    ├── taskflow_progress.py  # Read-only progress report

    ├── taskflow_budget.py    # Token/cost budget query and set

    ├── taskflow_update_steps.py # Full replacement of the steps list

    ├── taskflow_list.py      # Session-scoped flow board

    ├── taskflow_finish.py    # Mark done (terminal)

    ├── taskflow_fail.py      # Mark failed (terminal)

    └── taskflow_cancel.py    # Cancel flow (terminal)

Registration

Tools are registered via build_taskflow_tools() in agent/tools/taskflow/tools/__init__.py, which returns the three merged tools tagged with metadata = {"scope": "main_only"} and handle_tool_error = True. The subagent tool-policy drops them unconditionally — only the main agent manages shared flow state.


State Machine

Flow Status (TaskFlowStatus)


running ──→ waiting ──→ running (via taskflow_step(action="resume"))

  │                       └──→ done     (taskflow_flow(action="finish"), terminal)

  │                       └──→ failed   (taskflow_flow(action="fail"), terminal)

  │                       └──→ cancelled(taskflow_flow(action="cancel"), terminal)

  └──→ done / failed / cancelled (directly from running)

Terminal statuses (done, failed, cancelled) are immutable: every mutating tool rejects them with Error: TaskFlow '<id>' is terminal (status=...); no further mutations allowed.

Step Status (StepStatus)


blocked → ready → dispatched → done

| Status | Meaning | Transition trigger |

| ------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------- |

| blocked | Dependencies not yet all done; taskflow_step(action="run_task") only registers, no spawn | taskflow_step(action="resume") unlocks when deps satisfied |

| ready | Dependencies satisfied, awaiting dispatch | taskflow_step(action="dispatch") dispatches it |

| dispatched | Detached child session spawned, child_session_key persisted | taskflow_step(action="resume") injects result |

| done | Result injected via taskflow_step(action="resume") and its configured gates passed | (terminal for this step) |

| failed | Definitive failure: step_outcome="failure", or a response_schema result stayed invalid after its retry budget | (terminal for this step; dependents stay blocked) |

| skipped | Declared step_outcome="skipped", or a dependency was skipped/cancelled (the skip cascades) | (terminal for this step) |

| cancelled | taskflow_flow(action="cancel") cancelled the flow before the step finished | (terminal for this step) |

done means "a result was injected and the step's configured gates passed" — with no expectation configured (response_schema, judge_criteria/validation_criteria, retry_policy) it degrades to the older meaning: "a result was injected", so a failed child can still land done unless the caller reports step_outcome="failure". The full rule, with what each gate does about it, is in Judgement Gates.

A completion-judge budget exhaustion (the child's goal loop spent goal_max_turns turns without a DONE verdict) is reported as step_outcome="blocked", not failure and not OK: the child did work, so the step keeps its partial result readable and its dependents stay blocked for the agent to retry, replan, or cancel. failed remains reserved for a definitive failure or an unrepairable schema miss.

failed, skipped and cancelled never unlock dependents: a failed dependency leaves its dependents blocked (a failure must not be silently skipped over), and a skipped/cancelled dependency cascades skipped into its dependents so a dead branch settles instead of parking the flow forever.

Expectation → Actual Closure

A step may carry an expectation, and the resume path records the actual alongside it, so "did this step do what was asked" is answerable from the flow state alone.

Expectation fields (all optional, set by taskflow_step(action="run_task"), stored on the step):

| Field | Meaning |

| ---------------------- | ---------------------------------------------------------------------------------------- |

| response_schema | JSON Schema the structured result must satisfy (Tier 1). Also handed to the child as its output contract through the spawn layer's output_schema. |

| judge_criteria | Natural-language acceptance criteria for the LLM step judge (Tier 2). judge_model overrides the judge's model. |

| expected_params | Structured inputs the step is supposed to work on (recorded; nothing is enforced from it). |

| input_bindings | {"param": "step-A.structured_result.files"} — upstream structured values appended to this step's dispatched task as an ## Input parameters block. |

| validation_criteria | Legacy text criteria; still judged when present (used when judge_criteria is absent). |

| retry_policy | Existing failure retry policy (max_retries, retry_delay_seconds, retry_on). |

| file_deps | Project-relative source files this step's verification depends on; when another step writes one, the finish-time replay prioritizes this step. |

Actual fields (taskflow_step(action="resume") records them on the result entry):

| Field | Meaning |

| ------------------- | ----------------------------------------------------------------------------- |

| step_id | Pairing key: which step this result belongs to. |

| structured_result | The parsed structured value (from the caller's structured_result or result). |

| schema_validated | true / false / null (no schema configured) — the Tier 1 verdict. |

| step_outcome | The caller's declaration when given (success / failure / partial / skipped / blocked). |

The two tiers chain in that order, and both are opt-in per step (see taskflow_step(action="resume") below for the exact order of operations).

Legacy Step Compatibility

Steps without a status field are handled by step_status(): a step with a child_session_key is treated as dispatched; otherwise ready. This keeps flows without the field backward-compatible.


Tool Family (3 Tools)

taskflow_flow(action="create")

async def taskflow_flow(action="create", flow_id: str, description: str = "", initial_state: dict | None = None,
                         deadline_hours: float | None = None, resumed_from: str | None = None) -> str

Creates a durable flow at INITIAL_REVISION = 1 with status running. Returns the flow id, status, and revision. An existing non-terminal flow with the same id returns an idempotent success (TaskFlow already exists ...); a terminal flow returns an error telling the caller to pick a new id or pass resumed_from.

Pass resumed_from=<predecessor flow_id> when the flow REPLACES an earlier one: the new flow records resumed_from and the predecessor is stamped superseded_by — see Flow Lineage. An unknown predecessor is refused before anything is created; a self-reference is refused too.

Resource ceilings (enforced here, refused as Error: text): at most TASKFLOW_INFRA["max_steps_per_flow"] (20) steps per flow, and at most TASKFLOW_INFRA["max_flows_per_session"] (20) ACTIVE flows per session — running/waiting ones only, a finished or cancelled flow releases its slot (a superseded one releases it too). taskflow_flow(action="plan") applies the same flow ceiling before it spends a planner call.

taskflow_flow(action="plan")

Asks the TaskFlow planner for a dependency-ordered step list, creates the flow with the stable plan-<sha256(session_id + goal)[:10]> id, binds its todo root, and auto-dispatches every initial ready step (the no-dependency siblings) through the same batch dispatch path a manual call uses. Steps with unmet depends_on stay blocked; a failed spawn is fail-open and leaves its step ready. TASKFLOW_INFRA["auto_dispatch_initial_ready"] (default true) restores the old review-then-dispatch behavior. The returned plan shows the post-dispatch statuses and names the auto-dispatched ids.

taskflow_step(action="run_task")

async def taskflow_step(action="run_task",
    flow_id: str, task: str, label: str | None = None,

    expected_revision: int | None = None,

    depends_on: list[str] | None = None,

    validation_criteria: str | None = None,

    retry_policy: dict | None = None,

    aggregate_deps: bool = False,

    response_schema: dict | None = None,

    expected_params: dict | None = None,

    input_bindings: dict | None = None,

    judge_criteria: str | None = None,

    judge_model: str | None = None,

    functional_role: str | None = None,

    step_model: str | None = None,

    step_timeout_seconds: float | None = None,

    priority: int | None = None,

    session_id: Annotated[str, InjectedState("session_id")] = "",

) -> str

Registers a step on the flow and dispatches it to a detached child subagent. Step ids are auto-assigned as step-1, step-2, etc.

  • No dependencies (or all satisfied) → step is dispatched immediately (child spawned).

  • Unsatisfied dependencies → step is registered as blocked, no child spawned. Unknown dependency ids are rejected before any spawn or state change.

  • Expectation parameters are stored on the step and enforced at resume: response_schema (also passed to the spawn layer as the child's output_schema), judge_criteria / judge_model, expected_params, input_bindings.

  • Execution metadata rides along to the child: functional_role (researcher / executor / reviewer / librarian / general), step_model, step_timeout_seconds; priority is a dispatch-ordering hint.

  • A field that is omitted stays absent on the step, which is what keeps a flow without expectations byte-identical to the pre-closure format.

  • Returns step_id, child_session_key, and revision (or pending=[...] listing unsatisfied deps when blocked).

taskflow_step(action="dispatch")

async def taskflow_step(action="dispatch",
    flow_id: str, step_ids: list[str],

    expected_revision: int | None = None,

    session_id: Annotated[str, InjectedState("session_id")] = "",

) -> str

Batch-dispatches one or more currently-ready steps. A step is dispatchable when ready, or blocked but its dependencies are now satisfied.

  • All-or-nothing validation: every id is validated before any spawn. An unknown id, an already-dispatched/done step, or a blocked step with unsatisfied deps rejects the whole call with zero spawns.

  • Mid-batch failure: if a spawn fails mid-batch, already-spawned steps are persisted in one update_flow so no child is left unrecorded. The error names the failed and dispatched step ids.

  • The flow-level child_session_key is deliberately NOT touched — per-step child keys are authoritative.

taskflow_step(action="wait_all")

async def taskflow_step(action="wait_all",
    flow_id: str, timeout_seconds: float = 300.0,

    poll_interval_seconds: float = 0.5,

    session_id: Annotated[str, InjectedState("session_id")] = "",

) -> str

Waits until this flow's dispatched child sessions settle (or a timeout). Polls ONLY the child sessions recorded on THIS flow's dispatched steps — unrelated background children never block the return.

  • An unknown/absent run is treated as settled (never hangs).

  • On timeout, returns a partial report with instructions to taskflow_step(action="resume") the settled children and call wait_all again.

  • The registry seam (get_run_by_child_session_key / is_live_unended_run) is lazily imported and injectable for tests.

taskflow_step(action="resume")

async def taskflow_step(action="resume",
    flow_id: str, child_session_key: str = "", result: str = "",

    expected_revision: int | None = None, token_usage: dict | None = None,

    validation_criteria: str | None = None,

    structured_result: dict | None = None,

    step_outcome: str | None = None,

    auto_dispatch: bool = True,

) -> str

Injects a completed child session result into the flow state (idempotent). Appends {child_session_key, result, result_hash, injected_at, step_id, schema_validated} (plus structured_result / step_outcome when known) to results. If the flow was waiting, returns to running.

Order of operations — the gates chain and every one is opt-in per step: retry_policy (a classified failure, or schema_validated=false, re-dispatches onto a replacement child before any judge call) → response_schema (Tier 1, validated for free; a miss is a schema_error retry) → judge_criteria / validation_criteria (Tier 2, the auxiliary-LLM judge) → a caller-declared step_outcome, which outranks them all. Verdicts, budgets, the evidence-aware judge prompt, the fail-open rules and what done really means are documented in Judgement Gates.

DAG bookkeeping: a successful gate marks the matching step done and calls unlock_dependents() to move newly-satisfied blocked steps to ready; a failed step leaves its dependents blocked, and a skipped/cancelled step cascades skipped into them. Returns the unlocked step ids. The write re-applies the already-decided verdict onto the freshly-read state on a conflict retry, so two children completing at the same moment both land (see Conflict Retry with Spawned Children). With auto_dispatch=True (the default) the full ready set is spawned immediately in a bounded concurrent batch — see Auto-Dispatch Wave; pass auto_dispatch=False to unlock only and dispatch explicitly via taskflow_step(action="dispatch").

taskflow_flow(action="set_waiting")

async def taskflow_flow(action="set_waiting",
    flow_id: str, wait_reason: str = "",

    expected_revision: int | None = None,

) -> str

Parks the flow in waiting state, recording what it is waiting for. The wait payload is cleared by taskflow_step(action="resume").

taskflow_inspect(action="summary")

async def taskflow_inspect(action="summary", flow_id: str) -> str

Read-only re-read of the full flow state: status, revision, child_session_key, description, all steps (with status, depends_on, child_session_key, plus the configured expectations — response_schema properties/required, judge_criteria, judge_model, input_bindings, expected_params, execution metadata and any block_reason / fail_reason / skip_reason), step status counts, results (each with its step_id, schema_validated, structured_result, step_outcome, judge_verdict / judge_reason and token_usage when recorded), wait payload, summary, failure_reason, cancel_reason. Also the designated re-read step after a revision conflict.

taskflow_inspect(action="progress")

async def taskflow_inspect(action="progress", flow_id: str) -> str

Read-only completion report: completion percentage, the full status breakdown (done / dispatched / ready / blocked / failed / skipped / cancelled), the next steps worth starting, a Needs a decision list naming every failed / blocked / skipped / cancelled step with its recorded reason, and an estimated remaining time (when at least two done steps carry a dispatched_at timestamp). Never mutates the flow.

taskflow_flow(action="budget")

async def taskflow_flow(action="budget",
    flow_id: str, action: str = "query", token_budget: int | None = None,

    expected_revision: int | None = None,

) -> str

Queries (query) or sets (set) the flow's token/cost budget. query reports total_tokens, total_cost, the budget, tokens remaining, and a status (ok / WARNING at 80% / EXCEEDED); set requires a positive token_budget and writes through the optimistic lock.

taskflow_step(action="update_steps")

async def taskflow_step(action="update_steps",
    flow_id: str, steps: list[dict],

    expected_revision: int | None = None,

) -> str

Full replacement of the flow's steps list (like todowrite for TaskFlow): steps can be added, removed, reordered, or have their task/depends_on rewritten. Safety rules keep a dispatched step bound to its child_session_key and refuse to rewrite a done step; deleting a dispatched step whose child still runs succeeds with a non-blocking Warning: naming the child key.

taskflow_inspect(action="list")

async def taskflow_inspect(action="list", status_filter: str = "active") -> str

Read-only board of this session's flows: "active" (running + waiting), "all" (terminal statuses included), or an exact status name. Every read filters the owning session_id in SQL; the rendered table caps the description at 40 chars and reads updated_at from the flow row (falling back to the legacy activity stamps for rows without the column value).

taskflow_flow(action="finish") / taskflow_flow(action="fail") / taskflow_flow(action="cancel")

async def taskflow_flow(action="finish", flow_id: str, summary: str = "", expected_revision: int | None = None) -> str

async def taskflow_flow(action="fail", flow_id: str, reason: str = "", expected_revision: int | None = None) -> str
async def taskflow_flow(action="cancel", flow_id: str, reason: str = "", expected_revision: int | None = None) -> str

Terminal transitions. finish records a summary, fail records a failure_reason, cancel records a cancel_reason in the flow state. Already-dispatched child sessions may keep running, but once the flow is terminal taskflow_step(action="resume") refuses every result; resume them before finishing, failing, or cancelling.

finish gates the DONE transition on four checks, in order — A every step is done or blocked; B no unresolved step remains (a failed, skipped, cancelled or blocked step is reported by id with its recorded reason); C the flow's evidence carries no FAIL and no [stale] row; E the opt-in goal judge, for a flow of GOAL_GATE["min_steps"] (3) steps or more. Every gate is fail-open; the reject reasons and the goal gate's contract are documented in Judgement Gates.

cancel marks every step that had not finished as cancelled (with the cancel reason) before flipping the flow terminal, so the step statuses never keep claiming ready / dispatched / blocked after the flow is gone.


Optimistic Locking & Conflict Retry

All mutations go through UPDATE ... WHERE flow_id = ? AND expected_revision = ?. When the update matches zero rows, the write conflicted (or the flow vanished):

  • FlowConflictError: carries the latest revision so the caller can re-read and retry. The error text embeds it: expected_revision=2 but latest revision=3; re-read with taskflow_inspect(action="summary") and retry with expected_revision=3.

  • FlowNotFoundError: the flow was deleted.

Retry flow (from the LLM's perspective):

  1. Call taskflow_inspect(action="summary", flow_id) to re-read, getting the latest revision.

  2. Re-apply the mutation with expected_revision=<latest revision>.

  3. The conflict error text contains the directly-usable retry value.

Terminal flows are immutable: every mutating tool checks is_terminal(status) before any state change.


DAG Dependency System

DAG fields live entirely inside state_json (no DB migration). The StepStatus enum defines seven states (blocked, ready, dispatched, done, failed, skipped, cancelled), and three pure functions in _shared.py manage transitions:

deps_satisfied(step, steps) → bool

True iff every depends_on id exists in steps and is done. Missing/empty depends_on is trivially satisfied. An unknown dep id is never satisfied. A self-dependency is never satisfied, which makes a self-referential step safe to leave blocked without an infinite unlock loop.

mark_step_done(steps, child_session_key) → str | None

Marks the step matching child_session_key as done. Idempotent: a repeated call for the same key returns the same step id. Returns None when no step carries that child key.

unlock_dependents(steps) → list[str]

A single pass through steps: moves blocked steps with now-satisfied dependencies to ready, and returns the newly-ready step ids. Single-pass ensures a dependency cycle can never loop. Unlocking is failure-aware: a dependency that ended failed (or is still blocked / in flight) leaves its dependents blocked, and a dependency that was skipped or cancelled cascades skipped into its dependents with a skip_reason — so a dead branch settles instead of parking the flow forever.


Synthesize — aggregate_deps

Pass aggregate_deps=true to taskflow_step(action="run_task") to make a synthesis step receive

its dependency steps' recorded results appended to the dispatched task text. The

aggregation is built by

agent/tools/taskflow/tools/_shared.py::build_task_with_dep_results(step, steps, results):

results are matched by each dependency step's child_session_key against the

flow's {child_session_key, result, result_hash} ledger and appended under a

## Upstream Results header in depends_on order. A dependency without a

recorded result yields a no result recorded placeholder.

The flag is stored on the step, so taskflow_step(action="dispatch"), the StepJudge retry and

the retry-policy paths re-derive the aggregation without rewriting the stored

task. The default (aggregate_deps absent or false) leaves the dispatched text

unchanged.

Parallel Step Execution

Two tools enable parallel execution of independent steps:

Batch Dispatch (taskflow_step(action="dispatch"))

Validates the entire batch before any spawn (all-or-nothing). The batch then spawns CONCURRENTLY through the shared _dispatch.dispatch_child seam, bounded by TASKFLOW_INFRA["max_parallel_dispatch"] (2 by default: the SUBAGENT lane is the global backpressure, this cap only decides how many spawn calls are in flight at once). One spawn failing no longer aborts its siblings — every successful child is persisted in ONE update_flow call and every failed step id is named in the answer (Error: dispatch failed for step_id(s) …; dispatched=[…]). A failed step also gets a persisted last_spawn_error (+ last_spawn_failed_at) marker — in the same write when anything spawned, in a marker-only write when nothing did — and a successful dispatch clears both, so the board can tell a retry target from work the next automatic wave will start. The apply_dispatched_steps() helper re-applys recorded dispatched-step payloads onto a freshly-read step list, matching by step_id — a spawned child is never lost to a concurrent writer that rewrote the step list. max_parallel_dispatch = 1 restores the historical sequential behaviour exactly.

Auto-Dispatch Wave (taskflow_step(action="resume"))

A resume starts the whole ready set, not only the dependents it unlocked (auto_dispatch=True, the default): newly_ready ∪ all_ready — the newly unlocked downstream plus sibling steps that were already ready but never dispatched — spawns concurrently through the same seam and the same max_parallel_dispatch bound. TASKFLOW_INFRA["auto_dispatch_all_ready_on_resume"] (default true) controls the wider scan; set it false (or pass auto_dispatch=False) to keep the historical unlock-only/newly-unlocked behaviour. The spawned keys are persisted with the CAS-retried write (update_flow_with_conflict_retry) so a concurrent writer cannot drop them. Each step is dispatched exactly like taskflow_step(action="dispatch") does it (task bindings + any judge feedback). Failures are reported, never raised: a step that could not spawn stays ready, the resume's answer carries auto_dispatch_failed=<step_id>: <error> for a manual retry, and the step is stamped with last_spawn_error so the board keeps naming it as a retry target (a failed spawn that later succeeds clears the marker). Already-dispatched steps are filtered and re-checked under the flow lock, so the wider scan spawns each step exactly once.

Bounded-Poll Wait (taskflow_step(action="wait_all"))

Flow-scoped: only polls child sessions recorded on THIS flow's dispatched steps. Never blocks behind unrelated background children. Clamped poll interval (minimum 0.05s). Unknown/absent runs are settled (never hangs). Timeout returns a partial report.


Live progress

Steps are reported as a flat list per flow (agent/tools/taskflow/progress_push.py):

each row carries the step id, the task text and its status, plus per-status

totals. The scheduler unlocks each step on its own dependencies; there is no

wave/round projection, so the payload never implies a barrier between groups of

steps.

The chat's floating progress panel (top-right, collapsed to a pill by default)

renders that step list plus the session's todo list. Both halves arrive over the

WebSocket: every flow mutation pushes taskflow_updated with the same payload the

taskflow_refresh request answers with, so a reconnecting client recovers the

board with one frame. Nothing is polled.

Idempotent Resume

taskflow_step(action="resume") fingerprints the (child_session_key, result) pair using SHA-256 truncated to 16 hex chars. Before injecting, it checks whether a result with the same result_hash already exists in the flow's results list. If so, the call is a no-op: it neither re-injects nor bumps the revision. This makes announce-pipeline redeliveries safe — duplicate deliveries cannot corrupt the state.


Conflict Retry with Spawned Children

When a child session has ALREADY spawned but the optimistic-lock write loses the race, the child must never be silently dropped. update_flow_with_conflict_retry() in _shared.py handles this:

  1. After a successful spawn, the caller invokes this with a build_state callback.

  2. On FlowConflictError: re-read the flow, re-invoke build_state(fresh_flow, attempt) against the freshly-read state, and retry up to PERSIST_MAX_ATTEMPTS = 3.

  3. On FlowNotFoundError or a terminal fresh flow: return an error naming every spawned child_session_key — the caller must recover them by key, NOT re-dispatch.

  4. On exhaustion: same error, naming all child keys.

The build_state callback receives a fresh flow and an attempt number, so it can rebuild state against the latest data (e.g., re-assigning step_id based on the current step count).


Flow Lineage

Two nullable columns on task_flows record how flows evolved (resumed_from TEXT, superseded_by TEXT, in the current schema; rows with no lineage read NULL):

| Column | Written when | Meaning |

| ------ | ------------ | ------- |

| resumed_from | flow creation (taskflow_flow(action="create", resumed_from=…)) | the predecessor flow this one continues |

| superseded_by | the successor's creation, stamped onto the predecessor | the flow that replaced this one |

The writer is the CREATE path, not taskflow_flow(action="replan"): replan regenerates a flow's remaining steps IN PLACE (update_flow_with_conflict_retry on the same flow_id), so it never forks a new flow and has no lineage to record. taskflow_flow(action="finish") never touches either column — finishing is a terminal state, not a replacement.

Consequences: get_active_flows_sync excludes a superseded flow even while its status is still running/waiting (the continuation enforcer, the progress panel and the per-session flow cap all read through it), while get_all_flows_sync(session_id, "all") still shows it with its back-pointer — the history view keeps it. taskflow_inspect(action="summary") renders both pointers (resumed_from: …, superseded_by: …). The back-pointer write is a plain session-scoped UPDATE that deliberately does NOT bump expected_revision: lineage is metadata, so a caller holding the predecessor's revision is not invalidated.


Persistence & Connection Lifecycle

store_sqlite.py mirrors the subagent registry blueprint:

  • Database: src/data/registry.db (task_flows table)

  • Table: task_flows(flow_id TEXT PK, state_json TEXT NOT NULL, wait_json TEXT, expected_revision INTEGER NOT NULL, status TEXT NOT NULL, child_session_key TEXT)

  • WAL mode: switched once per process via _switch_to_wal_if_needed(); the pragma is skipped once the file is already WAL.

  • Busy timeout: 5000ms on EVERY connection (first statement). The journal-mode switch does not reliably honor this, handled separately with try/except tolerance.

  • Async init: once-per-process under an asyncio.Lock owned by the calling loop; other loops poll _initialized (never touch a foreign loop's lock — avoids non-threadsafe call_soon wakeups).

  • Sync path: get_flow_sync() uses stdlib sqlite3 with threading.Lock-guarded one-time table creation. Failures are logged and swallowed with a None return (for system prompt injection where no event loop exists).


Known Limitations

  • done ≠ success: step done means "a result was injected and the step's configured gates passed". With no expectation configured (response_schema, judge_criteria/validation_criteria, retry_policy) it degrades to the old meaning, so a failed child still lands done unless the caller reports step_outcome="failure". To make the closure catch a failure: declare an expectation (a response_schema is validated for free, before any judge call) or report the outcome; failed then blocks its dependents, and retry_policy still re-dispatches a settled child while budget remains (the step judge keeps marking blocked on a block verdict or an exhausted budget). The full rule, with what each gate does about it, is in Judgement Gates.

  • taskflow_step(action="wait_all") timeout is bounded polling: a never-settling child session does not automatically fail the flow. The timeout returns a partial report.

  • Step ids are sequential: step-{len(steps)+1} assigned at registration time. If steps are appended concurrently, the id is re-computed inside build_state on conflict retry.

Clone this wiki locally