Files
pipewright/docs/design.md
T

16 KiB

pipewright design (v0)

Why

pipewright generalizes a hand-run workflow: mine candidates from several sources, label them with heuristics and LLMs, build agentic tasks, validate them in Docker sandboxes and remote KVM VMs, probe them with a ladder of models through agent harnesses, audit failures, and compute funnels. Every stage was an ad-hoc script, and each one re-implemented the same infrastructure: funnels, caching, resumption, provider rate limits, VM lifecycles. Provider quirks broke runs again and again: an HTTP 200 whose stream carried an error event, 429s that still counted against the per-minute window, agents that "completed" because their last model call failed.

The design goal: write that infrastructure once, keep the core generic, and put domain logic in plugin packs.

Module map

src/pipewright/
  items.py         Item (immutable, content-addressed, lineage, provenance), ArtifactRef
  hashing.py       canonical JSON + digests
  store.py         SQLite index + content-addressed blobs: items, lineage, memo, runs,
                   flows (item x edge x run), events, usage, request cache, reviews;
                   buffered batch writes (one connection per store per process), result
                   queries (select_runs/query), lineage (roots/descendants/origin)
  imports.py       cross-graph edges: `imports:` + `alias:node.port` -> graph.import nodes
  graph.py         GraphSpec/NodeSpec (file format), load/save JSON/YAML/.py, Graph builder
  nodes/base.py    NodeType, Port, kinds, ResourceRef, hooks (resources, identity, cost_hint, ...)
  nodes/builtin.py generic node types (sources, expr label/map/filter/route, python escape
                   hatches, repeat, join.group/pair, llm.generate/label/synthesize,
                   review.manual, retry.loop, sink.jsonl)
  nodes/agentic.py sandbox.check, agent.run
  nodes/query.py   store.query (select earlier results), graph.import (cross-graph edge)
  expr.py          safe expressions + {{ templates }}
  check.py         static validation with codes/hints + budget estimate
  patch.py         schema-validated graph patch ops
  engine.py        executor: pipelined async, memoization, retries, budgets, run records
  scheduler.py     RateLimiter (rolling window, gate, priority), SlotPool, BudgetTracker
  project.py       project file: providers, model aliases, sandboxes, harnesses, budgets, secrets
  registry.py      the four plugin registries (+ entry points)
  models/          ModelProvider + ModelClient (cache/pacing/retries/accounting),
                   openai_compat (httpx + quirk adapters), fake, proxy (logging proxy)
  harness/         Harness/AgentTask/Trajectory, builtin_agent, cli, verifiers_adapter
  sandbox/         Sandbox/SandboxProvider (+ pooled lease lifecycle), local, docker
                   (+ egress allowlist proxy, ssh_docker, containers on host pools), fake
  hosts/           Host/HostProvider/Resources/Requirements (base), HostPool (placement,
                   autoscaling, setup, TTL, idle shutdown, budget, images, state), vmapi
                   (HTTP VM API base), static + fake providers
  contrib/boat.py  boat.dev VMs as a host provider (entry point `pipewright.hosts`)
  ops.py           every CLI operation as a plain function returning JSON
  cli.py           `pw`
  report.py        static HTML report
  mcp_server.py    MCP tools over ops.py

Key decisions

Items are immutable records with lineage

A node never mutates an item; it derives a new one whose parents name its inputs and whose producer/op name the node and node-type version (stamped by the engine). The id hashes key, kind, payload, labels, artifact hashes, parents, producer and provenance. Consequences:

  • identical work yields identical ids → memo hits propagate downstream;
  • lineage is a query (pw lineage), not bookkeeping;
  • provenance (real / derived / synthetic) is carried explicitly, so an export can always tell invented data from mined data.

Filters, routes and reviews pass the same item through (no derived copy), so routing does not create lineage noise.

Memoization per (node signature, input item)

The signature hashes the node type, its declared version, its params and the resolved identity of its resources (NodeType.identity, by default: which provider config, model and default params an alias resolves to; which image/network a sandbox pool uses). Changing an alias target invalidates exactly the nodes using it; changing rate limits, slots or secrets does not. Joins key on the sorted ids of all their inputs; cacheable sources (e.g. llm.synthesize) key on params + limit.

What is memoized: successful results and deterministic node errors. What is not: provider/infra failures (the next run retries them), budget-pending items, review decisions, sinks (rewritten every run — cheap, and they must reflect the current run).

LLM requests have a second cache keyed by (provider identity, payload, salt). The salt separates requests that must not share answers (the k rollouts of one task use the rollout item id), and --retry-errors bypasses cache reads so a recomputed error draws a fresh sample instead of replaying the bad one.

Every run records flows

