Files

403 lines
20 KiB
Markdown

# pipewright
A small, generic framework for **repeatable data pipelines that mix LLM calls, agents
and sandboxed execution**: fetch → label → filter → build → validate → probe with
models → audit → rewrite/synthesize → export.
A pipeline is a typed graph of nodes. Every item flowing through it is an immutable,
content-addressed record with lineage, every node result is memoized per item, and
every run records which items crossed which edge — so re-running only does new work,
a crash resumes where it stopped, and the funnel is a query instead of a script.
Provider rate limits, sandbox lifecycles, retries and budgets are handled once, in the
framework, instead of in every stage script.
Every node's outputs are reusable: a later graph (or a later run of the same graph)
selects earlier results by node/port, labels and lineage and builds new work on them,
with item ids preserved so nothing is recomputed. Sandboxes scale out onto pools of
remote hosts (VMs from an API, or your own servers) that are created, packed by
resources, extended and shut down automatically.
Nothing in the core is domain-specific. Domain logic comes as plugin packs: node
types, model providers, agent harnesses, sandbox providers and host providers.
```
pw check examples/coding_tasks/graph.py # types, wiring, resources, budget estimate
pw preview examples/coding_tasks/graph.py --upto validate -n 2
pw run examples/coding_tasks/graph.py # resumable; memoized results are reused
pw funnel examples/coding_tasks/graph.py # item counts per node and edge
pw report examples/coding_tasks/graph.py # static HTML: graph + counts + samples
```
## Install
```
uv sync # or: pip install -e .
uv sync --extra mcp # optional MCP server (`pw mcp`)
uv run pytest # unit + integration tests (fake model, local sandbox)
uv run pytest --docker # + Docker sandbox tests (incl. egress allowlist)
uv run pytest --live # + live tests (needs a provider key, see below)
```
Python ≥ 3.12. Core dependencies: pydantic, httpx, pyyaml. Docker sandboxes use the
`docker` CLI (no SDK).
## Concepts
**Item** — an immutable record: `key` (logical identity, e.g. `gh-101`,
`add/rollout1`), `kind` (the port type, e.g. `issue`, `task`), `payload`, `labels`,
`artifacts` (content-addressed blobs, e.g. a trajectory), `parents` + `producer`
(lineage), and `provenance` (`real` / `derived` / `synthetic`). Its `id` hashes all of
that, so identical work produces identical ids. Nodes never mutate items; they
`item.derive(...)` new ones.
**Graph** — a DAG of nodes. Each node has a **type** (registered behaviour, e.g.
`llm.label`), **params** (validated by a pydantic model) and **inputs** (`node` or
`node.port` references). Graphs are authored in Python (`pipewright.Graph`) or
YAML/JSON, and round-trip between them (`pw convert`).
**Node kinds** — a small fixed vocabulary for how items flow; domain behaviour comes
from node types, not new kinds:
| kind | shape | example types |
|---|---|---|
| source | () → items | `source.file`, `source.inline`, `store.query`, `source.prior_run`, `llm.synthesize` |
| map | 1 → 1 | `label.expr`, `map.expr`, `llm.label`, `llm.generate`, `sandbox.check`, `agent.run`, `python.map` |
| flatmap | 1 → n | `flatmap.repeat` (k rollouts), `python.flatmap` |
| filter | 1 → out \| rejected | `filter.expr`, `python.filter` |
| route | 1 → named ports | `route.expr` |
| join | all → items | `join.group` (with aggregates), `join.pair` |
| retry | bounded check → fix loop | `retry.loop` |
| review | park for a human | `review.manual` |
| sink | all → side effect | `sink.jsonl` (appends new items; `mode: rewrite` for a full rewrite) |
`pw nodes list` / `pw nodes describe <type>` document every type: ports and their
item kinds, the params JSON schema, the project resources it needs, cost hints and a
working example.
**Project** — `pipewright.yaml` next to (or above) the graph binds the *names* a graph
uses to concrete resources: model aliases → providers, sandbox pools, harnesses,
budgets. Swap the project file (`--project`) to run the same graph on a fake model in
tests and a real one in production.
**Memoization** — a node's result for an input item is stored under
(node type + version + params + resolved resource identity, input item id). Re-running
replays stored results and computes only what is new or changed; editing one node's
params recomputes that node, and downstream nodes only for items whose content actually
changed. LLM calls also go through a request cache keyed by payload hash. Transient
failures (provider, infra) are not memoized; deterministic node errors are (rerun them
with `--retry-errors`).
**Scheduling** — every item is processed as soon as it arrives (pipelined), limited
only by resource leases: provider request/token budgets per minute (rejected requests
count against the window; a 429 closes a shared gate for Retry-After), sandbox slots
derived from capacity, and USD / token / VM-hour budgets per run. There are no worker
counts to tune. Deeper nodes get priority so items finish instead of every stage being
half done.
**Errors** — every failure is classified: `provider` (429/5xx/transport, in-stream
errors, an agent whose last model call failed) and `infra` (sandbox/harness) are
retried and never recorded as results; `node` errors are deterministic results.
**Building on results** — any node's outputs can seed new work:
- `store.query` selects stored items by graph, node, port, run (`latest`, `all`,
`group:<g>`, a run id), kind, provenance, labels, an expression and lineage
(`derived_from`), from this store or another project's (copied with lineage and blobs).
- Cross-graph edges: a graph declares `imports` and uses `alias:node.port` as an input.
Each run reads that port's items from the upstream graph's latest run; since item ids
are kept, items handled before stay memoized and only new upstream items cost work.
- Re-entrant loops across runs: `imports: {prev: {graph: self}}` reads this graph's
previous run (e.g. audited failures of run N become generator seeds in run N+1) —
no live cycle, every step memoized.
- Lineage spans graphs that share a store: `pw lineage ITEM --roots` (the root source
of a variant), `--descendants` (every variant derived from an item), each entry with
the graph and run that made it. `pw query` shows what a `store.query` would select.
```python
g = Graph("harden")
build = g.import_graph("build", "graph_build.py") # another graph, by reference
task = g.add("task", "map.expr", input=build.node("bucket").port("too_easy"), kind="task", fields={...})
```
**Host pools** — `hosts:` in the project file defines pools of machines (a host
provider: `boat` VMs, `static` SSH hosts, or a plugin) with capacity (cpus, memory,
disk), capabilities (kvm, gpu), labels, a setup hook, `min`/`max`, `idle_shutdown`,
TTL extension and an hours/$ budget. A Docker sandbox pool with `hosts: <pool>` runs
each sandbox as a container on a pool host (`docker -H ssh://…` from this machine, so
nothing is synced to hosts). Placement reserves the sandbox's `cpus`/`memory` on a host
that has the required capabilities and labels, preferring hosts that already have the
image or warm volume, then the tightest fit; when nothing fits the pool creates hosts
(within `max` and budget), and idle hosts are deleted. Capacity is resources, not slots:
two 8 GB tasks never share a 16 GB host. Images are ensured per host (`image_source:
{build: dir | load: tar | pull: ref}`) and recorded as `image:<ref>` labels.
```yaml
hosts:
boat:
type: boat # pipewright.contrib.boat (optional extra)
api_key: {file: ~/.config/deepswe-eval/secrets, var: BOAT_API_KEY}
max: 4
idle_shutdown: 300
reserve: {cpus: 0.5, memory: 1g}
docker_kvm_runtime: true # every container gets /dev/kvm (mode 0666)
budget: {hours: 4}
sandboxes:
vmtest: {type: docker, hosts: boat, image: nix-base:dev, image_source: {build: ./image},
cpus: 4, memory: 7g, requires: {kvm: true}}
```
**Scaling out** — `pw run --shard I/N --group G` processes only the source items whose
key hashes to I (mod N); several processes or machines share one store (writes are
buffered and committed in short batches, so the SQLite write lock is held for
milliseconds). Sinks are skipped in shard runs; a final `pw run` without `--shard`
replays everything from memo and writes them. `pw funnel --group G` sums the shards.
Provider rate limits can be shared by every process on a machine (`rate: {shared:
true}`), so concurrent runs pace jointly against one key's budget.
## Quickstart
```python
# graph.py
from pipewright import Graph
g = Graph("triage")
issues = g.add("issues", "source.file", path="data/issues.jsonl", kind="issue")
heur = g.add("heur", "label.expr", input=issues,
labels={"has_traceback": "re(r'traceback', payload.body)", "words": "words(payload.body)"})
keep = g.add("keep", "filter.expr", input=heur, expr="labels.words >= 8")
cls = g.add("classify", "llm.label", input=keep, model="labeler",
prompt="Classify:\n\n{{ payload.title }}\n\n{{ payload.body }}",
labels={"category": {"type": "string", "enum": ["bug", "feature", "question"]},
"severity": {"type": "integer", "minimum": 0, "maximum": 3}})
route = g.add("route", "route.expr", input=cls, routes={"urgent": "labels.severity >= 2"}, default="rest")
g.add("export", "sink.jsonl", input=route.port("urgent"), path="out/urgent.jsonl")
graph = g
```
```yaml
# pipewright.yaml
providers:
fake: {type: fake} # deterministic, schema-conforming answers
morph:
type: openai
base_url: https://api.morphllm.com/v1
api_key: {env: MORPH_SK, file: ~/.tmp, var: MORPH_SK}
rate: {requests_per_minute: 200, input_tokens_per_minute: 500000, output_tokens_per_minute: 20000}
models:
labeler: {provider: fake, model: fake} # switch to {provider: morph, model: morph-dsv41flash-1017}
budgets: {usd: 5, counters: {rollouts.solver: 60}} # counters: spent by nodes via ctx.count(name)
```
```
pw check graph.py && pw preview graph.py --upto classify -n 3 && pw run graph.py && pw funnel graph.py
```
Typed authoring: instead of a type string you can pass the node's Params model,
which gives IDE completion and immediate validation:
`g.add("keep", FilterExpr.Params(expr="labels.words >= 8"), input=heur)`.
Expressions (`label.expr`, `filter.expr`, `route.expr`, `map.expr`, `join.group`) and
`{{ templates }}` use a safe, whitelisted Python subset over `payload`, `labels`, `key`,
`kind`, with helpers such as `re`, `re_count`, `re_find`, `words`, `mean`, `json`.
Missing keys read as `None`.
## Examples (run end to end; also the integration tests)
- `examples/issue_triage` — read GitHub-style issues → heuristic labels → filter →
structured LLM labels → route → export. `pipewright.yaml` uses the fake model;
`pipewright.live.yaml` uses DeepSeek via Morph.
- `examples/hardening` — two graphs on one store. `graph_build.py` synthesizes coding
tasks, validates them in sandboxes, probes them with an agent (k=2) and buckets them
by pass rate; `graph_harden.py` imports build's `bucket.too_easy`, asks an LLM for a
harder variant of each, and validates + probes the variants again. Re-running harden
after build found more too-easy tasks processes only the new ones.
`pipewright.boat.yaml` runs the same graphs with sandboxes on boat.dev VMs
(`live_boat.py` is the live end-to-end: 2 VMs, /dev/kvm in containers, idle
scale-down, cleanup).
- `examples/coding_tasks` — synthesize small coding tasks with an LLM → validate each
in sandboxes (reference solution passes, empty stub fails) → probe with the built-in
agent at k=2 → group rollouts → route by pass rate (too_easy / learnable / too_hard).
`pipewright.yaml`: fake model + local sandbox; `pipewright.docker.yaml`: Docker with
no network; `pipewright.live.yaml`: Morph + Docker.
## CLI
All commands accept `--json` and `--project FILE`.
| command | |
|---|---|
| `pw nodes list` / `pw nodes describe TYPE` | node docs: ports, params schema, resources, cost hints, example |
| `pw check GRAPH` | errors/warnings with codes and hints; budget estimate; exit 1 on errors |
| `pw patch GRAPH OPS` | apply JSON ops (`add_node`, `remove_node`, `rename_node`, `connect`, `disconnect`, `set_param`, `set_node`); written only if the result checks clean. `--dry-run`, `--force`, `--schema` |
| `pw preview GRAPH --upto NODE -n 5` | run the first n source items up to a node, show its output |
| `pw run GRAPH [--upto N] [--limit N] [--force NODE] [--retry-errors]` | run/resume |
| `pw status GRAPH` | latest run: per-node in/ok/cached/errors/running/pending/parked, usage, budget |
| `pw funnel GRAPH` | counts per node, port and edge |
| `pw items GRAPH NODE [--port P] [-n 5] [--sample] [--errors] [--full]` | inspect items / failures |
| `pw run GRAPH --shard I/N --group G` | one worker's share of the source items (several workers, one store) |
| `pw funnel GRAPH --group G` | funnel summed over a run group (e.g. all shards) |
| `pw lineage GRAPH ITEM [--roots] [--descendants]` | an item (id, prefix or key) and its ancestors across graphs; root sources; all variants derived from it |
| `pw query GRAPH [--of NAME] [--node N --port P] [--run latest\|all\|ID] [--where EXPR] [--label k=v] [--derived-from ITEM]` | select stored results; prints the equivalent `store.query` node |
| `pw hosts list\|up\|down\|orphans [--pool P] [--count N]` | host pools outside a run: list, pre-create (kept for later runs with `persist: true`), delete, clean up unrecorded provider hosts |
| `pw export GRAPH NODE -o out.jsonl [--fields a,b]` | export a node's output |
| `pw report GRAPH [--watch S]` | static HTML report with per-edge counts and drill-down samples |
| `pw review GRAPH NODE [--approve ID… \| --reject ID…]` | human review queue |
| `pw convert GRAPH.py GRAPH.yaml` | builder → file (and between JSON/YAML) |
| `pw proxy --model ALIAS --log-dir DIR` | standalone logging proxy for running an agent by hand |
| `pw mcp` | the same operations as MCP tools (stdio) |
## Writing plugins
All five registries work the same way: register in-process (decorator/function), or
ship a distribution with an entry point in the matching group (`pipewright.nodes`,
`pipewright.providers`, `pipewright.harnesses`, `pipewright.sandboxes`,
`pipewright.hosts`), or list local modules under `plugins:` in the project or graph file.
```toml
[project.entry-points."pipewright.nodes"]
mypack = "mypack.nodes" # importing the module registers its node types
```
### Node types
```python
from pydantic import BaseModel
from pipewright import NodeType, Port, ResourceRef, register_node
class DedupParams(BaseModel):
field: str = "title"
@register_node
class NearDup(NodeType):
"""Label items whose `field` was seen in an earlier run (cross-run feedback)."""
name = "mypack.near_dup"
kind = "map"
version = "1" # bump when behaviour changes -> memo invalidated
Params = DedupParams
inputs = {"in": Port(kind="issue")}
outputs = {"out": Port(kind="same")}
example = {"field": "title"}
async def process(self, item, ctx):
seen = {i.payload.get(self.params.field) for i in ctx.prior_items("triage", "classify")}
return item.derive(update_labels={"seen_before": item.payload.get(self.params.field) in seen})
```
`ctx` gives `ctx.model(alias)` (paced, cached, accounted chat client),
`async with ctx.sandbox(pool) as sb`, `ctx.harness(name)`, `ctx.put_blob(...)`,
`ctx.prior_items(graph, node, port)`, `ctx.log(...)`. Declare `resources()` so
`pw check` verifies aliases/pools exist and memo keys include what they resolve to;
`cost_hint()` feeds budget estimates; `validate_params()` adds semantic checks.
### Model providers
The built-in `openai` type covers OpenAI-compatible APIs. A provider only implements
`complete(payload) -> chat.completion dict` and raises `ProviderError(status=...)`;
retries, pacing, caching and accounting are layered on top.
```python
from pipewright import register_provider, ProviderError
from pipewright.models.base import ModelProvider
class MyAPI(ModelProvider):
type = "myapi"
async def complete(self, payload):
resp = await my_call(payload) # translate to/from your API
if resp.overloaded:
raise ProviderError("overloaded", status=429, retry_after=resp.retry_after)
return {"choices": [{"index": 0, "message": {"role": "assistant", "content": resp.text}}],
"usage": {"prompt_tokens": resp.n_in, "completion_tokens": resp.n_out, "cost": resp.usd}}
register_provider("myapi", MyAPI)
```
Quirk adapters for misbehaving OpenAI-compatible providers are small functions
(`pipewright.models.openai_compat.register_quirk`); `stream_error_event` (HTTP 200
stream whose first data event is an error, after heartbeat comments → real 429/5xx) and
`body_error` are on by default. Secrets are references (`{env: VAR}` or
`{file: path, var: KEY}`), resolved at call time, never stored or logged; a literal key
in the config is rejected.
### Agent harnesses
```python
from pipewright import register_harness
from pipewright.harness.base import Harness, Trajectory
class MyAgent(Harness):
type = "myagent"
async def run(self, task, sandbox, ctx):
client = ctx.model(self.config["model"]) # or: proxy = await ctx.proxy() for CLI agents
...
return Trajectory(harness=self.name, status="completed", messages=msgs, turns=n)
register_harness("myagent", MyAgent)
```
Contract: return a Trajectory for anything that is a *result* (completed, gave up, ran
out of turns/time); raise `ProviderError` when the agent stopped because a model call
failed, `InfraError` when the sandbox/harness broke. Shipped: `builtin` (minimal
bash/read/write/finish tool-calling agent), `cli` (runs an external agent CLI in the
sandbox, routed through the logging proxy so every turn is recorded, and raising
ProviderError if its last model call failed), `verifiers` (experimental adapter for
prime-intellect verifiers v1 harnesses).
### Sandbox / host providers
```python
from pipewright import register_sandbox
from pipewright.sandbox.base import Sandbox, SandboxProvider, ExecResult, Capabilities
class MyVMs(SandboxProvider):
type = "myvms"
capabilities = Capabilities(kvm=True, remote=True)
async def create(self) -> Sandbox: ... # boot a VM, return a Sandbox with exec/read/write
async def destroy(self, sandbox): ...
async def extend(self, sandbox, seconds): ... # optional (TTL-based VMs)
register_sandbox("myvms", MyVMs)
```
The base class provides the pooled lifecycle for every provider: slots, create, the
pool's `setup` commands, health checks, optional reuse of healthy sandboxes
(`reuse: true`), destroy on release, `drain()` at the end of a run, and VM-hour / $
accounting (`cost_per_hour`). Shipped: `local` (temp dir on the host, no isolation),
`docker` (fresh container per lease; `network: none | bridge | allowlist`, where
`allowlist` uses an internal Docker network plus an allowlisting CONNECT proxy),
`ssh_docker` (the same against a remote Docker daemon, `host: ssh://user@host`), and
`fake` (in-memory, for tests). Docker pools with `hosts: <pool>` place containers on a
host pool (see Host providers below).
### Host providers
A host provider makes machines; the pool (`pipewright.hosts.HostPool`) does setup,
health, placement, scaling, TTL extension, images and accounting.
```python
from pipewright import register_host_provider
from pipewright.hosts import Host, HostProvider
class MyCloud(HostProvider):
type = "mycloud"
default_capacity = {"cpus": 16, "memory": "64g"}
async def create(self, host_id, state_dir) -> Host:
vm = await my_api.create(name=host_id) # boot, register an SSH key
return Host(id=host_id, pool=self.name, docker_host=f"ssh://ubuntu@{vm.ip}")
async def delete(self, host): await my_api.delete(host.meta["vm_id"])
async def extend(self, host, seconds): ... # optional (TTL-based VMs)
register_host_provider("mycloud", MyCloud)
```
`pipewright.hosts.vmapi.VMApiHostProvider` handles the common HTTP-VM-API parts (secret
ref, retries, per-host SSH config with a pinned host key and ControlMaster);
`pipewright.contrib.boat` is a complete example (~150 lines).
## Docs
- `docs/design.md` — architecture and decisions (what came from datatrove, DataDesigner,
ComfyUI, and what was left out)
- `docs/agents.md` — how an agent should author and debug a pipeline with the CLI
- `docs/roadmap.md` — deferred work and known gaps
- `docs/changes-for-plugins.md` — interface changes for plugin packs (host pools, imports, store)