Each run (including pure replays) records (run, node, port, item) for every emitted item, plus one event per (node, input) with status ok / error / pending / parked and whether it was cached. Funnels, pw items, sampling per edge and the HTML report are queries on those two tables. Replays are fast, so "the funnel of the current graph" is always one run away.

Pipelined async execution; concurrency from leases

Every node is an asyncio task with an inbox; every item is processed in its own task as soon as it arrives. Nothing limits concurrency except resource leases:

  • RateLimiter per provider: rolling 60 s window over requests, input tokens and (estimated, then settled) output tokens. Requests are recorded at admission, so rejected requests count against the window, matching providers that count them. A 429 closes a shared gate for Retry-After (or exponential backoff), so retries do not keep the window saturated and starve themselves. Waiters are served in priority order — deeper nodes first — so items reach the end of the pipeline.
  • SlotPool per sandbox pool: slots come from capacity (host CPUs / sandbox CPUs for Docker; docker info on remote hosts; an explicit number for VM APIs).
  • BudgetTracker per run: USD, input/output tokens, VM hours. When exhausted, no new work is admitted, in-flight work finishes, and the remaining items are recorded as pending (the run ends budget_exceeded; the next run resumes them).

There is no worker count to configure. This was a deliberate reaction to guessed concurrency caps that were always either too low (idle quota) or too high (429 storms).

Error classification is part of the contract

ProviderError (429/5xx/transport/in-band error/agent stopped on a failed model call) and InfraError (sandbox/harness) are transient: retried within the run per the node's retries policy (provider: 3, infra: 2, node: 0 by default) and never memoized. NodeError is a result. Harnesses must raise ProviderError when an agent "finished" only because its model failed — the CLI harness detects this through the logging proxy (session.failed_last_call), so it can never be graded as the model failing the task.

Quirks live in the provider layer

The OpenAI-compatible provider turns quirks into honest statuses before anything else sees them: an HTTP 200 stream whose first data event is {"error": ...} (possibly after : heartbeat comments) becomes a 429/5xx; a 200 JSON body with only error likewise. Quirk adapters are named functions, enabled per provider.

External agents go through a logging proxy

External agent CLIs never get the real URL or key. They get a proxy URL and a per-session token; the proxy runs each request through the same ModelClient as built-in nodes (pacing, quirks, retries, request cache, accounting), records every turn (conversation continuation by message-prefix matching, as in the original llm_logging_proxy), and answers streaming requests with a synthesized SSE stream. The same proxy is available standalone (pw proxy) for running an agent by hand.

Sandboxes: tiny interface, shared lifecycle

Sandbox = exec/read/write/expose/host_address/health; SandboxProvider = create/destroy/extend + capabilities. Leasing (slots, create, setup hook, health, reuse, destroy, drain, VM-hour/$ accounting) is implemented once in the base class, so a remote VM provider is ~50 lines. The Docker provider uses the CLI, which makes the SSH-host variant free (docker -H ssh://...). Its allowlist network mode puts the container on an --internal network (no route out) and runs an allowlisting HTTP CONNECT proxy on that network's gateway.

Loops are bounded and explicit

The graph is a DAG. In-run loops are the retry.loop node kind: a check node and a fix node with a hard max_rounds (≤ 20, validated), each inner step memoized per item. Feedback across runs (recalibrating a score from later results) reads earlier runs' outputs (source.prior_run, ctx.prior_items) instead of being a live cycle. pw check rejects cycles with a hint pointing at both.

Agent-friendly authoring

  • Graphs as typed Python (builder; Params models give completion and fail at the line that made the mistake) that round-trip to YAML/JSON.
  • pw nodes describe returns machine-readable docs including a working example (the test suite validates every example).
  • pw check diagnostics have stable codes, the node/port, and a hint (often a "did you mean"). Layers: plugins/project → node types → params (schema and semantic, e.g. expressions compile and only use known names) → wiring → port kinds (inferred along the DAG, with same pass-through) → resources → budget estimate.
  • pw patch applies schema-validated ops to an in-memory copy and writes only if the result checks clean.
  • Every command has --json; operations are plain functions (ops.py), and the MCP server is a thin layer over them.

Results are inputs: queries, imports, lineage across graphs

Because items are immutable and content-addressed, "build on earlier results" needs no new execution model: a source that emits stored items unchanged (same ids) makes all downstream memo entries valid again. store.query selects items by graph/node/port/run plus filters; a graph's imports: lets inputs name alias:node.port, and the engine expands each referenced alias:node into a virtual graph.import source before checking or running (the graph file keeps the reference, the funnel/report show the node as imported, with dashed edges). Upstream port kinds are inferred from the imported graph, so pw check type-checks cross-graph edges. Re-entrant loops are imports of self reading the previous run: feedback without live cycles, every step memoized. Imported items from another store are copied with ancestors and blobs, so lineage stays local. Items record the run that first stored them, so pw lineage can say which graph made each ancestor.

Host pools: resources, not slots

VM tests that each need 8 GB flaked when two shared a 16 GB host, so hosts have capacity (cpus, memory, disk minus a reserve) and sandboxes reserve what they declare. A request waits (priority order) until a ready host has the capabilities, required labels and free resources; among candidates it prefers locality labels (image:<ref> recorded when an image is ensured, volume:<name> for warm named volumes), then the tightest fit, so other hosts drain and can be deleted. Scaling simulates packing the waiting requests onto hosts already being created and starts only the missing ones, within max, the hours/$ budget, a creation backoff, and a hard create_limit per pool lifetime (a guard against runaway billing when setup keeps failing). Host time is accounted per host lifetime (creation to deletion), not per lease. Sandboxes stay Docker containers driven from the orchestrating machine with docker -H ssh://…; each host gets an SSH config (pinned host key, ControlMaster) and Docker's SSH helper is pointed at it with a per-host ssh wrapper on PATH. Agents in those containers reach the local logging proxy through Sandbox.reverse(port): one ssh -N -R tunnel per host (sshd binds it to the host's loopback) plus a tiny relay on the Docker bridge gateway, so CLI harnesses work unchanged on remote hosts. Host providers only create, delete and extend machines; everything else is shared. Hosts can persist across runs (persist: true; the next process adopts them after a health check) and pw hosts manages them between runs; every host event is appended to <store>/hosts/<pool>/events.jsonl, and the state file lets pw hosts down|orphans clean up after crashes.

Many workers on one store

The store buffers hot-path writes (items, lineage, flows, events, memo, usage, request cache) in memory and commits them with one executemany per statement inside a short BEGIN IMMEDIATE transaction (every 5000 rows or 0.5 s), so the write lock is held for milliseconds instead of while Python works. Readers in the same process share the connection (one per store path), memo/request-cache lookups consult in-memory overlays, and query-style reads flush first. Node memo entries are preloaded per signature at plan time, so replays do no per-item lookups. With this, --shard I/N workers scale on one SQLite file (4 workers: 2.6x on the benchmark); a store server remains on the roadmap for multi-machine sharding without a shared filesystem.

Shared rate limits and incremental sinks

rate: {shared: true} moves a provider's rolling window and 429 gate into a SQLite ledger (~/.cache/pipewright/rate/<key>.sqlite); admission checks the window and records the request in one BEGIN IMMEDIATE transaction, so rejected requests count for every process and a 429 in one closes the gate for all. Each process keeps its own priority queue and re-polls the ledger while waiting. sink.jsonl appends rows for new items only (a sidecar <path>.pwindex records written ids, the file size and a params hash; a mismatch triggers a full rewrite), so re-running a large graph does not rewrite its exports.

Counter budgets

Some budgets are counts, not dollars (e.g. "at most 60 rollouts of model X", when the provider reports no cost). budgets: {counters: {name: limit}} with ctx.count(name) in a node: over the limit only that call raises BudgetExceeded (the item is pending and resumes next run); other work continues.

What came from where

datatrove — taken: steps independent of the executor; completion state per unit of work so reruns skip completed work; a request cache for LLM calls; stats per step; rank/world-size style sharding of sources (--shard I/N, by key hash, so all items derived from one source item stay in one shard). Not taken: file-shard outputs per rank — shards share one store and a final unsharded replay writes the sinks.

NVIDIA DataDesigner — taken: model aliases configured per project (graphs never name a concrete model); dependency-aware labels (structured LLM labels whose schema is declared next to the prompt, validated with a repair re-ask); validators/judges as ordinary nodes; preview vs. create (pw preview = the same engine on n items up to a node); plugins. Not taken: the column-centric dataset model — pipewright's unit is an item flowing through a graph, because tasks fan out (k rollouts), fan in (pass rates) and route, which columns model poorly.

ComfyUI — taken: typed node graph with ports checked at load time; workflow as a JSON file with links on the consuming node; cache per node by input hash so only what changed re-executes; custom node packs via a registry; "run up to a node" (--upto). Not taken: the UI, and caching only the latest execution — pipewright memoizes every result persistently, per item.

Agent-authoring work — ComfyBench/ComfyAgent (LLMs author graphs better as code → the Python builder), n8n-MCP (node docs + layered validation tools → nodes describe and check), Dagster Components/dg (schema-backed YAML, dg check, example values → params schemas and tested examples), Spec Graph (schema-validated graph patches → pw patch).

Deliberately not in v0

  • Distributed execution without a shared filesystem (shards share one SQLite store).
  • A web UI (static HTML report only).
  • Streaming token-level responses to callers (batch pipelines do not need them).
  • DuckDB analytics (SQLite is stdlib; the index is plain SQL and can be attached).
  • Automatic schema inference for payloads (port kinds are names, not JSON schemas). See roadmap.md.