From a2768caf198a009f1d85c10ec05ee3bdd4b3987b Mon Sep 17 00:00:00 2001 From: Carsten Kragelund Date: Sat, 14 Nov 2026 07:49:19 +0000 Subject: [PATCH] pipewright: graph-based data/task pipeline framework --- .gitignore | 10 + README.md | 402 +++ bench/bench_pipeline.py | 103 + bench/bench_shards.py | 66 + docs/agents.md | 158 + docs/changes-for-plugins.md | 106 + docs/design.md | 268 ++ docs/roadmap.md | 74 + examples/coding_tasks/fakes.py | 57 + examples/coding_tasks/graph.py | 65 + examples/coding_tasks/graph.yaml | 162 + examples/coding_tasks/pipewright.docker.yaml | 12 + examples/coding_tasks/pipewright.live.yaml | 16 + examples/coding_tasks/pipewright.yaml | 14 + examples/hardening/common.py | 34 + examples/hardening/graph_build.py | 26 + examples/hardening/graph_harden.py | 33 + examples/hardening/hardening_fakes.py | 74 + examples/hardening/live_boat.py | 93 + examples/hardening/live_tunnel.py | 59 + examples/hardening/pipewright.boat.yaml | 35 + examples/hardening/pipewright.yaml | 12 + examples/issue_triage/data/issues.jsonl | 12 + examples/issue_triage/graph.py | 47 + examples/issue_triage/graph.yaml | 102 + examples/issue_triage/pipewright.live.yaml | 18 + examples/issue_triage/pipewright.yaml | 12 + pyproject.toml | 45 + src/pipewright/__init__.py | 24 + src/pipewright/check.py | 228 ++ src/pipewright/cli.py | 462 +++ src/pipewright/contrib/__init__.py | 1 + src/pipewright/contrib/boat.py | 136 + src/pipewright/engine.py | 645 ++++ src/pipewright/errors.py | 107 + src/pipewright/expr.py | 232 ++ src/pipewright/graph.py | 346 ++ src/pipewright/harness/__init__.py | 5 + src/pipewright/harness/base.py | 88 + src/pipewright/harness/builtin_agent.py | 126 + src/pipewright/harness/cli.py | 100 + src/pipewright/harness/verifiers_adapter.py | 102 + src/pipewright/hashing.py | 32 + src/pipewright/hosts/__init__.py | 6 + src/pipewright/hosts/base.py | 250 ++ src/pipewright/hosts/pool.py | 793 +++++ src/pipewright/hosts/static.py | 101 + src/pipewright/hosts/vmapi.py | 126 + src/pipewright/imports.py | 161 + src/pipewright/items.py | 128 + src/pipewright/mcp_server.py | 152 + src/pipewright/models/__init__.py | 5 + src/pipewright/models/base.py | 240 ++ src/pipewright/models/fake.py | 144 + src/pipewright/models/openai_compat.py | 209 ++ src/pipewright/models/proxy.py | 239 ++ src/pipewright/nodes/__init__.py | 1 + src/pipewright/nodes/agentic.py | 212 ++ src/pipewright/nodes/base.py | 170 + src/pipewright/nodes/builtin.py | 929 ++++++ src/pipewright/nodes/query.py | 150 + src/pipewright/ops.py | 503 +++ src/pipewright/patch.py | 185 ++ src/pipewright/project.py | 315 ++ src/pipewright/registry.py | 176 ++ src/pipewright/report.py | 143 + src/pipewright/sandbox/__init__.py | 5 + src/pipewright/sandbox/base.py | 218 ++ src/pipewright/sandbox/docker.py | 421 +++ src/pipewright/sandbox/fake.py | 77 + src/pipewright/sandbox/local.py | 97 + src/pipewright/scheduler.py | 423 +++ src/pipewright/store.py | 616 ++++ tests/conftest.py | 53 + tests/fake_docker.py | 77 + tests/fake_scripts.py | 10 + tests/test_cli.py | 56 + tests/test_engine.py | 225 ++ tests/test_examples.py | 64 + tests/test_expr.py | 45 + tests/test_graph_check_patch.py | 129 + tests/test_harness.py | 105 + tests/test_hosts.py | 217 ++ tests/test_imports.py | 135 + tests/test_items_store.py | 41 + tests/test_live.py | 58 + tests/test_mcp.py | 24 + tests/test_models.py | 104 + tests/test_plugins.py | 85 + tests/test_proxy.py | 59 + tests/test_sandbox.py | 118 + tests/test_scheduler.py | 112 + tests/test_shards.py | 36 + tests/test_shared_rate.py | 115 + tests/test_sink_append.py | 101 + uv.lock | 2966 ++++++++++++++++++ 96 files changed, 16879 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 bench/bench_pipeline.py create mode 100644 bench/bench_shards.py create mode 100644 docs/agents.md create mode 100644 docs/changes-for-plugins.md create mode 100644 docs/design.md create mode 100644 docs/roadmap.md create mode 100644 examples/coding_tasks/fakes.py create mode 100644 examples/coding_tasks/graph.py create mode 100644 examples/coding_tasks/graph.yaml create mode 100644 examples/coding_tasks/pipewright.docker.yaml create mode 100644 examples/coding_tasks/pipewright.live.yaml create mode 100644 examples/coding_tasks/pipewright.yaml create mode 100644 examples/hardening/common.py create mode 100644 examples/hardening/graph_build.py create mode 100644 examples/hardening/graph_harden.py create mode 100644 examples/hardening/hardening_fakes.py create mode 100644 examples/hardening/live_boat.py create mode 100644 examples/hardening/live_tunnel.py create mode 100644 examples/hardening/pipewright.boat.yaml create mode 100644 examples/hardening/pipewright.yaml create mode 100644 examples/issue_triage/data/issues.jsonl create mode 100644 examples/issue_triage/graph.py create mode 100644 examples/issue_triage/graph.yaml create mode 100644 examples/issue_triage/pipewright.live.yaml create mode 100644 examples/issue_triage/pipewright.yaml create mode 100644 pyproject.toml create mode 100644 src/pipewright/__init__.py create mode 100644 src/pipewright/check.py create mode 100644 src/pipewright/cli.py create mode 100644 src/pipewright/contrib/__init__.py create mode 100644 src/pipewright/contrib/boat.py create mode 100644 src/pipewright/engine.py create mode 100644 src/pipewright/errors.py create mode 100644 src/pipewright/expr.py create mode 100644 src/pipewright/graph.py create mode 100644 src/pipewright/harness/__init__.py create mode 100644 src/pipewright/harness/base.py create mode 100644 src/pipewright/harness/builtin_agent.py create mode 100644 src/pipewright/harness/cli.py create mode 100644 src/pipewright/harness/verifiers_adapter.py create mode 100644 src/pipewright/hashing.py create mode 100644 src/pipewright/hosts/__init__.py create mode 100644 src/pipewright/hosts/base.py create mode 100644 src/pipewright/hosts/pool.py create mode 100644 src/pipewright/hosts/static.py create mode 100644 src/pipewright/hosts/vmapi.py create mode 100644 src/pipewright/imports.py create mode 100644 src/pipewright/items.py create mode 100644 src/pipewright/mcp_server.py create mode 100644 src/pipewright/models/__init__.py create mode 100644 src/pipewright/models/base.py create mode 100644 src/pipewright/models/fake.py create mode 100644 src/pipewright/models/openai_compat.py create mode 100644 src/pipewright/models/proxy.py create mode 100644 src/pipewright/nodes/__init__.py create mode 100644 src/pipewright/nodes/agentic.py create mode 100644 src/pipewright/nodes/base.py create mode 100644 src/pipewright/nodes/builtin.py create mode 100644 src/pipewright/nodes/query.py create mode 100644 src/pipewright/ops.py create mode 100644 src/pipewright/patch.py create mode 100644 src/pipewright/project.py create mode 100644 src/pipewright/registry.py create mode 100644 src/pipewright/report.py create mode 100644 src/pipewright/sandbox/__init__.py create mode 100644 src/pipewright/sandbox/base.py create mode 100644 src/pipewright/sandbox/docker.py create mode 100644 src/pipewright/sandbox/fake.py create mode 100644 src/pipewright/sandbox/local.py create mode 100644 src/pipewright/scheduler.py create mode 100644 src/pipewright/store.py create mode 100644 tests/conftest.py create mode 100755 tests/fake_docker.py create mode 100644 tests/fake_scripts.py create mode 100644 tests/test_cli.py create mode 100644 tests/test_engine.py create mode 100644 tests/test_examples.py create mode 100644 tests/test_expr.py create mode 100644 tests/test_graph_check_patch.py create mode 100644 tests/test_harness.py create mode 100644 tests/test_hosts.py create mode 100644 tests/test_imports.py create mode 100644 tests/test_items_store.py create mode 100644 tests/test_live.py create mode 100644 tests/test_mcp.py create mode 100644 tests/test_models.py create mode 100644 tests/test_plugins.py create mode 100644 tests/test_proxy.py create mode 100644 tests/test_sandbox.py create mode 100644 tests/test_scheduler.py create mode 100644 tests/test_shards.py create mode 100644 tests/test_shared_rate.py create mode 100644 tests/test_sink_append.py create mode 100644 uv.lock diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..59f62a0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.pyc +.venv/ +.pipewright*/ +*.egg-info/ +dist/ +build/ +.pytest_cache/ +examples/*/out/ +*.pwindex diff --git a/README.md b/README.md new file mode 100644 index 0000000..d48470e --- /dev/null +++ b/README.md @@ -0,0 +1,402 @@ +# 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 ` 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:`, 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: ` 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:` 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: ` 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) diff --git a/bench/bench_pipeline.py b/bench/bench_pipeline.py new file mode 100644 index 0000000..6399f85 --- /dev/null +++ b/bench/bench_pipeline.py @@ -0,0 +1,103 @@ +"""Scheduler/store benchmark: a fake pipeline over N items (fake model + fake sandbox). + + uv run python bench/bench_pipeline.py [-n 10000] [--profile] + +Reports wall time and items/s for a cold run and a fully memoized replay, plus the +number of node executions, so per-execution overhead (scheduler + store) is visible. +""" + +from __future__ import annotations + +import argparse +import cProfile +import json +import pstats +import tempfile +import time +from pathlib import Path + +import yaml + + +def build(n: int, root: Path) -> Path: + data = root / "data.jsonl" + with data.open("w") as f: + for i in range(n): + f.write(json.dumps({"id": f"it{i}", "title": f"item {i}", "body": "word " * (i % 17 + 3), + "group": f"g{i // 2}"}) + "\n") + (root / "pipewright.yaml").write_text(yaml.safe_dump({ + "store": ".pipewright", + "providers": {"fake": {"type": "fake"}}, + "models": {"m": {"provider": "fake", "model": "fake-m"}}, + "sandboxes": {"sb": {"type": "fake", "slots": 64, "rules": [{"match": "fail", "exit_code": 1}]}}, + })) + (root / "graph.yaml").write_text(yaml.safe_dump({ + "name": "bench", + "nodes": { + "src": {"type": "source.file", "params": {"path": "data.jsonl", "kind": "rec"}}, + "heur": {"type": "label.expr", "inputs": {"in": "src"}, + "params": {"labels": {"words": "words(payload.body)"}}}, + "keep": {"type": "filter.expr", "inputs": {"in": "heur"}, "params": {"expr": "labels.words >= 4"}}, + "cls": {"type": "llm.label", "inputs": {"in": "keep"}, + "params": {"model": "m", "prompt": "Classify {{ payload.title }}", + "labels": {"cat": {"type": "string", "enum": ["a", "b"]}}}}, + "check": {"type": "sandbox.check", "inputs": {"in": "cls"}, + "params": {"pool": "sb", "checks": [{"name": "ok", "command": "true"}]}}, + "rep": {"type": "flatmap.repeat", "inputs": {"in": "check"}, "params": {"k": 2}}, + "score": {"type": "label.expr", "inputs": {"in": "rep"}, + "params": {"labels": {"passed": "len(key) % 2 == 0"}}}, + "group": {"type": "join.group", "inputs": {"in": "score"}, + "params": {"by": "labels.group", "aggregates": {"rate": ["mean", "labels.passed"]}, + "keep_members": False}}, + "route": {"type": "route.expr", "inputs": {"in": "group"}, + "params": {"routes": {"hi": "labels.rate >= 0.5"}, "default": "lo"}}, + "sink": {"type": "sink.jsonl", "inputs": {"in": "route.hi"}, "params": {"path": "out/hi.jsonl", + "fields": ["key"]}}, + }}, sort_keys=False)) + return root / "graph.yaml" + + +def run(graph: Path) -> tuple[float, dict]: + from pipewright import ops + + t = time.perf_counter() + res = ops.run_graph(graph) + dt = time.perf_counter() - t + return dt, res + + +def executions(res: dict) -> int: + return sum(sum(v for k, v in n["events"].items() if k in ("ok",) or k.startswith("error")) + for n in res["funnel"]["nodes"].values()) + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("-n", type=int, default=10000) + ap.add_argument("--profile", action="store_true") + ap.add_argument("--dir") + a = ap.parse_args() + root = Path(a.dir or tempfile.mkdtemp(prefix="pw-bench-")) + root.mkdir(parents=True, exist_ok=True) + graph = build(a.n, root) + prof = cProfile.Profile() if a.profile else None + if prof: + prof.enable() + cold, res = run(graph) + if prof: + prof.disable() + ex = executions(res) + warm, res2 = run(graph) + out = {"items": a.n, "node_executions": ex, "status": res["status"], + "cold_s": round(cold, 2), "cold_items_per_s": round(a.n / cold, 1), + "cold_us_per_execution": round(cold / ex * 1e6, 1), + "replay_s": round(warm, 2), "replay_items_per_s": round(a.n / warm, 1), + "replay_us_per_execution": round(warm / max(1, executions(res2)) * 1e6, 1), + "store_mb": round(sum(p.stat().st_size for p in (root / ".pipewright").glob("index.sqlite*")) / 1e6, 1)} + print(json.dumps(out, indent=2)) + if prof: + pstats.Stats(prof).sort_stats("cumulative").print_stats(35) + + +if __name__ == "__main__": + main() diff --git a/bench/bench_shards.py b/bench/bench_shards.py new file mode 100644 index 0000000..e33244a --- /dev/null +++ b/bench/bench_shards.py @@ -0,0 +1,66 @@ +"""Several worker processes on one store: `pw run --shard I/N` in parallel, then one +unsharded replay that writes the sinks. Compares with a single process. + + uv run python bench/bench_shards.py [-n 4000] [-w 4] +""" + +import argparse +import json +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from bench_pipeline import build # noqa: E402 + + +def pw(*args, cwd): + return subprocess.Popen([sys.executable, "-m", "pipewright.cli", *args], cwd=cwd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("-n", type=int, default=4000) + ap.add_argument("-w", type=int, default=4) + a = ap.parse_args() + single = Path(tempfile.mkdtemp(prefix="pw-single-")) + g1 = build(a.n, single) + t = time.perf_counter() + p = pw("run", str(g1), "--quiet", "--json", cwd=single) + out, err = p.communicate() + t_single = time.perf_counter() - t + assert p.returncode == 0, err[-2000:] + + multi = Path(tempfile.mkdtemp(prefix="pw-shards-")) + g = build(a.n, multi) + t = time.perf_counter() + procs = [pw("run", str(g), "--quiet", "--json", "--shard", f"{i}/{a.w}", "--group", "bench", cwd=multi) + for i in range(a.w)] + results = [pr.communicate() for pr in procs] + t_shards = time.perf_counter() - t + for (o, e), pr in zip(results, procs): + assert pr.returncode == 0, e[-2000:] + statuses = [json.loads(o)["status"] for o, _ in results] + t = time.perf_counter() + p = pw("run", str(g), "--quiet", "--json", cwd=multi) + out2, err2 = p.communicate() + t_final = time.perf_counter() - t + final = json.loads(out2) + f = subprocess.run([sys.executable, "-m", "pipewright.cli", "funnel", str(g), "--group", "bench", "--json"], + cwd=multi, capture_output=True, text=True) + grp = json.loads(f.stdout) + print(json.dumps({ + "items": a.n, "workers": a.w, "single_process_s": round(t_single, 2), + "shards_wall_s": round(t_shards, 2), "shard_statuses": statuses, + "final_replay_s": round(t_final, 2), "final_status": final["status"], + "speedup_work": round(t_single / t_shards, 2), + "group_funnel_keep_ok": grp["nodes"]["keep"]["events"].get("ok"), + "final_sink_rows": final["funnel"]["nodes"]["route"]["out"], + }, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..87ae2c8 --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,158 @@ +# Authoring and debugging pipelines as an agent + +pipewright is designed to be driven by a coding agent through the CLI (or the same +operations over MCP: `pw mcp`). Use `--json` on every command; outputs are stable +objects. Exit codes: 0 ok, 1 check/patch errors or a failed run, 2 usage/config error +(with `{"error": ...}` in JSON mode). + +## 1. Learn the vocabulary + +``` +pw nodes list --json # [{type, kind, summary}] +pw nodes describe llm.label --json # inputs/outputs (+ item kinds), params_schema, + # resources, cost_hint, example, example_yaml, example_python +pw patch --schema # JSON schema of graph patch ops +``` + +Prefer starting from a node's `example` and changing values, not writing params from +scratch. Kinds you will meet: source, map, flatmap, filter (`out`/`rejected`), route +(one port per route + default), join, retry, review (`approved`/`rejected`), sink. + +## 2. Write the graph + +Write Python with the builder (best for larger graphs) or YAML (best for patching). +Reference upstream outputs as `node` (= `node.out`) or `node.port`. + +```python +from pipewright import Graph +g = Graph("my-pipeline") +src = g.add("records", "source.file", path="data/records.jsonl", kind="record") +lab = g.add("labels", "label.expr", input=src, labels={"long": "len(payload.text) > 500"}) +g.add("export", "sink.jsonl", input=lab, path="out/labelled.jsonl") +graph = g +``` + +`pw convert graph.py graph.yaml` writes the file form. Model, sandbox and harness +names (`model: labeler`, `pool: docker`, `harness: mini`) must exist in the project +file (`pipewright.yaml` at or above the graph). For development point aliases at the +`fake` provider: it returns schema-conforming JSON for structured requests, supports +regex `rules`, scripted responses (`script: module:function`) and injected failures. + +## 3. Check until clean + +``` +pw check graph.yaml --json +``` + +Each diagnostic: `{level, code, node, port, message, hint}`. Fix all `error`s. Codes: + +| code | meaning | usual fix | +|---|---|---| +| PW000 | invalid node id | no `.` in ids | +| PW001 | unknown node type | use the `hint` (closest match) or `pw nodes list` | +| PW002 | invalid params (schema or semantic: expressions, templates, inner node types) | compare with `pw nodes describe` | +| PW003 | input refers to an unknown node | fix the reference | +| PW004 | unknown output port on the upstream node | ports are in the hint | +| PW005 | unknown input port / inputs on a source | | +| PW006 | required input not connected | | +| PW007 | item kind mismatch on an edge | connect another port or add a converting `map.expr` (`kind:`) | +| PW008 | cycle | use `retry.loop` (bounded) or `source.prior_run` (across runs) | +| PW009 | unconnected outputs (warning/info) | add a sink, or ignore while debugging | +| PW011 | missing model alias / sandbox pool / harness | add it to pipewright.yaml or fix the name | +| PW012 | project problem (unknown provider type, secret unavailable) | | +| PW014 | budget estimate (info) / estimate exceeds budget (warning) | preview first, or raise budgets | +| PW016 | plugin module failed to import | | + +Expressions are Python syntax over `payload`, `labels`, `key`, `kind`, `id`, `item`; +dict keys read as attributes and missing keys are `None`. Helpers: `re`, `re_count`, +`re_find`, `words`, `lines`, `mean`, `median`, `get`, `coalesce`, `json`, `len`, +`min`, `max`, `sum`, `any`, `all`, `sorted`. Templates: `{{ expr }}`. + +## 4. Edit with patches + +``` +pw patch graph.yaml '[{"op": "add_node", "id": "summ", "type": "llm.generate", + "inputs": {"in": "labels"}, "params": {"model": "labeler", "prompt": "Summarize: {{ payload.text }}", + "output_field": "summary"}}, {"op": "connect", "from": "summ", "to": "export.in"}, + {"op": "disconnect", "from": "labels", "to": "export.in"}]' --json +``` + +The file is written only if the patched graph has no errors (`written: true`); +otherwise you get the diagnostics and the file is untouched. `--dry-run` returns the +patched graph without writing. Ops: `add_node`, `remove_node` (`rewire: true` connects +its inputs to its consumers), `rename_node`, `connect`, `disconnect`, +`set_param` (dotted `path`, or `unset: true`), `set_node` (type/timeout/retries/description). + +## 5. Preview small, then run + +``` +pw preview graph.yaml --upto labels -n 3 --json # items that came out of `labels` +pw run graph.yaml --limit 20 --json # first 20 items per source +pw run graph.yaml --json # everything; reuses all previous results +``` + +Previews and limited runs are memoized too, so the full run does not redo them. +After editing one node, re-running recomputes only that node (and downstream items +whose content changed). `--force NODE` ignores the memo for a node; `--retry-errors` +recomputes memoized node errors with fresh model samples. + +## 6. Debug + +``` +pw funnel graph.yaml --json # nodes: {out: {port: n}, events: {ok, cached, error:, pending, parked}} + # edges: [{from, to, items}] +pw status graph.yaml --json # per-node in/ok/cached/errors/running/pending/parked, usage, budget, errors +pw items graph.yaml NODE --port rejected -n 5 --json # what a filter dropped +pw items graph.yaml NODE --errors --json # failures + their input items +pw items graph.yaml NODE --sample -n 5 --full --json # random sample, untruncated +pw lineage graph.yaml ITEM_ID_PREFIX --json # which node produced what from what +pw report graph.yaml # HTML for a human +``` + +Reading error categories: `provider` / `infra` are transient (rate limits, flaky +sandboxes) and are retried automatically on the next `pw run` — do not change the +graph for them unless they persist. `node` errors are about the item or the node's +logic (bad LLM output, a failing expression) — look at `pw items --errors`. + +Item counts that look wrong are usually a filter/route expression: check +`pw items NODE --port rejected` / the route's `other` port, and remember missing keys +are `None` (so `labels.score > 0.5` on an item without `score` raises a node error; +write `(labels.score or 0) > 0.5`). + +## 7. Human review and loops + +`review.manual` parks items (`pw review graph.yaml NODE` lists them; `--approve ID…` +/ `--reject ID…` records decisions; the next run moves them on). `auto_approve` / +`auto_reject` expressions skip the human for clear cases. Use `retry.loop` for +validate → fix → validate with a hard `max_rounds`. + +## 8. Build on earlier results + +- Find what you want to reuse: `pw query graph.py --of build --node bucket --port too_easy + --where "labels.pass_rate >= 0.75"`; the output ends with the equivalent `store.query` + node, ready to paste into a new graph. +- To consume another graph continuously, import it instead of copying data: + `up = g.import_graph("build", "graph_build.py")`, then `input=up.node("bucket").port("too_easy")`. + `pw check` validates the alias, node, port and item kind. Re-running only processes + upstream items that are new. +- Feedback across runs: `g.import_graph("prev", "self")` reads this graph's previous run + (e.g. route failures to a port and feed it back into the generator) — no cycle needed. +- Trace items: `pw lineage graph.py ITEM --roots` (where a variant came from), + `--descendants` (everything derived from an item, across graphs). + +## 9. Scale out + +- Sandboxes on remote machines: define a host pool under `hosts:` and set `hosts: ` + on a docker sandbox pool with the per-sandbox `cpus`/`memory`/`requires`. Check with + `pw hosts list`; clean up with `pw hosts down` (and `pw hosts orphans` after a crash). +- Many items: run `pw run graph.py --shard I/N --group G` in N processes, then one + `pw run graph.py` to replay and write sinks; `pw funnel graph.py --group G` for totals. + +## Rules of thumb + +- Keep graphs generic; put domain logic in node types (a plugin pack) rather than in + long expressions. +- Bump a node type's `version` when you change its behaviour, so memoized results are + invalidated. +- Never put secrets in project files; use `{env: VAR}` or `{file: path, var: KEY}`. +- Use `flatmap.repeat` + `agent.run` + `join.group` for k rollouts and pass rates. diff --git a/docs/changes-for-plugins.md b/docs/changes-for-plugins.md new file mode 100644 index 0000000..d79f320 --- /dev/null +++ b/docs/changes-for-plugins.md @@ -0,0 +1,106 @@ +# Interface changes for plugin packs + +Changes made while adding host pools, cross-graph imports, sharding and the batched store. +Everything is **additive**: existing node types, providers, harnesses, sandbox providers, +`ops.*` functions and CLI commands keep working unchanged, except for the two behaviour +changes marked **(behaviour)**. + +## New registry: host providers +- `pipewright.register_host_provider(name, factory)` — `factory(name, config, project) -> HostProvider`. + Entry point group: `pipewright.hosts`. `registry.hosts` is the fifth registry. +- `pipewright.hosts.HostProvider` (in `hosts/base.py`): implement `async create(host_id, state_dir) -> Host` + and `async delete(host)`. Optional: `extend(host, seconds) -> new_expiry`, `list_remote()`, + `delete_remote(remote)`, `alive(host)`, `capacity()`, `labels()`, `kvm()`, `gpu()`, + `cost_per_hour`, and `run(host, command, timeout=, stdin=)` if hosts are not reached over SSH. +- `pipewright.hosts.vmapi.VMApiHostProvider`: base for HTTP VM APIs (bearer secret from a + secret ref, retries, per-host SSH config with a pinned host key and ControlMaster). +- Shipped: `static` (fixed SSH hosts), `fake` (tests; host commands are recorded and never run + locally), `boat` (`pipewright.contrib.boat`, loaded through the entry point; extra `boat`). + +## Project file +- New section `hosts: {: {type, min, max, capacity, reserve, labels, setup, + docker_kvm_runtime, idle_shutdown, ttl, extend_margin, budget: {hours, usd}, cost_per_hour, + persist, create_retries, create_backoff, create_limit, docker}}`. See `hosts/pool.py`. +- `Project.host_pool(name) -> HostPool` (one per Project object, shared by all sandbox pools using it). + `Project.aclose()` drains host pools after sandboxes. +- Docker sandbox pools gain `hosts: ` (place containers on a host pool) with `cpus`, + `memory`, `requires: {kvm, gpu, labels, disk}`, `prefer: [labels]`, `image_source: + {build | load | pull}`, `volumes: {name: mount}`. `host` and `hosts` are mutually exclusive. + These placement keys are excluded from memo identity (moving a sandbox to another host does + not invalidate results; changing `image` does). + +## Sandboxes +- `pipewright.sandbox.base.LEASE_CONTEXT` (ContextVar of `(priority, budget)`), set by + `SandboxProvider.lease()` around `create()`. Providers that place sandboxes on host pools use + it; `create()` keeps its signature. +- `SandboxProvider.accounts_vm_hours() -> bool` (default `capabilities.remote`): whether lease + time counts as run VM-hours. Return False when something else (a host pool) accounts host time. +- `DockerProvider.docker_argv(*args, host=None)` (new optional `host`), `DockerSandbox(..., + docker_host=, env=, host_lease=)` and `DockerSandbox.host` (the pool `Host` or None). +- `Sandbox.reverse(port) -> "host:port" | None` (async): an address reachable from inside the + sandbox that connects to 127.0.0.1:`port` on the orchestrator. Default None (use + `host_address()`). Docker sandboxes on host pools implement it with an SSH reverse tunnel + (`HostPool.reverse(host, port)`: one `ssh -N -R` per host and port, plus a relay on the + Docker bridge gateway and a best-effort `iptables` accept for it); the `cli` harness uses it + automatically, so CLI agents on pool hosts reach the logging proxy. Pool-hosted Docker pools + accept `network: host` (no relay; the container uses the loopback end). +- A plugin that wants a whole host per job can do it without new code: give the docker pool + `cpus`/`memory` equal to the host's usable capacity. + +## Graphs: imports and new node types +- `GraphSpec.imports: dict[alias, ImportSpec]` with `ImportSpec(graph, project, store, run, where)`; + inputs may reference `alias:node.port`. `Graph.import_graph(alias, path, run=..., where=...)` + returns a handle: `handle.node("bucket").port("too_easy")`. `graph="self"` reads this graph's + own previous run (re-entrant loops). `GraphSpec.base_dir` = directory of the graph file. +- `pipewright.imports.expand_imports(spec, project)` turns `alias:node` refs into virtual + `graph.import` source nodes (ids `alias:node`). `Engine.spec` is the expanded spec + (`Engine.source_spec` the original). Node ids may now contain `:` only for these. +- New node types: `store.query` (source over stored results; params graph, node, port, run, + store, kind, provenance, labels, where, derived_from, limit) and `graph.import`. +- `map.expr` gains an optional `key` expression (new item key, e.g. `payload.name`). +- `sink.jsonl` gains `mode: append | rewrite`. **(behaviour)** The default is `append`: rows are + appended for items not yet written (sidecar `.pwindex`); rows of items that no longer + reach the sink stay. Use `mode: rewrite` for the old "file = exactly this run" semantics. + +## Store +- Writes are buffered and committed in batches (`Store.commit()` flushes; buffered rows are + visible to every `Store` object on the same path in the same process — they share one + connection — and to other processes after the next commit, ≤ 0.5 s or 5000 rows). + **(behaviour)** A second *process* reading the store mid-run sees writes up to ~0.5 s late. +- New: `Store(path, readonly=True)`, `store.current_run`, `select_runs(graph, run, exclude)` + (`latest | previous | all | group: | `), `group_runs`, `query(...)`, + `descendants(id)`, `roots(id)`, `item_origin(id)`, `resolve_item(id | prefix | key)`, + `copy_from(other, ids)`, `memo_preload(sig)`. The `items` table has a new `run_id` column + (migrated automatically). + +## Engine / ops / CLI +- `RunOptions.shard=(i, n)` and `RunOptions.group`; sinks are skipped in shard runs (run once + more without `--shard` to replay from memo and write them). `engine.shard_of(key, n)`. +- `ops.run_graph(..., shard="I/N", group=...)`, `ops.funnel(..., group=...)`, + `ops.lineage(..., descendants=, roots=)` (each entry now has `origin: {run_id, graph}`), + `ops.query(...)`, `ops.hosts(action, pool=, count=, project=, start=)`. `funnel_for_run` + accepts a list of run ids; imported nodes carry `imported_from`. +- Run stats (`pw status --json`) include `hosts: {pool: snapshot}`; the final stats are written + after the drain, so they include host deletions. +- CLI: `pw run --shard I/N --group G`, `pw funnel --group G`, `pw query`, `pw lineage --roots + --descendants`, `pw hosts list|up|down|orphans`. MCP: `query`, `hosts`, `lineage(descendants, + roots)`, `funnel(group)`, `run_graph(shard, group)`. +- Expressions: `Obj` wraps nested values lazily (on attribute/index access, `get`, `values`, + `items`); `evaluate`/`eval_item` results are unchanged. + +## Rate limits (shared across processes) +- Provider `rate:` accepts `shared: true | ""` and `shared_dir` (default + `~/.cache/pipewright/rate`): the window and the 429 gate live in a SQLite ledger shared by + every process using the key. `RateLimiter(..., shared=SharedLedger)`; + `rate_limiter_from(cfg, name=None, base_dir=None)`. + +## Budgets (counters) +- `budgets: {counters: {"rollouts.terra": 60}}` in the project file; a node spends it with + `ctx.count("rollouts.terra", n=1)` (NodeContext). Over the limit, that call raises + `BudgetExceeded`: the item is recorded `pending` (resumed by a later run) while other items + and nodes continue. Unlimited counters are tracked too. `BudgetTracker(counters=...)`, + `BudgetTracker.count(name, n)`; `snapshot()` gains `counters`/`counter_limits`. + +## Funnels +- `funnel_for_run` adds `result` per node when the node returned one (sinks: `{path, rows, + appended, ...}`), shown by `pw funnel`/`pw run` and in `--json`. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..f13f075 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,268 @@ +# 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:` +recorded when an image is ensured, `volume:` 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 +`/hosts//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/.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 `.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`. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..5c8e9fa --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,74 @@ +# Roadmap and known gaps + +v0 is an async engine with a SQLite index; several worker processes can share one store +(`--shard`), sandboxes can run on autoscaled host pools, and graphs can consume each +other's results. Deferred, roughly in order of expected value: + +## Execution +- **Multi-machine sharding without a shared filesystem**: `--shard I/N` works for + processes sharing one SQLite store (batched writes; measured 2.6x with 4 workers); + across machines it needs a store server or Postgres. Joins in shard runs see only + their shard (fine for per-source-item groups like rollouts; global joins should run + in the final unsharded replay). +- **Live cross-graph triggers**: imports are read when the downstream graph runs; a + watcher that re-runs downstream graphs when an upstream run completes is not built. +- **Back-pressure for huge sources**: per-item tasks are spawned as items arrive; + millions of items should stream in bounded batches. +- **Per-node concurrency hints** for CPU-bound Python nodes (currently they run on the + event loop; heavy ones should use `asyncio.to_thread` or a process pool). +- **Cross-machine rate-limit sharing**: `rate: {shared: true}` paces all processes on + one machine through a SQLite ledger; runs on different machines sharing a key still + only learn about each other through 429s (needs a small coordinator service). +- **Run-level wall-clock timeouts and a `pw cancel`** for detached runs (Ctrl-C works + today; the run is marked cancelled and resumes on the next run). + +## Sandboxes / hosts +- Reverse tunnels exist for Docker sandboxes on host pools (`Sandbox.reverse`); not yet + for `ssh_docker` (single remote daemon) — it should become a one-host pool. +- Host pools: disk is a declared resource but not probed; GPU placement is by flag, + not by device count; hosts are packed greedily (no rebalancing/migration); a pool + is per process (two concurrent `pw run` processes each create their own hosts — use + `persist` + `pw hosts up` to share pre-created hosts, but leases are not coordinated + across processes). +- Host pool providers for other clouds (the `vmapi` base covers HTTP VM APIs). +- Modal / E2B / verifiers-runtime sandbox providers. +- Egress allowlist for remote Docker hosts; DNS-level policy. +- Snapshot/restore of sandbox state for cheap repeated attempts. + +## Harnesses +- **verifiers adapter**: the v1 harness adapter works (smoke-tested by hand with the + bash harness + subprocess runtime, including provider-failure mapping) but is not in + the automated suite because verifiers is an optional dependency; next: a Taskset adapter mapping + items to verifiers Tasks (setup/validate/score hooks) so verifiers tasksets can be + graph sources and verifiers environments can run pipewright-built tasks. +- Ready-made CLI harness configs for common agents (opencode, codex, claude code, + mini-swe-agent). +- Token/turn budgets per rollout enforced in the proxy. + +## Models +- Native (non-OpenAI) providers: Anthropic messages API, Responses API. +- Cost tables per model when providers do not report cost. +- Batch APIs for large offline labeling jobs. + +## Authoring and inspection +- `pw init` scaffolding; `pw nodes describe --all` as one LLM-sized document. +- Payload JSON schemas on ports (today port types are kind names), with checks of + expression field references against them. +- A live web UI (today: static HTML with optional auto-refresh via `pw report --watch`). +- `pw diff RUN_A RUN_B` (which items changed buckets) and per-edge samples in the CLI + funnel. +- Store maintenance: `pw gc` for blobs/memo entries unreachable from recent runs; + DuckDB attachment for ad-hoc analytics. +- Optional per-node quality gates (fail the run if a funnel ratio drops below X). + +## Known gaps in v0 +- Port kinds are checked by name only; `same` is resolved only for single-kind inputs. +- Budget estimates are coarse upper bounds from per-item cost hints. +- The fake provider's schema sampler covers common JSON-schema features only. +- `review.manual` decisions are keyed by node id; renaming the node loses them. +- `sink.jsonl` appends by default: rows of items that stop reaching the sink stay in + the file (use `mode: rewrite` when the file must equal exactly this run). +- Benchmarks (`bench/`) ran on a loaded 16-core machine (load average ~20); absolute + numbers are noisy, ratios are more meaningful. +- Docker `exec` timeouts rely on coreutils/busybox `timeout` inside the image. +- The Python graph loader executes the graph file (it is code); only load graphs you trust. diff --git a/examples/coding_tasks/fakes.py b/examples/coding_tasks/fakes.py new file mode 100644 index 0000000..6092b73 --- /dev/null +++ b/examples/coding_tasks/fakes.py @@ -0,0 +1,57 @@ +"""Scripted fake model for the coding-tasks example (offline tests). + +- synthesis requests get four fixed tasks (one with a broken reference solution, so + validation has something to reject); +- agent requests get a write_file tool call, then finish. The agent always solves + `add`, never solves `reverse_words`, and solves `classify` on alternate attempts, + so the pass-rate routing has one task in each bucket. +""" + +import json + +TASKS = [ + {"name": "add", "statement": "Return the sum of a and b.", "signature": "def add(a, b):", + "solution": "def add(a, b):\n return a + b\n", + "tests": "from solution import *\nassert add(2, 3) == 5\nassert add(-1, 1) == 0\nprint('ok')\n"}, + {"name": "classify", "statement": "Return 'fizz' for multiples of 3, 'buzz' for multiples of 5, " + "'fizzbuzz' for both, else str(n).", "signature": "def classify(n):", + "solution": "def classify(n):\n s = ('fizz' if n % 3 == 0 else '') + ('buzz' if n % 5 == 0 else '')\n" + " return s or str(n)\n", + "tests": "from solution import *\nassert classify(3) == 'fizz'\nassert classify(10) == 'buzz'\n" + "assert classify(15) == 'fizzbuzz'\nassert classify(7) == '7'\nprint('ok')\n"}, + {"name": "reverse_words", "statement": "Reverse the order of words in s, collapsing whitespace.", + "signature": "def reverse_words(s):", + "solution": "def reverse_words(s):\n return ' '.join(reversed(s.split()))\n", + "tests": "from solution import *\nassert reverse_words('a b c') == 'c b a'\nassert reverse_words('') == ''\n" + "print('ok')\n"}, + {"name": "broken_max", "statement": "Return the largest element of xs.", "signature": "def biggest(xs):", + "solution": "def biggest(xs):\n return min(xs)\n", + "tests": "from solution import *\nassert biggest([1, 5, 2]) == 5\nprint('ok')\n"}, +] + +ATTEMPTS = { + "add": ["def add(a, b):\n return a + b\n"], + "classify": [TASKS[1]["solution"], "def classify(n):\n return str(n)\n"], + "reverse_words": ["def reverse_words(s):\n return s[::-1]\n"], +} +_counter: dict[str, int] = {} + + +def respond(payload: dict): + rf = payload.get("response_format") or {} + if rf.get("type") == "json_schema": + return {"role": "assistant", "content": json.dumps({"items": TASKS})} + messages = payload["messages"] + prompt = next(m["content"] for m in messages if m["role"] == "user") + if any(m["role"] == "tool" for m in messages): + return {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_2", "type": "function", "function": {"name": "finish", "arguments": '{"summary": "done"}'}}]} + name = next((n for n in ATTEMPTS if f"def {n}(" in prompt), None) + if name is None: + return {"role": "assistant", "content": "I cannot solve this."} + i = _counter.get(name, 0) + _counter[name] = i + 1 + code = ATTEMPTS[name][i % len(ATTEMPTS[name])] + return {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_1", "type": "function", + "function": {"name": "write_file", "arguments": json.dumps({"path": "solution.py", "content": code})}}]} diff --git a/examples/coding_tasks/graph.py b/examples/coding_tasks/graph.py new file mode 100644 index 0000000..0999c36 --- /dev/null +++ b/examples/coding_tasks/graph.py @@ -0,0 +1,65 @@ +"""Agentic example: synthesize small coding tasks, validate them in a sandbox +(reference solution passes, the empty stub fails), probe each valid task with the +built-in agent at k=2, and route by pass rate. + + pw run examples/coding_tasks/graph.py # fake model + local sandbox (offline, fast) + pw run examples/coding_tasks/graph.py --project examples/coding_tasks/pipewright.docker.yaml + pw run examples/coding_tasks/graph.py --project examples/coding_tasks/pipewright.live.yaml +""" + +from pipewright import Graph + +TEST_CMD = "python3 test_solution.py" + +g = Graph("coding-tasks", description="Synthetic coding tasks, sandbox-validated and probed by an agent") + +synth = g.add("synth", "llm.synthesize", model="generator", kind="task", calls=1, batch=4, key_field="name", + prompt=( + "Invent {{ batch }} small, self-contained Python exercises of mixed difficulty (variation " + "{{ i }}). For each give: `name` (snake_case id), `statement` (what to implement), " + "`signature` (the single `def ...:` line), `solution` (a complete solution.py module), and " + "`tests` (a Python script that does `from solution import *`, checks the behaviour with " + "plain `assert`s, and prints ok). Use only the standard library."), + item_schema={"type": "object", "required": ["name", "statement", "signature", "solution", "tests"], + "properties": {k: {"type": "string"} for k in + ("name", "statement", "signature", "solution", "tests")}}) + +prepare = g.add("prepare", "map.expr", input=synth, fields={ + "stub": "payload.signature + '\\n raise NotImplementedError\\n'", + "files": "{'test_solution.py': payload.tests}", +}) + +validate = g.add("validate", "sandbox.check", input=prepare, pool="sandbox", files_expr="payload.files", + checks=[ + {"name": "gold", "files": {"solution.py": "{{ payload.solution }}"}, "command": TEST_CMD, + "expect": "pass", "timeout": 60}, + {"name": "empty", "files": {"solution.py": "{{ payload.stub }}"}, "command": TEST_CMD, + "expect": "fail", "timeout": 60}, + ]) + +valid = g.add("valid", "filter.expr", input=validate, expr="labels.valid") + +rollouts = g.add("rollouts", "flatmap.repeat", input=valid, k=2) + +probe = g.add("probe", "agent.run", input=rollouts, harness="solver", pool="sandbox", max_turns=12, timeout=600, + prompt=("{{ payload.statement }}\n\nImplement it in solution.py with this signature:\n\n" + " {{ payload.signature }}\n\nsolution.py currently contains a stub."), + files={"solution.py": "{{ payload.stub }}"}, + grade={"command": TEST_CMD, "files": {"test_solution.py": "{{ payload.tests }}"}, "timeout": 60}, + retries={"provider": 3, "infra": 2}) + +passrate = g.add("passrate", "join.group", input=probe, by="labels.group", kind="task_result", + aggregates={"pass_rate": ["mean", "labels.passed"], "rollouts": ["count", "1"]}) + +bucket = g.add("bucket", "route.expr", input=passrate, default="too_hard", routes={ + "too_easy": "labels.pass_rate == 1", + "learnable": "labels.pass_rate > 0", +}) + +for name in ("too_easy", "learnable", "too_hard"): + g.add(f"export_{name}", "sink.jsonl", path=f"out/{name}.jsonl", input=bucket.port(name), + fields=["key", "labels.pass_rate", "labels.rollouts"]) +g.add("export_invalid", "sink.jsonl", path="out/invalid.jsonl", input=valid.port("rejected"), + fields=["key", "labels.checks"]) + +graph = g diff --git a/examples/coding_tasks/graph.yaml b/examples/coding_tasks/graph.yaml new file mode 100644 index 0000000..aa2c482 --- /dev/null +++ b/examples/coding_tasks/graph.yaml @@ -0,0 +1,162 @@ +name: coding-tasks +description: Synthetic coding tasks, sandbox-validated and probed by an agent +nodes: + synth: + type: llm.synthesize + params: + model: generator + kind: task + calls: 1 + batch: 4 + key_field: name + prompt: 'Invent {{ batch }} small, self-contained Python exercises of mixed difficulty (variation + {{ i }}). For each give: `name` (snake_case id), `statement` (what to implement), `signature` + (the single `def ...:` line), `solution` (a complete solution.py module), and `tests` (a Python + script that does `from solution import *`, checks the behaviour with plain `assert`s, and prints + ok). Use only the standard library.' + item_schema: + type: object + required: + - name + - statement + - signature + - solution + - tests + properties: + name: + type: string + statement: + type: string + signature: + type: string + solution: + type: string + tests: + type: string + prepare: + type: map.expr + params: + fields: + stub: payload.signature + '\n raise NotImplementedError\n' + files: '{''test_solution.py'': payload.tests}' + inputs: + in: synth.out + validate: + type: sandbox.check + params: + pool: sandbox + files_expr: payload.files + checks: + - name: gold + files: + solution.py: '{{ payload.solution }}' + command: python3 test_solution.py + expect: pass + timeout: 60 + - name: empty + files: + solution.py: '{{ payload.stub }}' + command: python3 test_solution.py + expect: fail + timeout: 60 + inputs: + in: prepare.out + valid: + type: filter.expr + params: + expr: labels.valid + inputs: + in: validate.out + rollouts: + type: flatmap.repeat + params: + k: 2 + inputs: + in: valid.out + probe: + type: agent.run + params: + harness: solver + pool: sandbox + max_turns: 12 + prompt: |- + {{ payload.statement }} + + Implement it in solution.py with this signature: + + {{ payload.signature }} + + solution.py currently contains a stub. + files: + solution.py: '{{ payload.stub }}' + grade: + command: python3 test_solution.py + files: + test_solution.py: '{{ payload.tests }}' + timeout: 60 + inputs: + in: rollouts.out + timeout: 600.0 + retries: {} + passrate: + type: join.group + params: + by: labels.group + kind: task_result + aggregates: + pass_rate: + - mean + - labels.passed + rollouts: + - count + - '1' + inputs: + in: probe.out + bucket: + type: route.expr + params: + default: too_hard + routes: + too_easy: labels.pass_rate == 1 + learnable: labels.pass_rate > 0 + inputs: + in: passrate.out + export_too_easy: + type: sink.jsonl + params: + path: out/too_easy.jsonl + fields: + - key + - labels.pass_rate + - labels.rollouts + inputs: + in: bucket.too_easy + export_learnable: + type: sink.jsonl + params: + path: out/learnable.jsonl + fields: + - key + - labels.pass_rate + - labels.rollouts + inputs: + in: bucket.learnable + export_too_hard: + type: sink.jsonl + params: + path: out/too_hard.jsonl + fields: + - key + - labels.pass_rate + - labels.rollouts + inputs: + in: bucket.too_hard + export_invalid: + type: sink.jsonl + params: + path: out/invalid.jsonl + fields: + - key + - labels.checks + inputs: + in: valid.rejected diff --git a/examples/coding_tasks/pipewright.docker.yaml b/examples/coding_tasks/pipewright.docker.yaml new file mode 100644 index 0000000..c9b5801 --- /dev/null +++ b/examples/coding_tasks/pipewright.docker.yaml @@ -0,0 +1,12 @@ +# Same fake model, but every check and agent attempt runs in a fresh Docker container +# with no network. +store: .pipewright-docker +providers: + fake: {type: fake, script: "fakes:respond"} +models: + generator: {provider: fake, model: fake-generator} + solver: {provider: fake, model: fake-solver} +sandboxes: + sandbox: {type: docker, image: "python:3.12-slim", cpus: 1, memory: 512m, network: none} +harnesses: + solver: {type: builtin, model: solver, max_turns: 12} diff --git a/examples/coding_tasks/pipewright.live.yaml b/examples/coding_tasks/pipewright.live.yaml new file mode 100644 index 0000000..ebfb125 --- /dev/null +++ b/examples/coding_tasks/pipewright.live.yaml @@ -0,0 +1,16 @@ +# Live: DeepSeek via Morph generates the tasks and plays the agent; Docker sandboxes. +store: .pipewright-live +providers: + 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: + generator: {provider: morph, model: morph-dsv41flash-1017, params: {temperature: 0.7, max_tokens: 6000}} + solver: {provider: morph, model: morph-dsv41flash-1017, params: {temperature: 0.6, max_tokens: 3000}} +sandboxes: + sandbox: {type: docker, image: "python:3.12-slim", cpus: 1, memory: 512m, network: none} +harnesses: + solver: {type: builtin, model: solver, max_turns: 12} +budgets: {input_tokens: 400000, output_tokens: 80000} diff --git a/examples/coding_tasks/pipewright.yaml b/examples/coding_tasks/pipewright.yaml new file mode 100644 index 0000000..0f7dac4 --- /dev/null +++ b/examples/coding_tasks/pipewright.yaml @@ -0,0 +1,14 @@ +# Offline project: scripted fake model + local subprocess sandbox (needs python3 on the host). +store: .pipewright +plugins: [] +providers: + fake: + type: fake + script: fakes:respond +models: + generator: {provider: fake, model: fake-generator} + solver: {provider: fake, model: fake-solver} +sandboxes: + sandbox: {type: local} +harnesses: + solver: {type: builtin, model: solver, max_turns: 12} diff --git a/examples/hardening/common.py b/examples/hardening/common.py new file mode 100644 index 0000000..8672935 --- /dev/null +++ b/examples/hardening/common.py @@ -0,0 +1,34 @@ +"""Shared sub-graph: validate tasks in sandboxes, probe them with an agent at k=2, +and bucket them by pass rate. Used by both graphs of this example.""" + +TEST_CMD = "python3 test_solution.py" + + +def validate_and_probe(g, tasks, *, pool="sandbox", harness="solver", k=2, prefix=""): + """Add validate -> valid -> rollouts -> probe -> passrate -> bucket; return the bucket node.""" + validate = g.add(f"{prefix}validate", "sandbox.check", input=tasks, pool=pool, files_expr="payload.files", + checks=[ + {"name": "gold", "files": {"solution.py": "{{ payload.solution }}"}, "command": TEST_CMD, + "expect": "pass", "timeout": 120}, + {"name": "empty", "files": {"solution.py": "{{ payload.stub }}"}, "command": TEST_CMD, + "expect": "fail", "timeout": 120}, + ]) + valid = g.add(f"{prefix}valid", "filter.expr", input=validate, expr="labels.valid") + rollouts = g.add(f"{prefix}rollouts", "flatmap.repeat", input=valid, k=k) + probe = g.add(f"{prefix}probe", "agent.run", input=rollouts, harness=harness, pool=pool, max_turns=12, + timeout=900, + prompt=("{{ payload.statement }}\n\nImplement it in solution.py with this signature:\n\n" + " {{ payload.signature }}\n\nsolution.py currently contains a stub."), + files={"solution.py": "{{ payload.stub }}"}, + grade={"command": TEST_CMD, "files": {"test_solution.py": "{{ payload.tests }}"}, "timeout": 120}) + passrate = g.add(f"{prefix}passrate", "join.group", input=probe, by="labels.group", kind="task_result", + aggregates={"pass_rate": ["mean", "labels.passed"], "rollouts": ["count", "1"]}) + bucket = g.add(f"{prefix}bucket", "route.expr", input=passrate, default="too_hard", routes={ + "too_easy": "labels.pass_rate == 1", + "learnable": "labels.pass_rate > 0", + }) + return valid, bucket + + +STUB = {"stub": "payload.signature + '\\n raise NotImplementedError\\n'", + "files": "{'test_solution.py': payload.tests}"} diff --git a/examples/hardening/graph_build.py b/examples/hardening/graph_build.py new file mode 100644 index 0000000..836b983 --- /dev/null +++ b/examples/hardening/graph_build.py @@ -0,0 +1,26 @@ +"""Graph 1 of the two-graph example: synthesize coding tasks, validate them in +sandboxes, probe them with an agent and bucket them by pass rate. + + pw run examples/hardening/graph_build.py + pw run examples/hardening/graph_harden.py # consumes build's too_easy outputs +""" + +from pipewright import Graph + +from common import STUB, validate_and_probe + +g = Graph("build", description="Synthesize tasks, validate, probe, bucket by pass rate") +synth = g.add("synth", "llm.synthesize", model="generator", kind="task", calls=1, batch=6, key_field="name", + prompt=("Invent {{ batch }} small, self-contained Python exercises (variation {{ i }}). For each " + "give `name`, `statement`, `signature` (one `def` line), `solution` (solution.py) and " + "`tests` (a script doing `from solution import *`, plain asserts, printing ok)."), + item_schema={"type": "object", "required": ["name", "statement", "signature", "solution", "tests"], + "properties": {k: {"type": "string"} for k in + ("name", "statement", "signature", "solution", "tests")}}) +prepare = g.add("prepare", "map.expr", input=synth, fields=STUB) +valid, bucket = validate_and_probe(g, prepare) +for name in ("too_easy", "learnable", "too_hard"): + g.add(f"export_{name}", "sink.jsonl", path=f"out/build_{name}.jsonl", input=bucket.port(name), + fields=["key", "labels.pass_rate"]) + +graph = g diff --git a/examples/hardening/graph_harden.py b/examples/hardening/graph_harden.py new file mode 100644 index 0000000..3f38e75 --- /dev/null +++ b/examples/hardening/graph_harden.py @@ -0,0 +1,33 @@ +"""Graph 2: take graph 1's `too_easy` tasks, make a harder variant of each with an +LLM, and validate + probe the variants again. + +The edge from graph 1 is by reference (`imports`): every run reads the items that +flowed out of build's `bucket.too_easy` in its latest run. Item ids are preserved, so +variants made in earlier runs stay memoized and only newly-too-easy tasks cost work. +""" + +from pipewright import Graph + +from common import STUB, validate_and_probe + +g = Graph("harden", description="Harder variants of build's too_easy tasks, probed again") +build = g.import_graph("build", "graph_build.py") # cross-graph edge (by reference) +easy = build.node("bucket").port("too_easy") + +task = g.add("task", "map.expr", input=easy, kind="task", fields={ + k: f"payload.members[0].payload.{k}" for k in ("name", "statement", "signature", "solution", "tests")}) +harden = g.add("harden", "llm.label", input=task, model="generator", + prompt=("This task is too easy for current agents. Write a HARDER variant of it (new name, " + "statement, signature, reference solution and tests).\n\nTask {{ payload.name }}: " + "{{ payload.statement }}\n\nSignature: {{ payload.signature }}\n\n" + "Solution:\n{{ payload.solution }}\n\nTests:\n{{ payload.tests }}"), + labels={k: {"type": "string"} for k in ("name", "statement", "signature", "solution", "tests")}) +variant = g.add("variant", "map.expr", input=harden, key="payload.name", fields={ + **{k: f"labels.{k}" for k in ("name", "statement", "signature", "solution", "tests")}, + "hardened_from": "payload.name", **STUB}) +valid, bucket = validate_and_probe(g, variant) +for name in ("too_easy", "learnable", "too_hard"): + g.add(f"export_{name}", "sink.jsonl", path=f"out/harden_{name}.jsonl", input=bucket.port(name), + fields=["key", "labels.pass_rate"]) + +graph = g diff --git a/examples/hardening/hardening_fakes.py b/examples/hardening/hardening_fakes.py new file mode 100644 index 0000000..55d72cf --- /dev/null +++ b/examples/hardening/hardening_fakes.py @@ -0,0 +1,74 @@ +"""Scripted fake model for the two-graph hardening example (offline tests). + +- synthesis requests get five fixed tasks (one with a broken reference solution); +- "harder variant" requests get a fixed harder variant per task; +- agent requests get a write_file tool call, then finish. The agent always solves + `add` and `biggest`, alternates on `classify` and `add_many`, and never solves + `reverse_words` or `second_biggest`. +""" + +import json +import re + +T = "from solution import *\n" +TASKS = [ + {"name": "add", "statement": "Return the sum of a and b.", "signature": "def add(a, b):", + "solution": "def add(a, b):\n return a + b\n", + "tests": T + "assert add(2, 3) == 5\nassert add(-1, 1) == 0\nprint('ok')\n"}, + {"name": "classify", "statement": "Return 'fizz' for multiples of 3, 'buzz' for multiples of 5, " + "'fizzbuzz' for both, else str(n).", "signature": "def classify(n):", + "solution": "def classify(n):\n s = ('fizz' if n % 3 == 0 else '') + ('buzz' if n % 5 == 0 else '')\n" + " return s or str(n)\n", + "tests": T + "assert classify(3) == 'fizz'\nassert classify(10) == 'buzz'\nassert classify(15) == 'fizzbuzz'\n" + "assert classify(7) == '7'\nprint('ok')\n"}, + {"name": "reverse_words", "statement": "Reverse the order of words in s, collapsing whitespace.", + "signature": "def reverse_words(s):", "solution": "def reverse_words(s):\n return ' '.join(reversed(s.split()))\n", + "tests": T + "assert reverse_words('a b c') == 'c b a'\nassert reverse_words('') == ''\nprint('ok')\n"}, + {"name": "biggest", "statement": "Return the largest element of xs.", "signature": "def biggest(xs):", + "solution": "def biggest(xs):\n return max(xs)\n", "tests": T + "assert biggest([1, 5, 2]) == 5\nprint('ok')\n"}, + {"name": "broken_min", "statement": "Return the smallest element of xs.", "signature": "def smallest(xs):", + "solution": "def smallest(xs):\n return max(xs)\n", "tests": T + "assert smallest([1, 5, 2]) == 1\nprint('ok')\n"}, +] + +VARIANTS = { + "add": {"name": "add_many", "statement": "Return the sum of all arguments (any number, possibly none).", + "signature": "def add_many(*xs):", "solution": "def add_many(*xs):\n return sum(xs)\n", + "tests": T + "assert add_many() == 0\nassert add_many(1, 2, 3) == 6\nprint('ok')\n"}, + "biggest": {"name": "second_biggest", "statement": "Return the second largest DISTINCT element of xs, or " + "None if there is none.", "signature": "def second_biggest(xs):", + "solution": "def second_biggest(xs):\n s = sorted(set(xs))\n return s[-2] if len(s) > 1 else None\n", + "tests": T + "assert second_biggest([1, 5, 5, 2]) == 2\nassert second_biggest([3, 3]) is None\n" + "print('ok')\n"}, +} + +ATTEMPTS = { + "add": ["def add(a, b):\n return a + b\n"], + "biggest": ["def biggest(xs):\n return max(xs)\n"], + "classify": [TASKS[1]["solution"], "def classify(n):\n return str(n)\n"], + "reverse_words": ["def reverse_words(s):\n return s[::-1]\n"], + "add_many": [VARIANTS["add"]["solution"], "def add_many(*xs):\n return xs[0] + xs[1]\n"], + "second_biggest": ["def second_biggest(xs):\n return sorted(xs)[-2]\n"], +} +_counter: dict[str, int] = {} + + +def respond(payload: dict): + messages = payload["messages"] + prompt = next(m["content"] for m in messages if m["role"] == "user") + if "HARDER variant" in prompt: + name = re.search(r"Task (\w+):", prompt).group(1) + return {"role": "assistant", "content": json.dumps(VARIANTS.get(name, {**TASKS[0], "name": name + "_v2"}))} + if (payload.get("response_format") or {}).get("type") == "json_schema": + return {"role": "assistant", "content": json.dumps({"items": TASKS})} + if any(m["role"] == "tool" for m in messages): + return {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_2", "type": "function", "function": {"name": "finish", "arguments": '{"summary": "done"}'}}]} + name = next((n for n in ATTEMPTS if f"def {n}(" in prompt), None) + if name is None: + return {"role": "assistant", "content": "I cannot solve this."} + i = _counter.get(name, 0) + _counter[name] = i + 1 + code = ATTEMPTS[name][i % len(ATTEMPTS[name])] + return {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_1", "type": "function", + "function": {"name": "write_file", "arguments": json.dumps({"path": "solution.py", "content": code})}}]} diff --git a/examples/hardening/live_boat.py b/examples/hardening/live_boat.py new file mode 100644 index 0000000..79070c1 --- /dev/null +++ b/examples/hardening/live_boat.py @@ -0,0 +1,93 @@ +"""Live end-to-end on boat.dev VMs (costs VM time; needs BOAT_API_KEY, see pipewright.boat.yaml). + +1. run graph 1 (build) with sandboxes on the `boat` host pool: up to 2 VMs are created, + set up (Docker kvm runtime), and containers are packed onto them by CPU/memory; +2. run graph 2 (harden) on the same VMs (adopted: `persist: true`); +3. open a sandbox on the pool and show /dev/kvm inside a container; +4. let the pool scale down on idle, then delete everything and verify via the API. + + uv run python examples/hardening/live_boat.py +""" + +import asyncio +import json +import sys +import time +from pathlib import Path + +from pipewright import ops +from pipewright.project import Project + +HERE = Path(__file__).resolve().parent +PROJECT = HERE / "pipewright.boat.yaml" + + +def log(msg): + print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) + + +def summarize(res): + f = res["funnel"]["nodes"] + return {"status": res["status"], "bucket": f.get("bucket", {}).get("out"), + "validate": f.get("validate", {}).get("events"), "probe": f.get("probe", {}).get("events")} + + +async def kvm_and_scale_down(): + proj = Project.load(PROJECT) + pool = proj.host_pool("boat") + sbp = proj.sandbox_provider("sandbox") + out = {} + async with sbp.lease() as sb: + r = await sb.exec("stat -c '%a %t:%T %F' /dev/kvm && python3 -c \"import os; " + "fd=os.open('/dev/kvm', os.O_RDWR); print('kvm open ok', fd)\" && nproc && " + "cat /sys/fs/cgroup/memory.max", timeout=60) + out["kvm_exec"] = {"host": sb.host.id, "exit": r.exit_code, "stdout": r.stdout.strip()} + log(f"/dev/kvm in container on {sb.host.id}: {r.stdout.strip()!r} (exit {r.exit_code})") + log(f"hosts before scale-down: {[h.id for h in pool.hosts.values()]}") + pool.idle_shutdown, pool.tick, pool.min = 5, 2, 0 + pool._ticker.cancel() + pool._ticker = asyncio.create_task(pool._tick_loop()) + t = time.time() + while [h for h in pool.hosts.values() if h.state != "deleted"] and time.time() - t < 180: + await asyncio.sleep(2) + out["after_scale_down"] = [h.id for h in pool.hosts.values()] + out["scale_down_s"] = round(time.time() - t, 1) + log(f"hosts after idle scale-down: {out['after_scale_down']} ({out['scale_down_s']}s)") + pool.persist = False + await proj.aclose() + await pool.provider.aclose() + out["pool_stats"] = {k: v for k, v in pool.snapshot().items() if k != "hosts"} + return out + + +def main(): + report = {} + t0 = time.time() + try: + log("graph 1 (build) on boat VMs") + report["build"] = summarize(ops.run_graph(HERE / "graph_build.py", project=PROJECT, on_log=None)) + log(json.dumps(report["build"])) + log("graph 2 (harden) on the same VMs") + report["harden"] = summarize(ops.run_graph(HERE / "graph_harden.py", project=PROJECT, on_log=None)) + log(json.dumps(report["harden"])) + report["kvm"] = asyncio.run(kvm_and_scale_down()) + finally: + log("cleanup: pw hosts down + orphans") + report["down"] = ops.hosts("down", project=PROJECT, start=HERE) + report["orphans"] = ops.hosts("orphans", project=PROJECT, start=HERE) + report["remaining_remote"] = ops.hosts("list", project=PROJECT, start=HERE)["remote"] + events = [json.loads(x) for x in (HERE / ".pipewright-boat/hosts/boat/events.jsonl").read_text().splitlines()] \ + if (HERE / ".pipewright-boat/hosts/boat/events.jsonl").exists() else [] + report["host_events"] = events + created = {e["host"]: e["at"] for e in events if e["event"] == "creating"} + deleted = {e["host"]: e["at"] for e in events if e["event"] == "deleted"} + report["vm_hours"] = round(sum((deleted.get(h, time.time()) - c) for h, c in created.items()) + / 3600, 3) + report["wall_s"] = round(time.time() - t0, 1) + print(json.dumps(report, indent=1, default=str)) + if report["remaining_remote"]: + print("WARNING: VMs remain:", report["remaining_remote"], file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/examples/hardening/live_tunnel.py b/examples/hardening/live_tunnel.py new file mode 100644 index 0000000..36ba375 --- /dev/null +++ b/examples/hardening/live_tunnel.py @@ -0,0 +1,59 @@ +"""Live check of reverse tunnels: containers on a boat VM (bridge network and host +network) call the local logging proxy — the path CLI-harness agents use — through +`Sandbox.reverse()`. One VM, deleted at the end. + + uv run python examples/hardening/live_tunnel.py +""" + +import asyncio +import json +import time +from pathlib import Path + +import yaml + +from pipewright.models.base import ModelClient +from pipewright.models.proxy import LoggingProxy +from pipewright.project import Project, ProjectConfig + +HERE = Path(__file__).resolve().parent + + +async def main(): + cfg = yaml.safe_load((HERE / "pipewright.boat.yaml").read_text()) + cfg["store"] = ".pipewright-tunnel" + cfg["hosts"]["boat"].update(max=1, persist=False) + cfg["sandboxes"]["sandbox"].update(network="bridge", cpus=1, memory="1g") + cfg["sandboxes"]["hostnet"] = {**cfg["sandboxes"]["sandbox"], "network": "host"} + cfg["providers"]["fake"] = {"type": "fake"} + proj = Project(ProjectConfig.model_validate(cfg), HERE) + alias = proj.config.models["solver"] + client = ModelClient("solver", alias, proj.provider(alias.provider)) + proxy = LoggingProxy() + out = {} + t = time.time() + try: + for pool in ("sandbox", "hostnet"): # bridge network (relay) and host network (loopback) + async with proj.sandbox_provider(pool).lease() as sb: + port = await proxy.listen("127.0.0.1") + session = proxy.open_session(client) + addr = await sb.reverse(port) + body = json.dumps({"model": "x", "messages": [{"role": "user", "content": "hello through the tunnel"}]}) + code = ("import json, os, urllib.request\n" + f"req = urllib.request.Request('http://{addr}/v1/chat/completions', data=os.environ['BODY'].encode()," + " headers={'Authorization': 'Bearer ' + os.environ['TOKEN'], 'Content-Type': 'application/json'})\n" + "d = json.load(urllib.request.urlopen(req, timeout=30))\n" + "print(d['choices'][0]['message']['content'][:80])\n") + r = await sb.exec(["python3", "-c", code], env={"BODY": body, "TOKEN": session.token}, timeout=60) + out[pool] = {"host": sb.host.id, "addr": addr, "exit": r.exit_code, "stdout": r.stdout.strip(), + "stderr": r.stderr.strip()[-300:], "proxy_turns": len(session.turns) if hasattr(session, "turns") + else None, "seconds": round(time.time() - t, 1)} + finally: + await proxy.aclose() + await proj.aclose() + out["remaining"] = await proj.host_pool("boat").provider.list_remote() + out["pool"] = {k: v for k, v in proj.host_pool("boat").snapshot().items() if k in ("created", "deleted", "used_hours")} + print(json.dumps(out, indent=1)) + + +asyncio.run(main()) diff --git a/examples/hardening/pipewright.boat.yaml b/examples/hardening/pipewright.boat.yaml new file mode 100644 index 0000000..3573296 --- /dev/null +++ b/examples/hardening/pipewright.boat.yaml @@ -0,0 +1,35 @@ +# Same graphs, sandboxes on boat.dev VMs: Docker containers placed on a host pool of +# up to 2 "large" VMs (8 vCPU / 16 GB), each container reserving 2 CPUs / 3 GB and +# requiring /dev/kvm. The model stays the offline fake (only the sandboxes are remote). +# +# pw run examples/hardening/graph_build.py --project examples/hardening/pipewright.boat.yaml +# pw hosts down --dir examples/hardening --project examples/hardening/pipewright.boat.yaml +store: .pipewright-boat +providers: + fake: {type: fake, script: hardening_fakes:respond} +models: + generator: {provider: fake, model: fake-generator} + solver: {provider: fake, model: fake-solver} +hosts: + boat: + type: boat # pipewright.contrib.boat (entry point) + api_key: {file: ~/.config/deepswe-eval/secrets, var: BOAT_API_KEY} + vm_type: large + min: 0 + max: 2 + ttl: 3600 + idle_shutdown: 60 + reserve: {cpus: 0.5, memory: 1g} + docker_kvm_runtime: true + budget: {hours: 2} + persist: true # keep VMs between the two graphs' runs; `pw hosts down` deletes them +sandboxes: + sandbox: + type: docker + hosts: boat + image: python:3.12-slim + cpus: 2 + memory: 3g + requires: {kvm: true} +harnesses: + solver: {type: builtin, model: solver, max_turns: 12} diff --git a/examples/hardening/pipewright.yaml b/examples/hardening/pipewright.yaml new file mode 100644 index 0000000..9545d8c --- /dev/null +++ b/examples/hardening/pipewright.yaml @@ -0,0 +1,12 @@ +# Offline project for both graphs (they share this store): scripted fake model + +# local subprocess sandbox (needs python3 on the host). +store: .pipewright +providers: + fake: {type: fake, script: hardening_fakes:respond} +models: + generator: {provider: fake, model: fake-generator} + solver: {provider: fake, model: fake-solver} +sandboxes: + sandbox: {type: local} +harnesses: + solver: {type: builtin, model: solver, max_turns: 12} diff --git a/examples/issue_triage/data/issues.jsonl b/examples/issue_triage/data/issues.jsonl new file mode 100644 index 0000000..edcb439 --- /dev/null +++ b/examples/issue_triage/data/issues.jsonl @@ -0,0 +1,12 @@ +{"id": "gh-101", "title": "Crash when opening a file with unicode name", "body": "Opening `résumé.txt` crashes the app.\n\nTraceback (most recent call last):\n File \"app.py\", line 88, in open_file\n name.encode('ascii')\nUnicodeEncodeError: 'ascii' codec can't encode character '\\xe9'\n\nSteps: 1. create the file 2. File > Open. Expected: file opens.", "comments": 4, "reactions": 7} +{"id": "gh-102", "title": "Add dark mode", "body": "It would be great to have a dark theme. My eyes hurt at night. Many similar apps support this already.", "comments": 12, "reactions": 40} +{"id": "gh-103", "title": "How do I configure the proxy?", "body": "I am behind a corporate proxy and downloads fail. Is there a setting for HTTP_PROXY? I could not find it in the docs.", "comments": 2, "reactions": 0} +{"id": "gh-104", "title": "Memory leak in background sync", "body": "After running for ~6 hours RSS grows from 200MB to 3GB. Heap snapshot shows thousands of retained SyncJob objects. Happens on v2.3.1 and main, not on v2.2.\n\n```\nSyncJob x 48211 retained 2.7GB\n```", "comments": 9, "reactions": 15} +{"id": "gh-105", "title": "typo in README", "body": "\"recieve\" should be \"receive\".", "comments": 0, "reactions": 1} +{"id": "gh-106", "title": "Support exporting to CSV", "body": "Please add CSV export next to JSON export. We need it for spreadsheets. Columns could match the table view.", "comments": 3, "reactions": 9} +{"id": "gh-107", "title": "Data loss when two clients edit the same note", "body": "Two clients editing the same note at the same time: the second save silently overwrites the first. No conflict warning. We lost a day of notes in our team. This seems to be a race in `merge_remote()`; the version check happens after the write.", "comments": 21, "reactions": 33} +{"id": "gh-108", "title": "Why is startup slow?", "body": "Startup takes 8 seconds on my laptop. Is that expected? What does it do on startup?", "comments": 5, "reactions": 2} +{"id": "gh-109", "title": "Segfault in image thumbnailer with large PNG", "body": "Loading a 20000x20000 PNG segfaults.\n\n```\nProgram received signal SIGSEGV\n#0 resize_rows (src=0x0) at thumb.c:211\n```\nLooks like the allocation fails and the NULL is not checked.", "comments": 6, "reactions": 4} +{"id": "gh-110", "title": "asdf", "body": "test", "comments": 0, "reactions": 0} +{"id": "gh-111", "title": "Keyboard shortcut to duplicate a line", "body": "VS Code has Shift+Alt+Down to duplicate a line. Could we get the same? I use it all the time.", "comments": 1, "reactions": 6} +{"id": "gh-112", "title": "Login fails with SSO after upgrade to 3.0", "body": "Since 3.0 SSO login redirects back to the login page in a loop. Error in console: `invalid_state: state parameter mismatch`. Downgrading to 2.9 fixes it. We have 200 users blocked.", "comments": 14, "reactions": 25} diff --git a/examples/issue_triage/graph.py b/examples/issue_triage/graph.py new file mode 100644 index 0000000..400461e --- /dev/null +++ b/examples/issue_triage/graph.py @@ -0,0 +1,47 @@ +"""Issue triage: heuristic labels -> filter -> structured LLM labels -> route -> export. + + pw check examples/issue_triage/graph.py + pw run examples/issue_triage/graph.py # fake model (pipewright.yaml) + pw run examples/issue_triage/graph.py --project examples/issue_triage/pipewright.live.yaml +""" + +from pipewright import Graph +from pipewright.nodes.builtin import FilterExpr, LabelExpr, LLMLabel, RouteExpr + +g = Graph("issue-triage", description="Label GitHub-style issues and route the urgent bugs") + +issues = g.add("issues", "source.file", path="data/issues.jsonl", kind="issue") + +heuristics = g.add("heuristics", LabelExpr.Params(labels={ + "has_traceback": r"re(r'traceback|sigsegv|segfault|exception|error:', payload.body)", + "has_code": "'```' in payload.body", + "words": "words(payload.body)", + "engagement": "payload.comments + payload.reactions", +}), input=issues) + +substantive = g.add("substantive", FilterExpr.Params(expr="labels.words >= 8"), input=heuristics) + +classify = g.add("classify", LLMLabel.Params( + model="labeler", + system="You triage issues for a software project. Be concise and literal.", + prompt=("Classify this issue.\n\nTitle: {{ payload.title }}\n\n{{ payload.body }}\n\n" + "Severity: 0 = cosmetic, 1 = minor, 2 = major (broken feature), 3 = critical (crash, data loss, " + "security, many users blocked)."), + labels={ + "category": {"type": "string", "enum": ["bug", "feature", "question", "docs"]}, + "severity": {"type": "integer", "minimum": 0, "maximum": 3}, + "summary": {"type": "string", "maxLength": 160}, + }, +), input=substantive) + +route = g.add("route", RouteExpr.Params(routes={ + "urgent": "labels.category == 'bug' and (labels.severity >= 2 or labels.has_traceback)", + "features": "labels.category == 'feature'", +}, default="other"), input=classify) + +fields = ["key", "payload.title", "labels.category", "labels.severity", "labels.summary", "labels.engagement"] +g.add("export_urgent", "sink.jsonl", path="out/urgent.jsonl", fields=fields, input=route.port("urgent")) +g.add("export_features", "sink.jsonl", path="out/features.jsonl", fields=fields, input=route.port("features")) +g.add("export_other", "sink.jsonl", path="out/other.jsonl", fields=fields, input=route.port("other")) + +graph = g diff --git a/examples/issue_triage/graph.yaml b/examples/issue_triage/graph.yaml new file mode 100644 index 0000000..7520ab3 --- /dev/null +++ b/examples/issue_triage/graph.yaml @@ -0,0 +1,102 @@ +name: issue-triage +description: Label GitHub-style issues and route the urgent bugs +nodes: + issues: + type: source.file + params: + path: data/issues.jsonl + kind: issue + heuristics: + type: label.expr + params: + labels: + has_traceback: re(r'traceback|sigsegv|segfault|exception|error:', payload.body) + has_code: '''```'' in payload.body' + words: words(payload.body) + engagement: payload.comments + payload.reactions + inputs: + in: issues.out + substantive: + type: filter.expr + params: + expr: labels.words >= 8 + inputs: + in: heuristics.out + classify: + type: llm.label + params: + model: labeler + prompt: |- + Classify this issue. + + Title: {{ payload.title }} + + {{ payload.body }} + + Severity: 0 = cosmetic, 1 = minor, 2 = major (broken feature), 3 = critical (crash, data loss, security, many users blocked). + system: You triage issues for a software project. Be concise and literal. + labels: + category: + type: string + enum: + - bug + - feature + - question + - docs + severity: + type: integer + minimum: 0 + maximum: 3 + summary: + type: string + maxLength: 160 + inputs: + in: substantive.out + route: + type: route.expr + params: + routes: + urgent: labels.category == 'bug' and (labels.severity >= 2 or labels.has_traceback) + features: labels.category == 'feature' + default: other + inputs: + in: classify.out + export_urgent: + type: sink.jsonl + params: + path: out/urgent.jsonl + fields: + - key + - payload.title + - labels.category + - labels.severity + - labels.summary + - labels.engagement + inputs: + in: route.urgent + export_features: + type: sink.jsonl + params: + path: out/features.jsonl + fields: + - key + - payload.title + - labels.category + - labels.severity + - labels.summary + - labels.engagement + inputs: + in: route.features + export_other: + type: sink.jsonl + params: + path: out/other.jsonl + fields: + - key + - payload.title + - labels.category + - labels.severity + - labels.summary + - labels.engagement + inputs: + in: route.other diff --git a/examples/issue_triage/pipewright.live.yaml b/examples/issue_triage/pipewright.live.yaml new file mode 100644 index 0000000..8e8d6fb --- /dev/null +++ b/examples/issue_triage/pipewright.live.yaml @@ -0,0 +1,18 @@ +# Live project: DeepSeek via Morph (OpenAI-compatible). The key is read from ~/.tmp +# (line MORPH_SK=...) or the MORPH_SK environment variable; it is never logged. +# Morph's per-minute limits are shared across everything using the key, and rejected +# requests count against the window; the limiter paces below them. +store: .pipewright-live +providers: + 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} + quirks: [stream_error_event, body_error] +models: + labeler: + provider: morph + model: morph-dsv41flash-1017 + params: {temperature: 0, max_tokens: 2000} +budgets: {input_tokens: 200000, output_tokens: 60000} diff --git a/examples/issue_triage/pipewright.yaml b/examples/issue_triage/pipewright.yaml new file mode 100644 index 0000000..c63404d --- /dev/null +++ b/examples/issue_triage/pipewright.yaml @@ -0,0 +1,12 @@ +# Default project for the example: a deterministic fake model, so it runs offline. +# Use pipewright.live.yaml for a real provider. +store: .pipewright +providers: + fake: + type: fake + rules: + - {match: "silently overwrites|SIGSEGV|RSS grows|redirects back|UnicodeEncodeError", content: '{"category": "bug", "severity": 3, "summary": "Crash or data loss affecting users."}'} + - {match: "would be great|please add|could we get|support exporting", content: '{"category": "feature", "severity": 0, "summary": "Feature request."}'} + - {match: "how do i|why is|is that expected", content: '{"category": "question", "severity": 0, "summary": "Usage question."}'} +models: + labeler: {provider: fake, model: fake-labeler} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..fa512bd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,45 @@ +[project] +name = "pipewright" +version = "0.1.0" +description = "Graph-based framework for repeatable data pipelines mixing LLM calls, agents and sandboxed execution" +readme = "README.md" +requires-python = ">=3.12" +license = { text = "MIT" } +dependencies = [ + "pydantic>=2.7", + "httpx>=0.27", + "pyyaml>=6", +] + +[project.optional-dependencies] +duckdb = ["duckdb>=1.0"] +mcp = ["mcp>=1.2"] +verifiers = ["verifiers>=0.1.10"] +boat = [] # boat.dev host provider (pipewright.contrib.boat; httpx is already a core dependency) + +[project.scripts] +pw = "pipewright.cli:main" + +[project.entry-points."pipewright.nodes"] +builtin = "pipewright.nodes.builtin" +agentic = "pipewright.nodes.agentic" + +[project.entry-points."pipewright.hosts"] +boat = "pipewright.contrib.boat" + +[dependency-groups] +dev = ["pytest>=8"] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/pipewright"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +markers = [ + "live: talks to a real model provider (run with --live)", + "docker: needs a local Docker daemon (run with --docker)", +] diff --git a/src/pipewright/__init__.py b/src/pipewright/__init__.py new file mode 100644 index 0000000..a0c8cde --- /dev/null +++ b/src/pipewright/__init__.py @@ -0,0 +1,24 @@ +"""pipewright: graph-based, resumable data pipelines mixing LLM calls, agents and sandboxes. + +Public API: + + from pipewright import Graph, Item, NodeType, Port, register_node + from pipewright import register_provider, register_harness, register_sandbox, register_host_provider +""" + +from .errors import ConfigError, InfraError, NodeError, ProviderError +from .graph import Graph, GraphSpec, NodeSpec, RetryPolicy, load_graph, save_graph +from .items import ArtifactRef, Item, new_item +from .nodes.base import ANY, SAME, NodeType, Port, ResourceRef +from .project import Project +from .registry import (register_harness, register_host_provider, register_node, register_provider, register_sandbox, + registry) + +__version__ = "0.1.0" + +__all__ = [ + "ANY", "SAME", "ArtifactRef", "ConfigError", "Graph", "GraphSpec", "InfraError", "Item", "NodeError", + "NodeSpec", "NodeType", "Port", "Project", "ProviderError", "ResourceRef", "RetryPolicy", "load_graph", + "new_item", "register_harness", "register_host_provider", "register_node", "register_provider", "register_sandbox", "registry", + "save_graph", +] diff --git a/src/pipewright/check.py b/src/pipewright/check.py new file mode 100644 index 0000000..619d1f8 --- /dev/null +++ b/src/pipewright/check.py @@ -0,0 +1,228 @@ +"""Static checks for graphs (`pw check`): every problem gets a code, a location and a +hint that says what to do. Layered like n8n-MCP's validators: file/schema -> node +types and params -> wiring and port types -> resources in the project -> budgets. +""" + +from __future__ import annotations + +import difflib +from dataclasses import asdict, dataclass + +from .errors import ConfigError +from .expr import ExprError +from .graph import GraphSpec, split_ref +from .nodes.base import ANY, SAME, NodeType +from .project import Project +from .registry import registry + + +@dataclass +class Diagnostic: + level: str # error | warning | info + code: str + message: str + node: str | None = None + port: str | None = None + hint: str | None = None + + def format(self) -> str: + where = f"{self.node}{'.' + self.port if self.port else ''}: " if self.node else "" + return f"{self.level.upper()} {self.code} {where}{self.message}" + (f" (hint: {self.hint})" if self.hint else "") + + def to_dict(self) -> dict: + return {k: v for k, v in asdict(self).items() if v is not None} + + +SECTIONS = {"model": "models", "sandbox": "sandboxes", "harness": "harnesses"} + + +def _suggest(name: str, options) -> str | None: + m = difflib.get_close_matches(name, list(options), n=1, cutoff=0.5) + return f"did you mean {m[0]!r}?" if m else None + + +def _kinds_compatible(produced: str, accepted: str) -> bool: + if ANY in (produced, accepted): + return True + return produced in accepted.split("|") + + +def check(spec: GraphSpec, project: Project | None = None) -> list[Diagnostic]: + project = project or Project.discover(".") + out: list[Diagnostic] = [] + try: + registry.import_plugins(spec.plugins) + except ConfigError as e: + out.append(Diagnostic("error", "PW016", str(e), hint="fix the module path in `plugins`")) + for where, msg in project.config_problems(): + level = "warning" if "secret" in msg else "error" + out.append(Diagnostic(level, "PW012", f"project {where}: {msg}", + hint="edit the project file (pipewright.yaml)")) + + from .imports import expand_imports + + problems: list[tuple[str, str, str]] = [] + try: + spec = expand_imports(spec, project, strict=False, problems=problems) + except ConfigError as e: + problems.append(("", "", str(e))) + for nid, port, msg in problems: + out.append(Diagnostic("error", "PW020", msg, nid or None, port or None, + hint="check `imports:` (alias, graph path) and that the imported node/port exists")) + + classes: dict[str, type[NodeType]] = {} + params: dict[str, object] = {} + for nid, n in spec.nodes.items(): + if "." in nid or not nid: + out.append(Diagnostic("error", "PW000", f"invalid node id {nid!r}", nid, + hint="node ids may not contain '.' (it separates node and port)")) + cls = registry.node_types.get(n.type) + if cls is None: + out.append(Diagnostic("error", "PW001", f"unknown node type {n.type!r}", nid, + hint=_suggest(n.type, registry.node_types.names()) or "see `pw nodes list`")) + continue + classes[nid] = cls + try: + p = cls.Params.model_validate(n.params) + except Exception as e: + for err in getattr(e, "errors", lambda: [])() or [{"loc": (), "msg": str(e)}]: + loc = ".".join(str(x) for x in err.get("loc", ())) + out.append(Diagnostic("error", "PW002", f"param {loc or '(root)'}: {err.get('msg')}", nid, + hint=f"see `pw nodes describe {n.type}` for the params schema")) + continue + params[nid] = p + try: + for msg in cls.validate_params(p): + out.append(Diagnostic("error", "PW002", msg, nid)) + except ExprError as e: + out.append(Diagnostic("error", "PW002", str(e), nid)) + for r in cls.resources(p): + if not project.has(r): + options = project.names(r.type) + out.append(Diagnostic( + "error", "PW011", f"{r.type} {r.name!r} (param `{r.param}`) is not defined in the project", nid, + hint=_suggest(r.name, options) or (f"defined: {options}" if options else + f"add it under `{SECTIONS[r.type]}:` in pipewright.yaml"))) + if cls.kind == "source" and n.inputs: + out.append(Diagnostic("error", "PW005", "source nodes take no inputs", nid, + hint="remove `inputs` from this node")) + + # wiring + for src, sport, dst, dport in spec.edges(): + if src not in spec.nodes: + out.append(Diagnostic("error", "PW003", f"input {dport!r} refers to unknown node {src!r}", dst, dport, + hint=_suggest(src, spec.nodes) or f"nodes: {sorted(spec.nodes)}")) + continue + if src in classes and src in params: + ports = classes[src].output_ports(params[src]) + if sport not in ports: + out.append(Diagnostic("error", "PW004", f"{src!r} has no output port {sport!r}", dst, dport, + hint=_suggest(sport, ports) or f"ports of {src}: {sorted(ports) or 'none'}")) + if dst in classes and dst in params: + ins = classes[dst].input_ports(params[dst]) + if dport not in ins: + out.append(Diagnostic("error", "PW005", f"no input port {dport!r}", dst, dport, + hint=f"input ports: {sorted(ins) or 'none'}")) + + try: + order = spec.topo_order() + except ConfigError as e: + out.append(Diagnostic("error", "PW008", str(e), hint="graphs are DAGs; use retry.loop for bounded loops " + "and source.prior_run for cross-run feedback")) + return out + + # port types (inferred along the DAG) + produced: dict[tuple[str, str], str] = {} + for nid in order: + if nid not in classes or nid not in params: + continue + cls, p = classes[nid], params[nid] + in_kinds: dict[str, set[str]] = {} + for dport, refs in spec.nodes[nid].inputs.items(): + for ref in refs: + s, sp = split_ref(ref) + k = produced.get((s, sp), ANY) + in_kinds.setdefault(dport, set()).add(k) + accepted = cls.input_ports(p).get(dport) + if accepted is not None and not _kinds_compatible(k, accepted.kind): + out.append(Diagnostic("error", "PW007", f"kind mismatch: {s}.{sp} produces {k!r} but " + f"{dport!r} accepts {accepted.kind!r}", nid, dport, + hint="insert a map node that converts the kind, or connect another port")) + same = in_kinds.get("in", set()) + same_kind = next(iter(same)) if len(same) == 1 else ANY + for port, spec_port in cls.output_ports(p).items(): + produced[(nid, port)] = same_kind if spec_port.kind == SAME else spec_port.kind + for port, spec_port in cls.input_ports(p).items(): + if port not in spec.nodes[nid].inputs and not spec_port.optional: + out.append(Diagnostic("error", "PW006", f"required input {port!r} is not connected", nid, port, + hint=f"set inputs.{port} to an upstream `node` or `node.port`")) + + # dead ends and unused ports + consumed = {(s, sp) for s, sp, _, _ in spec.edges()} + for nid in order: + if nid not in classes or nid not in params: + continue + cls, p = classes[nid], params[nid] + ports = cls.output_ports(p) + used = [pt for pt in ports if (nid, pt) in consumed] + if ports and not used and cls.kind != "sink": + out.append(Diagnostic("warning", "PW009", "no output is connected (results only visible via " + "`pw items`)", nid, hint="connect a sink, or ignore for preview/debug graphs")) + for pt, port in ports.items(): + if used and pt not in used and not port.optional: + out.append(Diagnostic("info", "PW009", f"output port {pt!r} is not connected", nid, pt)) + + out += estimate_budget(spec, project, order, classes, params) + return out + + +def estimate_budget(spec: GraphSpec, project: Project, order, classes, params) -> list[Diagnostic]: + """Rough upper-bound estimates from source counts x per-item cost hints.""" + count: dict[str, float | None] = {} + totals = {"llm_calls": 0.0, "input_tokens": 0.0, "output_tokens": 0.0, "sandbox_seconds": 0.0, "usd": 0.0} + unknown = [] + for nid in order: + if nid not in classes or nid not in params: + count[nid] = None + continue + cls, p = classes[nid], params[nid] + if cls.kind == "source": + try: + n = cls.estimate_count(p, project) + except Exception: + n = None + else: + ups = [count.get(split_ref(r)[0]) for refs in spec.nodes[nid].inputs.values() for r in refs] + n = None if any(u is None for u in ups) else sum(ups) * cls.estimate_factor(p) # type: ignore[arg-type] + count[nid] = n + hint = cls.cost_hint(p) + if not hint: + continue + mult = 1 if hint.get("per_run") else n + if mult is None: + unknown.append(nid) + continue + for k in ("llm_calls", "input_tokens", "output_tokens", "sandbox_seconds"): + totals[k] += hint.get(k, 0) * mult + for r in cls.resources(p): + if r.type == "model" and r.name in project.config.models: + alias = project.config.models[r.name] + pricing = (project.config.providers.get(alias.provider) or {}).get("pricing") or {} + totals["usd"] += (hint.get("input_tokens", 0) * pricing.get("input_per_mtok", 0) + + hint.get("output_tokens", 0) * pricing.get("output_per_mtok", 0)) * mult / 1e6 + diags = [] + if any(totals.values()): + msg = (f"estimate (upper bound, all items): {totals['llm_calls']:.0f} LLM calls, " + f"{totals['input_tokens']/1e3:.0f}k in / {totals['output_tokens']/1e3:.0f}k out tokens, " + f"{totals['sandbox_seconds']/3600:.2f} sandbox-hours" + + (f", ~${totals['usd']:.2f}" if totals["usd"] else "")) + if unknown: + msg += f" (excluding {', '.join(unknown)}: item count unknown)" + diags.append(Diagnostic("info", "PW014", msg)) + b = project.config.budgets + for key, lim in (("usd", b.usd), ("input_tokens", b.input_tokens), ("output_tokens", b.output_tokens)): + if lim is not None and totals[key] > lim: + diags.append(Diagnostic("warning", "PW014", f"estimated {key} {totals[key]:.4g} exceeds the " + f"budget {lim}", hint="the run stops admitting work at the budget; " + "use `pw preview -n` first or raise budgets")) + return diags diff --git a/src/pipewright/cli.py b/src/pipewright/cli.py new file mode 100644 index 0000000..17cc152 --- /dev/null +++ b/src/pipewright/cli.py @@ -0,0 +1,462 @@ +"""`pw` — the pipewright CLI. Every command takes --json for machine-readable output.""" + +from __future__ import annotations + +import argparse +import json +import sys +import time +from pathlib import Path +from typing import Any + +from . import ops +from .errors import ConfigError, PipewrightError + + +def _emit(args, data: Any, human) -> None: + if args.json: + print(json.dumps(data, indent=2, ensure_ascii=False, default=str)) + else: + human(data) + + +def _diag_lines(diags: list[dict]) -> None: + for d in diags: + where = f"{d.get('node')}{'.' + d['port'] if d.get('port') else ''}: " if d.get("node") else "" + hint = f"\n hint: {d['hint']}" if d.get("hint") else "" + print(f" {d['level']:<7} {d['code']} {where}{d['message']}{hint}") + + +def _print_funnel(f: dict) -> None: + print(f"run {f['run_id']}") + for nid, info in f["nodes"].items(): + ev = info["events"] + errs = {k: v for k, v in ev.items() if k.startswith("error")} + bits = [f"ok={ev.get('ok', 0)}"] + if ev.get("cached"): + bits.append(f"cached={ev['cached']}") + if errs: + bits.append("errors=" + ",".join(f"{k.split(':', 1)[-1]}:{v}" for k, v in errs.items())) + for k in ("pending", "parked"): + if ev.get(k): + bits.append(f"{k}={ev[k]}") + outs = " ".join(f"{p}={n}" for p, n in info["out"].items()) + print(f" {nid:<22} {info['type']:<18} {' '.join(bits):<36} -> {outs}") + if info.get("result") is not None: + print(f" {'':<22} result: {json.dumps(info['result'], default=str)[:200]}") + if info.get("imported_from"): + imp = info["imported_from"] + print(f" {'':<22} from graph {imp.get('graph')}:{imp.get('node')} (run={imp.get('run')})") + print("edges:") + for e in f["edges"]: + print(f" {e['from']:>28} -> {e['to']:<28} {e['items']}") + + +def _print_items(res: dict) -> None: + if "errors" in res: + for e in res["errors"]: + print(f"- [{e['category']}] {e['input'][:12]} {e['message']}") + return + print(f"run {res['run_id']} node {res['node']}{'.' + res['port'] if res.get('port') else ''}: " + f"{res['total']} items (showing {len(res['items'])})") + for it in res["items"]: + print(json.dumps(it, indent=2, ensure_ascii=False, default=str)) + + +def main(argv: list[str] | None = None) -> int: + common = argparse.ArgumentParser(add_help=False) + common.add_argument("--json", action="store_true", help="machine-readable output") + common.add_argument("--project", help="project file (default: nearest pipewright.yaml above the graph)") + + p = argparse.ArgumentParser(prog="pw", parents=[common], + description="pipewright: graph pipelines mixing LLM calls, agents and sandboxes") + sub = p.add_subparsers(dest="cmd", required=True) + + nodes = sub.add_parser("nodes", parents=[common], help="node type docs") + nsub = nodes.add_subparsers(dest="nodes_cmd", required=True) + nsub.add_parser("list", parents=[common], help="list node types") + nd = nsub.add_parser("describe", parents=[common], help="ports, params schema, resources, example") + nd.add_argument("type") + + c = sub.add_parser("check", parents=[common], help="validate a graph (exit 1 on errors)") + c.add_argument("graph") + + pa = sub.add_parser("patch", parents=[common], help="apply JSON graph ops, validated before writing") + pa.add_argument("graph", nargs="?") + pa.add_argument("ops", nargs="?", help="ops JSON file, '-' for stdin, or an inline JSON list") + pa.add_argument("--dry-run", action="store_true") + pa.add_argument("--force", action="store_true", help="write even if the result has errors") + pa.add_argument("--out", help="write to another file") + pa.add_argument("--schema", action="store_true", help="print the JSON schema of patch ops") + + for name, hlp in (("run", "run the graph (resumes: memoized results are reused)"), + ("preview", "run on the first N source items up to a node and show its output")): + r = sub.add_parser(name, parents=[common], help=hlp) + r.add_argument("graph") + r.add_argument("--upto", help="stop after this node") + if name == "run": + r.add_argument("--limit", type=int, help="items per source") + r.add_argument("--force", action="append", default=[], metavar="NODE", help="ignore memo for NODE") + r.add_argument("--retry-errors", action="store_true", help="recompute memoized node errors") + r.add_argument("--run-id") + r.add_argument("--shard", metavar="I/N", help="process only source items whose key hashes to I mod N " + "(several workers on one store; sinks are skipped)") + r.add_argument("--group", help="run group label (e.g. shared by all shards); see `pw funnel --group`") + else: + r.add_argument("-n", type=int, default=5) + r.add_argument("--quiet", action="store_true", help="no progress log on stderr") + + for name, hlp in (("status", "latest (or given) run: state, node stats, usage, errors"), + ("funnel", "item counts per node and edge"), ("runs", "list runs")): + s = sub.add_parser(name, parents=[common], help=hlp) + s.add_argument("graph") + if name != "runs": + s.add_argument("--run") + if name == "funnel": + s.add_argument("--group", help="sum the funnels of all runs in this group (e.g. shards)") + + it = sub.add_parser("items", parents=[common], help="items that came out of a node") + it.add_argument("graph") + it.add_argument("node") + it.add_argument("--port") + it.add_argument("-n", type=int, default=5) + it.add_argument("--sample", action="store_true", help="random sample instead of the first n") + it.add_argument("--errors", action="store_true", help="show the node's errors and their input items") + it.add_argument("--full", action="store_true", help="do not truncate long strings") + it.add_argument("--run") + + li = sub.add_parser("lineage", parents=[common], help="an item and its ancestors") + li.add_argument("graph") + li.add_argument("item", help="item id, unique id prefix, or key") + li.add_argument("--descendants", action="store_true", help="also every item derived from it (all variants)") + li.add_argument("--roots", action="store_true", help="only the root sources it was derived from") + + qy = sub.add_parser("query", parents=[common], help="select stored results (what a store.query node reads)") + qy.add_argument("graph", help="graph file (its project/store is used)") + qy.add_argument("--of", dest="of_graph", help="graph NAME whose runs to read (default: this graph)") + qy.add_argument("--node") + qy.add_argument("--port") + qy.add_argument("--run", default="latest", help="latest | all | ") + qy.add_argument("--where", help="expression, e.g. 'labels.pass_rate >= 0.75'") + qy.add_argument("--label", action="append", default=[], metavar="K=V", help="label equality (JSON value)") + qy.add_argument("--kind") + qy.add_argument("--provenance", choices=["real", "derived", "synthetic"]) + qy.add_argument("--derived-from", help="only descendants of this item (id, prefix or key)") + qy.add_argument("-n", type=int, default=20) + qy.add_argument("--full", action="store_true") + + hs = sub.add_parser("hosts", parents=[common], help="host pools: list hosts, scale, delete") + hs.add_argument("action", choices=["list", "up", "down", "orphans"], + help="list: recorded + provider-listed hosts; up: create hosts (--count); down: delete hosts; " + "orphans: delete provider hosts not recorded by this project") + hs.add_argument("--pool", help="host pool name (default: all pools)") + hs.add_argument("--count", type=int, default=1, help="for `up`: hosts to have") + hs.add_argument("--dir", default=".", help="where to look for pipewright.yaml (default: cwd)") + + ex = sub.add_parser("export", parents=[common], help="write a node's output items to JSONL/JSON") + ex.add_argument("graph") + ex.add_argument("node") + ex.add_argument("-o", "--out", required=True) + ex.add_argument("--port") + ex.add_argument("--fields", help="comma-separated dotted paths, e.g. key,payload.title,labels.score") + ex.add_argument("--run") + + rp = sub.add_parser("report", parents=[common], help="static HTML report with per-edge counts") + rp.add_argument("graph") + rp.add_argument("-o", "--out") + rp.add_argument("--run") + rp.add_argument("--watch", type=float, metavar="SECONDS", help="regenerate every SECONDS until the run ends") + + rv = sub.add_parser("review", parents=[common], help="list parked items or record decisions") + rv.add_argument("graph") + rv.add_argument("node") + rv.add_argument("--approve", nargs="+", metavar="ITEM") + rv.add_argument("--reject", nargs="+", metavar="ITEM") + rv.add_argument("--note", default="") + + gx = sub.add_parser("convert", parents=[common], help="convert a graph (.py builder/.json/.yaml) to .json/.yaml") + gx.add_argument("graph") + gx.add_argument("out") + + sub.add_parser("mcp", parents=[common], help="serve these operations over MCP (stdio; needs the mcp extra)") + + px = sub.add_parser("proxy", parents=[common], help="standalone logging proxy for running an agent by hand") + px.add_argument("--model", required=True, help="model alias") + px.add_argument("--host", default="127.0.0.1") + px.add_argument("--port", type=int, default=0) + px.add_argument("--log-dir", help="append every turn to /.jsonl") + + args = p.parse_args(argv) + try: + return _dispatch(args) + except (PipewrightError, FileNotFoundError) as e: + if args.json: + print(json.dumps({"error": str(e), "type": type(e).__name__})) + else: + print(f"error: {e}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("interrupted; completed work is stored — re-run to resume", file=sys.stderr) + return 130 + + +def _log(args): + if getattr(args, "quiet", False): + return None + return lambda msg: print(msg, file=sys.stderr, flush=True) + + +def _dispatch(args) -> int: + cmd = args.cmd + if cmd == "nodes": + if args.nodes_cmd == "list": + data = ops.nodes_list() + _emit(args, data, lambda d: [print(f"{x['type']:<20} {x['kind']:<8} {x['summary']}") for x in d]) + else: + data = ops.nodes_describe(args.type) + + def human(d): + print(f"{d['type']} ({d['kind']}, v{d['version']})\n\n{d['description']}\n") + print("inputs: ", ", ".join(f"{k}<{v['kind']}>" for k, v in d["inputs"].items()) or "-") + print("outputs:", ", ".join(f"{k}<{v['kind']}>" for k, v in d["outputs"].items()) or "-") + if d["resources"]: + print("resources:", ", ".join(f"{r['type']}:{r['name']}" for r in d["resources"])) + if d["cost_hint"]: + print("cost hint (per item):", d["cost_hint"]) + print("\nparams schema:") + print(json.dumps(d["params_schema"], indent=2)) + print("\nexample (YAML):\n" + d["example_yaml"]) + print("example (Python builder):\n " + d["example_python"]) + + _emit(args, data, human) + return 0 + + if cmd == "check": + data = ops.check_graph(args.graph, args.project) + + def human(d): + print(f"{d['graph']}: {'OK' if d['ok'] else 'FAILED'} ({d['errors']} errors, {d['warnings']} warnings)") + _diag_lines(d["diagnostics"]) + + _emit(args, data, human) + return 0 if data["ok"] else 1 + + if cmd == "patch": + if args.schema: + from .patch import ops_schema + + print(json.dumps(ops_schema(), indent=2)) + return 0 + if not args.graph or not args.ops: + raise ConfigError("usage: pw patch GRAPH OPS (file, '-' or inline JSON)") + if args.ops == "-": + raw = sys.stdin.read() + elif args.ops.lstrip().startswith("["): + raw = args.ops + else: + raw = Path(args.ops).read_text() + try: + op_list = json.loads(raw) + except ValueError as e: + raise ConfigError(f"ops are not valid JSON: {e}") from e + data = ops.patch_graph(args.graph, op_list if isinstance(op_list, list) else [op_list], + dry_run=args.dry_run, force=args.force, project=args.project, out=args.out) + + def human(d): + state = "written to " + d["path"] if d["written"] else ("dry run" if args.dry_run else "NOT written") + print(f"{d['ops']} ops: {'OK' if d['ok'] else 'errors'}; {state}") + _diag_lines([x for x in d["diagnostics"] if x["level"] != "info"]) + + _emit(args, data, human) + return 0 if data["ok"] else 1 + + if cmd == "run": + data = ops.run_graph(args.graph, project=args.project, upto=args.upto, limit=args.limit, force=args.force, + retry_errors=args.retry_errors, run_id=args.run_id, on_log=_log(args), + shard=args.shard, group=args.group) + + def human(d): + print(f"run {d['run_id']}: {d['status']}") + _print_funnel(d["funnel"]) + for u in d["usage"]: + print(f" usage {u['node']}/{u['alias']}: {u['calls']} calls ({u['cached_calls']} cached), " + f"{u['input_tokens']} in / {u['output_tokens']} out tokens" + + (f", ${u['cost_usd']:.4f}" if u["cost_usd"] else "")) + for e in d["errors"]: + print(f" error {e['node']} [{e['category']}] {e['message'][:160]}") + + _emit(args, data, human) + return 0 if data["status"] in ("completed", "completed_with_errors") else 1 + + if cmd == "preview": + data = ops.preview(args.graph, upto=args.upto, n=args.n, project=args.project, on_log=_log(args)) + + def human(d): + print(f"preview {d['run_id']} ({d['status']}) — output of {d['node']}:") + for it in d["items"]: + print(json.dumps(it, indent=2, ensure_ascii=False, default=str)) + for e in d["errors"]: + print(f" error {e['node']} [{e['category']}] {e['message'][:200]}") + + _emit(args, data, human) + return 0 + + if cmd == "status": + data = ops.status(args.graph, args.run, args.project) + + def human(d): + if not d.get("run"): + print(d.get("message")) + return + r = d["run"] + print(f"{d['graph']} run {r['run_id']} ({r['mode']}): {r['status']}") + for nid, s in (r["stats"].get("nodes") or {}).items(): + errs = sum(s["errors"].values()) + print(f" {nid:<22} in={s['in']:<5} ok={s['ok']:<5} cached={s['cached']:<5} errors={errs:<4} " + f"running={s['running']} pending={s['pending']} parked={s['parked']} out={s['out']}") + if r["stats"].get("budget"): + print(" budget:", r["stats"]["budget"]) + for u in d["usage"]: + print(f" usage {u['node']}/{u['alias']}: {u['calls']} calls, {u['input_tokens']} in, " + f"{u['output_tokens']} out") + for e in d["errors"][:10]: + print(f" error {e['node']} [{e['category']}] {e['message'][:160]}") + + _emit(args, data, human) + return 0 + + if cmd == "funnel": + _emit(args, ops.funnel(args.graph, args.run, args.project, group=args.group), _print_funnel) + return 0 + + if cmd == "runs": + data = ops.runs(args.graph, args.project) + _emit(args, data, lambda d: [print(f"{r['run_id']} {r['mode']:<8} {r['status']:<22} " + f"{time.strftime('%F %T', time.localtime(r['started']))}") + for r in d["runs"]]) + return 0 + + if cmd == "items": + data = ops.items(args.graph, args.node, port=args.port, n=args.n, sample=args.sample, run_id=args.run, + errors=args.errors, full=args.full, project=args.project) + _emit(args, data, _print_items) + return 0 + + if cmd == "lineage": + data = ops.lineage(args.graph, args.item, args.project, descendants=args.descendants, roots=args.roots) + + def line(it): + o = it.get("origin") or {} + where = f"{o.get('graph')}/{it['producer']}" if o.get("graph") else str(it["producer"]) + return f"{it['id'][:12]} {it['key']:<30} {it['kind']:<12} by {where} ({it['op']})" + + def human(d): + for title in ("lineage", "roots", "descendants"): + if title in d: + print(f"{title}:") + for it in d[title]: + print(" " + line(it)) + + _emit(args, data, human) + return 0 + + if cmd == "query": + labels = {} + for kv in args.label: + k, _, v = kv.partition("=") + try: + labels[k] = json.loads(v) + except ValueError: + labels[k] = v + data = ops.query(args.graph, node=args.node, port=args.port, run=args.run, of_graph=args.of_graph, + where=args.where, labels=labels or None, kind=args.kind, provenance=args.provenance, + derived_from=args.derived_from, n=args.n, full=args.full, project=args.project) + + def human(d): + print(f"{d['total']} items from {d['graph']} runs {d['runs']} (showing {len(d['items'])})") + for it in d["items"]: + print(json.dumps(it, ensure_ascii=False, default=str)) + print("as a node: " + json.dumps(d["as_node"])) + + _emit(args, data, human) + return 0 + + if cmd == "hosts": + data = ops.hosts(args.action, pool=args.pool, count=args.count, project=args.project, start=args.dir) + + def human(d): + for h in d.get("hosts", []): + print(f" {h.get('pool', ''):<10} {h.get('id', ''):<24} {h.get('state', ''):<10} " + f"{h.get('docker_host', '')} labels={sorted(h.get('labels', []))}") + for k in ("created", "deleted", "errors"): + if d.get(k): + print(f"{k}: {d[k]}") + + _emit(args, data, human) + return 0 + + if cmd == "export": + data = ops.export(args.graph, args.node, args.out, port=args.port, run_id=args.run, + fields=args.fields.split(",") if args.fields else None, project=args.project) + _emit(args, data, lambda d: print(f"wrote {d['rows']} rows to {d['path']}")) + return 0 + + if cmd == "report": + if args.watch: + while True: + data = ops.report(args.graph, args.out, args.run, args.project, refresh=int(max(2, args.watch))) + st = ops.status(args.graph, data["run_id"], args.project) + if st["run"]["status"] != "running": + data = ops.report(args.graph, args.out, args.run, args.project) + break + time.sleep(args.watch) + else: + data = ops.report(args.graph, args.out, args.run, args.project) + _emit(args, data, lambda d: print(d["path"])) + return 0 + + if cmd == "review": + if args.approve or args.reject: + data = ops.review_decide(args.graph, args.node, args.approve or args.reject, + "approved" if args.approve else "rejected", args.note, args.project) + _emit(args, data, lambda d: print(f"{d['decision']}: {len(d['items'])} items; {d['next']}")) + else: + data = ops.review_list(args.graph, args.node, project=args.project) + + def human(d): + print(f"{len(d['parked'])} parked at {d['node']}: {d['instructions']}") + for it in d["parked"]: + print(json.dumps(it, indent=2, ensure_ascii=False, default=str)) + + _emit(args, data, human) + return 0 + + if cmd == "convert": + data = ops.export_graph(args.graph, args.out) + _emit(args, data, lambda d: print(f"wrote {d['written']} ({d['nodes']} nodes)")) + return 0 + + if cmd == "proxy": + import asyncio + + def ready(info): + if args.json: + print(json.dumps(info), flush=True) + else: + print(f"OPENAI_BASE_URL={info['base_url']}\nOPENAI_API_KEY={info['api_key']}\n" + f"model: {info['model']} (usage recorded as run {info['run_id']}; Ctrl-C to stop)", flush=True) + + asyncio.run(ops.serve_proxy(args.model, project=args.project, host=args.host, port=args.port, + log_dir=args.log_dir, on_ready=ready)) + return 0 + + if cmd == "mcp": + from .mcp_server import serve + + serve() + return 0 + raise ConfigError(f"unknown command {cmd}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/pipewright/contrib/__init__.py b/src/pipewright/contrib/__init__.py new file mode 100644 index 0000000..3074409 --- /dev/null +++ b/src/pipewright/contrib/__init__.py @@ -0,0 +1 @@ +"""Optional plugins shipped with pipewright (loaded through entry points).""" diff --git a/src/pipewright/contrib/boat.py b/src/pipewright/contrib/boat.py new file mode 100644 index 0000000..fddb0e2 --- /dev/null +++ b/src/pipewright/contrib/boat.py @@ -0,0 +1,136 @@ +"""boat.dev VMs as a host pool (`type: boat`) — an optional plugin, registered through +the `pipewright.hosts` entry point (`pip install pipewright[boat]`; no extra deps). + + hosts: + boat: + type: boat + api_key: {file: ~/.config/deepswe-eval/secrets, var: BOAT_API_KEY} + vm_type: large # 8 vCPU / 16 GB (capacity defaults to that) + ttl: 3600 # extended by the pool while needed + min: 0 + max: 2 + idle_shutdown: 300 + docker_kvm_runtime: true # every container gets /dev/kvm (mode 0666) + reserve: {cpus: 0.5, memory: 1g} + budget: {hours: 4} + +API (https://boat.dev/api/v1): POST /sandboxes {ttlSeconds, type, name} → poll +GET /sandboxes/{id} until ready → POST /sandboxes/{id}/sshkey {key} → {sshEndpoint, +hostKey, sshUser}; PATCH /sandboxes/{id} {ttlSeconds} extends; DELETE /sandboxes/{id} +with header `X-Ascii-Confirm-Delete: `; GET /sandboxes lists (orphan cleanup by +name prefix). +""" + +from __future__ import annotations + +import asyncio +import time +from datetime import datetime +from pathlib import Path + +from ..errors import InfraError +from ..hosts.base import Host +from ..hosts.vmapi import VMApiHostProvider +from ..registry import register_host_provider + +READY = ("ready", "idle", "running") +DEAD = ("error", "failed", "deleted", "archived", "terminated") +SHAPES = {"large": {"cpus": 8, "memory": "16g"}} + + +def _expiry(sandbox: dict, fallback: float) -> float: + v = sandbox.get("archiveAfter") or sandbox.get("expiresAt") + if isinstance(v, (int, float)): + return float(v) / (1000 if v > 1e11 else 1) + if isinstance(v, str): + try: + return datetime.fromisoformat(v.replace("Z", "+00:00")).timestamp() + except ValueError: + pass + return fallback + + +class BoatHosts(VMApiHostProvider): + type = "boat" + api_base = "https://boat.dev/api/v1" + name_prefix = "pw" + supports_kvm = True + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + self.vm_type = config.get("vm_type", "large") + + def capacity(self): + from ..hosts.base import Resources + + cap = self.config.get("capacity") or SHAPES.get(self.vm_type) + return Resources.parse(cap) if cap else None + + async def create(self, host_id: str, state_dir: Path) -> Host: + pub = self.public_key() + vm_name = f"{self.prefix}-{host_id}" + d = await self.request("POST", "/sandboxes", json={"ttlSeconds": self.ttl, "type": self.vm_type, + "name": vm_name}) + vm = (d or {}).get("sandbox") or d or {} + vm_id = vm.get("id") + if not vm_id: + raise InfraError(f"boat: create returned no sandbox id: {str(d)[:300]}") + (state_dir / "vm_id").write_text(vm_id) # so a crashed process can still clean up + try: + deadline = time.time() + float(self.config.get("boot_timeout", 900)) + while True: + vm = ((await self.request("GET", f"/sandboxes/{vm_id}")) or {}).get("sandbox") or {} + st = str(vm.get("state", "")).lower() + if st in READY: + break + if st in DEAD or time.time() > deadline: + raise InfraError(f"boat: VM {vm_id} did not become ready (state {st!r})") + await asyncio.sleep(5) + ssh = await self.request("POST", f"/sandboxes/{vm_id}/sshkey", json={"key": pub}) or {} + endpoint = ssh.get("sshEndpoint") or "" + hostname, _, port = endpoint.rpartition(":") + if not hostname: + raise InfraError(f"boat: no ssh endpoint for {vm_id}: {str(ssh)[:200]}") + alias = f"pw-{host_id}" + cfg = self.write_ssh_config(state_dir, alias, hostname, int(port or 22), ssh.get("sshUser", "user"), + ssh.get("hostKey"), vm_id) + host = self._host(host_id, state_dir, alias, cfg, vm_id=vm_id, vm_name=vm_name, type=self.vm_type) + host.expires = _expiry(vm, time.time() + self.ttl) + return host + except BaseException: + await asyncio.shield(self._delete_id(vm_id)) + raise + + async def _delete_id(self, vm_id: str) -> None: + await self.request("DELETE", f"/sandboxes/{vm_id}", headers={"X-Ascii-Confirm-Delete": vm_id}, + ok=(200, 202, 204, 404)) + + async def delete(self, host: Host) -> None: + vm_id = host.meta.get("vm_id") + if vm_id: + await self._delete_id(vm_id) + + async def extend(self, host: Host, seconds: float) -> float | None: + d = await self.request("PATCH", f"/sandboxes/{host.meta['vm_id']}", json={"ttlSeconds": int(seconds)}) + vm = (d or {}).get("sandbox") or {} + return _expiry(vm, time.time() + seconds) + + async def alive(self, host: Host) -> bool: + try: + vm = ((await self.request("GET", f"/sandboxes/{host.meta['vm_id']}", retries=1)) or {}).get("sandbox") or {} + except InfraError: + return False + return str(vm.get("state", "")).lower() in READY + + async def list_remote(self) -> list[dict]: + d = await self.request("GET", "/sandboxes") + items = d.get("sandboxes", d.get("items", [])) if isinstance(d, dict) else (d or []) + return [{"id": v.get("id"), "name": v.get("name"), "state": v.get("state"), + "expires": v.get("archiveAfter")} + for v in items if str(v.get("name", "")).startswith(self.prefix + "-")] + + async def delete_remote(self, remote: dict) -> None: + await self._delete_id(remote["id"]) + + +register_host_provider("boat", BoatHosts) diff --git a/src/pipewright/engine.py b/src/pipewright/engine.py new file mode 100644 index 0000000..00279df --- /dev/null +++ b/src/pipewright/engine.py @@ -0,0 +1,645 @@ +"""The executor: streams items through the graph with per-item memoization. + +Every node runs as an asyncio task with an inbox. Items are processed as they arrive +(pipelined, not stage by stage), each in its own task; how many run at once is +decided only by resource leases (provider rate limits, sandbox slots, budgets), never +by a worker count. Deeper nodes get lease priority so finished items reach the end. + +Memoization: a node's result for an input is stored under +(node signature, input item id), where the signature hashes the node type, its +version, its params and the identity of the resources it resolves (e.g. which +concrete model an alias points to). Re-running a graph replays stored results and +only computes what is new or invalidated: new input items, nodes whose params +changed, and everything downstream of an item whose content changed. Transient +failures (provider/infra) are not memoized, so the next run retries them; +deterministic node errors are memoized (use --retry-errors to recompute them). + +Every run (including replays) records which items flowed over which edge, which is +what `pw funnel`, `pw items` and the HTML report read. +""" + +from __future__ import annotations + +import asyncio +import logging +import random +import time +import uuid +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import Any, AsyncIterator, Callable + +from .errors import BudgetExceeded, ConfigError, ItemError, NodeError, backoff_scale, classify +from .graph import GraphSpec, NodeSpec, RetryPolicy +from .hashing import digest +from .items import ArtifactRef, Item +from .nodes.base import NodeType, Port +from .project import Project +from .registry import registry +from .scheduler import BudgetTracker +from .store import Store + +log = logging.getLogger("pipewright") +CLOSE = object() + + +@dataclass +class RunOptions: + upto: str | None = None + limit: int | None = None + mode: str = "run" # run | preview + run_id: str | None = None + force: set[str] = field(default_factory=set) + retry_errors: bool = False + shard: tuple[int, int] | None = None + """(index, count): this worker processes only source items whose key hashes to `index` + (mod count). Several workers (processes/machines on a shared store) split a run; + sinks are skipped in shard runs — a final unsharded run replays the memoized results + and writes them.""" + group: str | None = None + """Run group label (e.g. one id for all shards of a run); `pw funnel --group` sums them.""" + + +def shard_of(key: str, count: int) -> int: + return int(digest(key, 8), 16) % count + + +@dataclass +class NodeInst: + id: str + spec: NodeSpec + cls: type[NodeType] + params: Any + obj: NodeType + sig: str + depth: int + in_ports: dict[str, Port] + out_ports: dict[str, Port] + policy: RetryPolicy + stats: dict = field(default_factory=dict) + + @property + def kind(self) -> str: + return self.cls.kind + + @property + def op(self) -> str: + return f"{self.cls.name}@{self.cls.version}" + + +def instantiate(node_id: str, spec: NodeSpec, project: Project) -> tuple[type[NodeType], Any]: + cls = registry.node_types.get(spec.type) + if cls is None: + raise ConfigError(f"node {node_id}: unknown node type {spec.type!r}") + try: + params = cls.Params.model_validate(spec.params) + except Exception as e: + raise ConfigError(f"node {node_id}: invalid params: {e}") from e + return cls, params + + +def node_signature(cls: type[NodeType], params: Any, project: Project) -> str: + return digest({"type": cls.name, "version": cls.version, "params": params.model_dump(mode="json"), + "identity": cls.identity(params, project)}) + + +class NodeContext: + """What a node may use while processing (one per item).""" + + def __init__(self, engine: "Engine", inst: NodeInst, item: Item | None = None): + self.engine, self.inst, self.item = engine, inst, item + self.node_id = inst.id + self.run_id = engine.run_id + self.project = engine.project + self.store = engine.store + self.limit = engine.opts.limit + self.priority = -inst.depth + self.refresh_cache = False + """Set when recomputing a memoized error: model calls skip request-cache reads.""" + + # ------------------------------------------------------------------ resources + def model(self, alias: str, *, cache_salt: str | None = None): + from .models.base import ModelClient + + cfg = self.project.config.models.get(alias) + if cfg is None: + raise ConfigError(f"unknown model alias {alias!r}; configured: {sorted(self.project.config.models)}") + provider = self.project.provider(cfg.provider) + item_id = self.item.id if self.item else None + + def on_usage(alias_name, provider_name, model, usage, cached): + self.store.record_usage(self.run_id, self.node_id, item_id, alias_name, provider_name, model, + usage.input_tokens, usage.output_tokens, usage.cost_usd, cached) + + return ModelClient(alias, cfg, provider, store=self.store, on_usage=on_usage, budget=self.engine.budget, + priority=self.priority, cache_salt=cache_salt, read_cache=not self.refresh_cache) + + @asynccontextmanager + async def sandbox(self, pool: str) -> AsyncIterator[Any]: + provider = self.project.sandbox_provider(pool) + async with provider.lease(self.priority, self.engine.budget) as sb: + yield sb + + def harness(self, name: str): + return self.project.harness(name) + + def count(self, name: str, n: float = 1) -> None: + """Spend a named counter budget (`budgets.counters` in the project file), e.g. + `ctx.count(f"rollouts.{alias}")` before an expensive call. Over the limit this raises + BudgetExceeded: the item is recorded as pending (resumed by a later run) and other + items/nodes continue.""" + self.engine.budget.count(name, n) + + def harness_context(self, cache_salt: str | None = None): + from .harness.base import HarnessContext + + return HarnessContext(lambda alias, salt: self.model(alias, cache_salt=salt), self.engine.get_proxy, + cache_salt=cache_salt) + + # ------------------------------------------------------------------ data + def put_blob(self, data: bytes | str, media_type: str = "application/octet-stream", + name: str | None = None) -> ArtifactRef: + return self.store.put_blob(data.encode() if isinstance(data, str) else data, media_type, name) + + def get_blob(self, ref: ArtifactRef | str) -> bytes: + return self.store.get_blob(ref) + + def resolve_path(self, p: str): + return self.project.resolve_path(p) + + def log(self, msg: str) -> None: + self.engine.emit_log(f"[{self.node_id}] {msg}") + + def prior_items(self, graph: str, node: str, port: str | None = None, run_id: str | None = None) -> list[Item]: + """Items that flowed out of `node` in a previous run (default: the latest + completed run of `graph`). This is how feedback loops across runs work.""" + run = self.store.run(run_id) if run_id else None + if run is None: + for r in self.store.runs(graph, limit=50): + if r["status"] in ("completed", "completed_with_errors") and r["run_id"] != self.run_id: + run = r + break + if run is None: + return [] + return self.store.get_items(self.store.flow_items(run["run_id"], node, port)) + + async def run_inner(self, name: str, type_name: str, params: dict, item: Item) -> list[tuple[str, Item]]: + """Run another node type on one item, memoized like a graph node (used by + composite node types such as retry.loop).""" + return await self.engine.run_inner(self.inst, name, type_name, params, item) + + +class Engine: + def __init__(self, spec: GraphSpec, project: Project, store: Store | None = None, + on_log: Callable[[str], None] | None = None): + from .imports import expand_imports + + self.project = project + registry.import_plugins(spec.plugins) + self.source_spec = spec + try: + self.spec = expand_imports(spec, project, strict=False) + except ConfigError: + self.spec = spec # reported by check() in _plan + self.store = store or Store(project.store_dir) + self.on_log = on_log + self.opts = RunOptions() + self.run_id = "" + self.budget = BudgetTracker(**project.config.budgets.model_dump()) + self.insts: dict[str, NodeInst] = {} + self.inbox: dict[str, asyncio.Queue] = {} + self.expected_closes: dict[str, int] = {} + self.downstream: dict[str, dict[str, list[tuple[str, str]]]] = {} + self._proxy = None + self._inner: dict[str, tuple[NodeType, str, type[NodeType]]] = {} + self.status = "running" + + def emit_log(self, msg: str) -> None: + if self.on_log: + self.on_log(msg) + log.info(msg) + + async def get_proxy(self): + if self._proxy is None: + from .models.proxy import LoggingProxy + + self._proxy = LoggingProxy() + return self._proxy + + # ------------------------------------------------------------------ setup + def _plan(self, opts: RunOptions) -> list[str]: + from .check import check + + diags = check(self.spec, self.project) + errors = [d for d in diags if d.level == "error"] + if errors: + raise ConfigError("graph has errors:\n" + "\n".join(f" {d.format()}" for d in errors)) + order = self.spec.topo_order() + if opts.upto: + if opts.upto not in self.spec.nodes: + raise ConfigError(f"--upto: unknown node {opts.upto!r}") + keep = self.spec.ancestors(opts.upto) | {opts.upto} + order = [n for n in order if n in keep] + depth: dict[str, int] = {} + for nid in order: + ups = [u for u in self.spec.upstream(nid) if u in depth] + depth[nid] = 1 + max((depth[u] for u in ups), default=-1) + for nid in order: + spec = self.spec.nodes[nid] + cls, params = instantiate(nid, spec, self.project) + self.insts[nid] = NodeInst( + id=nid, spec=spec, cls=cls, params=params, obj=cls(nid, params), + sig=node_signature(cls, params, self.project), depth=depth[nid], + in_ports=cls.input_ports(params), out_ports=cls.output_ports(params), + policy=spec.retries or RetryPolicy(), + stats={"in": 0, "ok": 0, "cached": 0, "errors": {}, "out": {}, "pending": 0, "parked": 0, + "running": 0}, + ) + self.inbox[nid] = asyncio.Queue() + self.downstream[nid] = {} + self.expected_closes[nid] = 0 + for inst in self.insts.values(): + if inst.cls.cacheable and inst.id not in opts.force: + self.store.memo_preload(inst.sig) + for src, sport, dst, dport in self.spec.edges(): + if src in self.insts and dst in self.insts: + self.downstream[src].setdefault(sport, []).append((dst, dport)) + self.expected_closes[dst] += 1 + return order + + # ------------------------------------------------------------------ run + async def run(self, opts: RunOptions | None = None) -> dict: + self.opts = opts = opts or RunOptions() + order = self._plan(opts) + self.run_id = opts.run_id or f"{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}" + self.store.begin_run(self.run_id, self.spec.name, self.spec.hash(), opts.mode, + {"upto": opts.upto, "limit": opts.limit, "nodes": order, + "shard": list(opts.shard) if opts.shard else None, "group": opts.group, + "imports": {a: i.model_dump() for a, i in self.spec.imports.items()}}) + self.store.current_run = self.run_id + started = time.time() + self.emit_log(f"run {self.run_id}: {len(order)} nodes" + (f" upto {opts.upto}" if opts.upto else "") + + (f" limit {opts.limit}" if opts.limit else "")) + flusher = asyncio.create_task(self._flush_loop()) + tasks = [asyncio.create_task(self._run_node(self.insts[n]), name=f"node:{n}") for n in order] + try: + await asyncio.gather(*tasks) + errs = sum(sum(i.stats["errors"].values()) for i in self.insts.values()) + pending = sum(i.stats["pending"] for i in self.insts.values()) + if self.budget.exceeded: + self.status = "budget_exceeded" + elif errs or pending: + self.status = "completed_with_errors" + else: + self.status = "completed" + except asyncio.CancelledError: + self.status = "cancelled" + for t in tasks: + t.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + raise + except BaseException: + self.status = "failed" + for t in tasks: + t.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + raise + finally: + flusher.cancel() + await self._shutdown() # drains sandboxes and host pools (their final stats go into the run) + self._flush(final=True, started=started) + self.emit_log(f"run {self.run_id}: {self.status} in {time.time() - started:.1f}s") + return self.summary() + + async def _shutdown(self) -> None: + try: + await asyncio.shield(self.project.aclose()) + except Exception as e: # pragma: no cover + log.warning("shutdown: %s", e) + if self._proxy is not None: + await self._proxy.aclose() + + def stats(self) -> dict: + return {"nodes": {n: i.stats for n, i in self.insts.items()}, "budget": self.budget.snapshot(), + "rate": {name: p.limiter.snapshot() for name, p in self.project._providers.items()}, + "sandboxes": {name: s.stats for name, s in self.project._sandboxes.items()}, + "hosts": {name: hp.snapshot() for name, hp in self.project._host_pools.items()}} + + def _flush(self, final: bool = False, started: float | None = None) -> None: + st = self.stats() + if final and started is not None: + st["duration_s"] = round(time.time() - started, 2) + self.store.update_run(self.run_id, stats=st, status=self.status if final else None, finished=final) + + async def _flush_loop(self) -> None: + while True: + await asyncio.sleep(1.0) + self._flush() + + def summary(self) -> dict: + from .ops import funnel_for_run + + return {"run_id": self.run_id, "status": self.status, "graph": self.spec.name, + "funnel": funnel_for_run(self.spec, self.store, self.run_id), + "usage": self.store.usage_summary(self.run_id), "budget": self.budget.snapshot(), + "errors": self.store.errors(self.run_id, limit=10)} + + # ------------------------------------------------------------------ flow + def _emit(self, inst: NodeInst, port: str, item: Item) -> None: + self.store.put_item(item) + self.store.record_flow(self.run_id, inst.id, port, item.id) + inst.stats["out"][port] = inst.stats["out"].get(port, 0) + 1 + for dst, dport in self.downstream[inst.id].get(port, []): + self.inbox[dst].put_nowait((dport, item)) + + def _close(self, inst: NodeInst) -> None: + for edges in self.downstream[inst.id].values(): + for dst, _ in edges: + self.inbox[dst].put_nowait(CLOSE) + + async def _inputs(self, inst: NodeInst) -> AsyncIterator[tuple[str, Item]]: + closes, seen = 0, set() + while closes < self.expected_closes[inst.id]: + msg = await self.inbox[inst.id].get() + if msg is CLOSE: + closes += 1 + continue + port, item = msg + if (port, item.id) in seen: + continue + seen.add((port, item.id)) + yield port, item + + async def _run_node(self, inst: NodeInst) -> None: + try: + ctx = NodeContext(self, inst) + try: + await inst.obj.setup(ctx) + except Exception as e: + err = classify(e) + self._record_error(inst, "__setup__", err) + async for _ in self._inputs(inst): + pass + return + if inst.kind == "sink" and self.opts.shard: + async for _ in self._inputs(inst): + inst.stats["in"] += 1 + self.store.record_event(self.run_id, inst.id, "__sink__", "skipped", False) + elif inst.kind == "source": + await self._run_source(inst) + elif inst.kind in ("join", "sink"): + await self._run_barrier(inst) + else: + pending: set[asyncio.Task] = set() + async for _port, item in self._inputs(inst): + inst.stats["in"] += 1 + t = asyncio.create_task(self._process_item(inst, item)) + pending.add(t) + t.add_done_callback(pending.discard) + if pending: + await asyncio.gather(*list(pending)) + finally: + self._close(inst) + + async def _run_source(self, inst: NodeInst) -> None: + key = f"__source__:{self.opts.limit}" + if inst.cls.cacheable and inst.id not in self.opts.force: + memo = self.store.memo_get(inst.sig, key) + if memo and memo.status == "ok": + for port, ids in memo.outputs.items(): + for item in self.store.get_items(ids): + if self._in_shard(item): + self._emit(inst, port, item) + inst.stats["cached"] += 1 + inst.stats["ok"] += 1 + self.store.record_event(self.run_id, inst.id, key, "ok", True) + return + ctx = NodeContext(self, inst) + outputs: dict[str, list[str]] = {} + start = time.time() + n = 0 + try: + agen = inst.obj.generate(ctx) + async for item in agen: + if self.opts.limit is not None and n >= self.opts.limit: + await agen.aclose() + break + port = "out" + if isinstance(item, tuple): + port, item = item + if item.producer is None: + item = item.stamped(inst.id, inst.op) + outputs.setdefault(port, []).append(item.id) + if self._in_shard(item): + self._emit(inst, port, item) + n += 1 + except asyncio.CancelledError: + raise + except BudgetExceeded as e: + inst.stats["pending"] += 1 + self.store.record_event(self.run_id, inst.id, key, "pending", False, {"message": str(e)}) + return + except Exception as e: + self._record_error(inst, key, classify(e)) + return + inst.stats["ok"] += 1 + if inst.cls.cacheable: + self.store.memo_put(inst.sig, key, inst.id, "ok", outputs, None, self.run_id, time.time() - start) + self.store.record_event(self.run_id, inst.id, key, "ok", False) + + def _in_shard(self, item: Item) -> bool: + sh = self.opts.shard + return sh is None or shard_of(item.key, sh[1]) == sh[0] + + async def _run_barrier(self, inst: NodeInst) -> None: + inputs: dict[str, list[Item]] = {p: [] for p in inst.in_ports} + async for port, item in self._inputs(inst): + inst.stats["in"] += 1 + inputs.setdefault(port, []).append(item) + for p in inputs: + inputs[p].sort(key=lambda i: (i.key, i.id)) + ctx = NodeContext(self, inst) + if inst.kind == "sink": + try: + result = await inst.obj.write([i for p in inputs for i in inputs[p]], ctx) + inst.stats["ok"] += 1 + inst.stats["result"] = result + self.store.record_event(self.run_id, inst.id, "__sink__", "ok", False) + except Exception as e: + self._record_error(inst, "__sink__", classify(e)) + return + key = digest({p: [i.id for i in v] for p, v in inputs.items()}) + await self._execute(inst, key, None, lambda: inst.obj.join(inputs, ctx), ctx=ctx) + + async def _process_item(self, inst: NodeInst, item: Item) -> None: + if inst.kind == "review": + await self._review(inst, item) + return + ctx = NodeContext(self, inst, item) + await self._execute(inst, item.id, item, lambda: inst.obj.process(item, ctx), ctx=ctx) + + async def _review(self, inst: NodeInst, item: Item) -> None: + ctx = NodeContext(self, inst, item) + try: + auto = await inst.obj.process(item, ctx) + except Exception as e: + self._record_error(inst, item.id, classify(e)) + return + decision = auto or (self.store.get_review(inst.id, item.id) or (None, ""))[0] + if decision in ("approved", "rejected"): + inst.stats["ok"] += 1 + self._emit(inst, decision, item) + self.store.record_event(self.run_id, inst.id, item.id, "ok", False) + else: + inst.stats["parked"] += 1 + self.store.record_flow(self.run_id, inst.id, "__parked__", item.id) + self.store.record_event(self.run_id, inst.id, item.id, "parked", False) + + async def _execute(self, inst: NodeInst, key: str, item: Item | None, call: Callable, + ctx: NodeContext | None = None) -> None: + if inst.cls.cacheable and inst.id not in self.opts.force: + memo = self.store.memo_get(inst.sig, key) + if memo is not None and memo.status == "error" and self.opts.retry_errors and ctx is not None: + ctx.refresh_cache = True # a fresh sample, not a replay of the cached bad answer + if memo is not None and (memo.status == "ok" or not self.opts.retry_errors): + if memo.status == "ok": + for port, ids in memo.outputs.items(): + for out in self.store.get_items(ids): + self._emit(inst, port, out) + inst.stats["ok"] += 1 + inst.stats["cached"] += 1 + self.store.record_event(self.run_id, inst.id, key, "ok", True) + else: + cat = (memo.error or {}).get("category", "node") + inst.stats["errors"][cat] = inst.stats["errors"].get(cat, 0) + 1 + inst.stats["cached"] += 1 + self.store.record_event(self.run_id, inst.id, key, "error", True, memo.error) + return + attempts: dict[str, int] = {} + start = time.time() + while True: + try: + self.budget.check() + except BudgetExceeded as e: + inst.stats["pending"] += 1 + self.store.record_event(self.run_id, inst.id, key, "pending", False, {"message": str(e)}) + return + inst.stats["running"] += 1 + try: + coro = call() + result = await (asyncio.wait_for(coro, inst.spec.timeout) if inst.spec.timeout else coro) + outputs = self._normalize(inst, item, result) + break + except asyncio.CancelledError: + raise + except BudgetExceeded as e: + inst.stats["pending"] += 1 + self.store.record_event(self.run_id, inst.id, key, "pending", False, {"message": str(e)}) + return + except Exception as e: + err = classify(e) + n = attempts[err.category] = attempts.get(err.category, 0) + 1 + allowed = getattr(inst.policy, err.category, 0) + if err.retryable and n <= allowed: + self.emit_log(f"[{inst.id}] retry {n}/{allowed} ({err.category}): {str(err)[:160]}") + await asyncio.sleep(min(30.0, (2.0 if err.category == "provider" else 1.0) * n) + * (0.5 + random.random()) * backoff_scale()) + continue + self._record_error(inst, key, err, memoize=not err.retryable, duration=time.time() - start) + return + finally: + inst.stats["running"] -= 1 + stored: dict[str, list[str]] = {} + final: list[tuple[str, Item]] = [] + for port, out in outputs: + if item is None or out.id != item.id: + if out.producer is None: + out = out.stamped(inst.id, inst.op) + self.store.put_item(out) + stored.setdefault(port, []).append(out.id) + final.append((port, out)) + if inst.cls.cacheable: + self.store.memo_put(inst.sig, key, inst.id, "ok", stored, None, self.run_id, time.time() - start) + inst.stats["ok"] += 1 + self.store.record_event(self.run_id, inst.id, key, "ok", False) + for port, out in final: + self._emit(inst, port, out) + + def _record_error(self, inst: NodeInst, key: str, err: ItemError, memoize: bool = False, + duration: float = 0.0) -> None: + d = err.to_dict() + inst.stats["errors"][err.category] = inst.stats["errors"].get(err.category, 0) + 1 + self.store.record_event(self.run_id, inst.id, key, "error", False, d) + if memoize and inst.cls.cacheable and key and not key.startswith("__"): + self.store.memo_put(inst.sig, key, inst.id, "error", {}, d, self.run_id, duration) + self.emit_log(f"[{inst.id}] error ({err.category}) on {key[:12]}: {str(err)[:200]}") + + def _normalize(self, inst: NodeInst, item: Item | None, res: Any) -> list[tuple[str, Item]]: + return normalize_result(inst.kind, inst.id, inst.out_ports, item, res) + + # ------------------------------------------------------------------ inner nodes + async def run_inner(self, outer: NodeInst, name: str, type_name: str, params: dict, + item: Item) -> list[tuple[str, Item]]: + ck = digest({"t": type_name, "p": params}) + if ck not in self._inner: + cls = registry.node_types.get(type_name) + if cls is None: + raise ConfigError(f"{outer.id}: unknown inner node type {type_name!r}") + p = cls.Params.model_validate(params) + self._inner[ck] = (cls(f"{outer.id}/{name}", p), node_signature(cls, p, self.project), cls) + obj, sig, cls = self._inner[ck] + inner_id = f"{outer.id}/{name}" + if cls.cacheable: + memo = self.store.memo_get(sig, item.id) + if memo is not None and memo.status == "ok": + return [(port, out) for port, ids in memo.outputs.items() for out in self.store.get_items(ids)] + fake_inst = NodeInst(id=inner_id, spec=NodeSpec(type=type_name), cls=cls, params=obj.params, obj=obj, + sig=sig, depth=outer.depth, in_ports=cls.input_ports(obj.params), + out_ports=cls.output_ports(obj.params), policy=outer.policy) + ctx = NodeContext(self, fake_inst, item) + start = time.time() + res = await obj.process(item, ctx) + outs = [] + stored: dict[str, list[str]] = {} + for port, out in normalize_result(cls.kind, inner_id, fake_inst.out_ports, item, res): + if out.id != item.id and out.producer is None: + out = out.stamped(inner_id, f"{cls.name}@{cls.version}") + self.store.put_item(out) + stored.setdefault(port, []).append(out.id) + outs.append((port, out)) + if cls.cacheable: + self.store.memo_put(sig, item.id, inner_id, "ok", stored, None, self.run_id, time.time() - start) + return outs + + +def normalize_result(kind: str, node_id: str, out_ports: dict[str, Port], item: Item | None, + res: Any) -> list[tuple[str, Item]]: + """Turn what a node returned into (port, item) pairs, per its kind.""" + pairs: list[tuple[str, Item]] + if isinstance(res, dict) and res and all(isinstance(v, list) for v in res.values()): + pairs = [(p, x) for p, v in res.items() for x in v] + elif kind == "map": + if not isinstance(res, Item): + raise NodeError(f"{node_id}: map node must return an Item, got {type(res).__name__}") + pairs = [("out", res)] + elif kind in ("flatmap", "join"): + res = list(res or []) + pairs = [x if isinstance(x, tuple) else ("out", x) for x in res] + elif kind == "filter": + pairs = [("out" if res else "rejected", item)] # type: ignore[list-item] + else: # route, retry, review + if res is None: + pairs = [] + elif isinstance(res, str): + pairs = [(res, item)] # type: ignore[list-item] + elif isinstance(res, tuple) and len(res) == 2 and isinstance(res[1], Item): + pairs = [res] + else: + pairs = [(x, item) if isinstance(x, str) else x for x in res] # type: ignore[misc] + for port, x in pairs: + if not isinstance(x, Item): + raise NodeError(f"{node_id}: output on {port!r} is not an Item ({type(x).__name__})") + if port not in out_ports: + raise NodeError(f"{node_id}: emitted on unknown port {port!r}; ports: {sorted(out_ports)}") + return pairs + diff --git a/src/pipewright/errors.py b/src/pipewright/errors.py new file mode 100644 index 0000000..f5046da --- /dev/null +++ b/src/pipewright/errors.py @@ -0,0 +1,107 @@ +"""Error classification. + +Every failure while processing an item is attributed to one class, which decides +whether it is retried in this run, recorded as a final result, or left pending for +the next run: + +- ProviderError: a model provider call failed (429, 5xx, transport, in-stream error, + or an agent whose final model call failed). Transient; retried. +- InfraError: sandbox/host/harness infrastructure failed (create, exec transport, + timeout of the infrastructure itself). Transient; retried. +- NodeError: the node's own logic rejected the item (bad LLM output after repair + attempts, invalid params at run time). Deterministic; memoized as the result. +- BudgetExceeded: a run budget ran out; the item stays pending. +""" + +from __future__ import annotations + +import os + + +def backoff_scale() -> float: + """Multiplier for retry backoff sleeps (PW_BACKOFF_SCALE; tests set it near 0).""" + try: + return float(os.environ.get("PW_BACKOFF_SCALE", "1")) + except ValueError: + return 1.0 + + +class PipewrightError(Exception): + """Base class.""" + + +class ConfigError(PipewrightError): + """The graph or project configuration is invalid.""" + + +class ItemError(PipewrightError): + """Base for failures attributed to processing one item.""" + + category: str = "node" + retryable: bool = False + + def __init__(self, message: str = "", *, detail: dict | None = None): + super().__init__(message) + self.detail = detail or {} + + def to_dict(self) -> dict: + return { + "category": self.category, + "type": type(self).__name__, + "message": str(self)[:2000], + "retryable": self.retryable, + **({"detail": self.detail} if self.detail else {}), + } + + +class ProviderError(ItemError): + category = "provider" + retryable = True + + def __init__(self, message: str = "", *, status: int | None = None, retry_after: float | None = None, + detail: dict | None = None): + super().__init__(message, detail=detail) + self.status = status + self.retry_after = retry_after + # 4xx other than 408/409/429 are deterministic request errors + if status is not None and 400 <= status < 500 and status not in (408, 409, 429): + self.retryable = False + + def to_dict(self) -> dict: + d = super().to_dict() + d["status"] = self.status + return d + + +class InfraError(ItemError): + category = "infra" + retryable = True + + +class NodeError(ItemError): + category = "node" + retryable = False + + +class BudgetExceeded(PipewrightError): + """A run budget (USD, VM hours, tokens) is exhausted.""" + + +def classify(exc: BaseException) -> ItemError: + """Map an arbitrary exception to an ItemError.""" + import asyncio + + if isinstance(exc, ItemError): + return exc + if isinstance(exc, (asyncio.TimeoutError, TimeoutError)): + return InfraError(f"timed out: {exc}" if str(exc) else "timed out") + try: + import httpx + + if isinstance(exc, httpx.TransportError): + return ProviderError(f"transport: {type(exc).__name__}: {exc}") + except ImportError: # pragma: no cover + pass + if isinstance(exc, (ConnectionError, OSError)) and not isinstance(exc, FileNotFoundError): + return InfraError(f"{type(exc).__name__}: {exc}") + return NodeError(f"{type(exc).__name__}: {exc}") diff --git a/src/pipewright/expr.py b/src/pipewright/expr.py new file mode 100644 index 0000000..dfba8ac --- /dev/null +++ b/src/pipewright/expr.py @@ -0,0 +1,232 @@ +"""Safe expressions and templates over items. + +Expressions are Python syntax restricted to a whitelist (no imports, no dunder +attributes, no arbitrary calls), evaluated against an item: + + len(payload.body) > 400 and labels.category == "bug" + re(r"traceback|exception", payload.body.lower()) + mean([m.labels.passed for m in payload.members]) + +Names: `payload`, `labels`, `key`, `kind`, `id`, `provenance`, `item` (all of it), +plus any extra variables a node passes in. Dict keys read as attributes; a missing key +reads as None, so `labels.score or 0` works on items that lack the label. + +Templates substitute `{{ expr }}`; dicts/lists render as JSON. +""" + +from __future__ import annotations + +import ast +import json +import math +import re as _rx +import statistics +from functools import lru_cache +from typing import Any + +from .errors import NodeError + + +class Obj(dict): + """dict with attribute access; missing keys are None. Wrapping is lazy: nested + values are wrapped when accessed, so evaluating `labels.x > 1` on an item with a + large payload does not copy the payload.""" + + def __getattr__(self, name: str) -> Any: + if name.startswith("_"): + raise AttributeError(name) + return wrap(dict.get(self, name)) + + def __getitem__(self, k: Any) -> Any: + return wrap(dict.__getitem__(self, k)) + + def get(self, k: Any, default: Any = None) -> Any: # type: ignore[override] + return wrap(dict.get(self, k, default)) + + def values(self): # type: ignore[override] + return [wrap(v) for v in dict.values(self)] + + def items(self): # type: ignore[override] + return [(k, wrap(v)) for k, v in dict.items(self)] + + def __iter__(self): + return dict.__iter__(self) + + +def wrap(v: Any) -> Any: + if isinstance(v, Obj): + return v + if isinstance(v, dict): + return Obj(v) + if isinstance(v, (list, tuple)): + return [wrap(x) for x in v] + return v + + +def unwrap(v: Any) -> Any: + if isinstance(v, dict): + return {k: unwrap(x) for k, x in dict.items(v)} + if isinstance(v, list): + return [unwrap(x) for x in v] + return v + + +def _mean(xs): + xs = [float(x) for x in xs if x is not None] + return statistics.fmean(xs) if xs else None + + +def _re_search(pattern: str, text: Any, flags: str = "i") -> bool: + return bool(_rx.search(pattern, str(text or ""), _flags(flags))) + + +def _re_count(pattern: str, text: Any, flags: str = "i") -> int: + return len(_rx.findall(pattern, str(text or ""), _flags(flags))) + + +def _re_find(pattern: str, text: Any, flags: str = "i") -> str | None: + m = _rx.search(pattern, str(text or ""), _flags(flags)) + if not m: + return None + return m.group(1) if m.groups() else m.group(0) + + +def _flags(s: str) -> int: + f = 0 + for c in s or "": + f |= {"i": _rx.I, "m": _rx.M, "s": _rx.S}.get(c, 0) + return f + + +def _get(obj: Any, path: str, default: Any = None) -> Any: + cur = obj + for part in str(path).split("."): + if isinstance(cur, dict) and part in cur: + cur = cur[part] + elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur): + cur = cur[int(part)] + else: + return default + return cur + + +def _coalesce(*xs): + for x in xs: + if x is not None: + return x + return None + + +FUNCTIONS: dict[str, Any] = { + "len": lambda x: len(x) if x is not None else 0, + "min": min, "max": max, "sum": sum, "abs": abs, "round": round, "sorted": sorted, + "int": int, "float": float, "str": str, "bool": bool, "any": any, "all": all, + "list": list, "set": set, "dict": dict, "range": range, "zip": zip, "enumerate": enumerate, + "mean": _mean, "median": lambda xs: statistics.median(xs) if xs else None, + "sqrt": math.sqrt, "log": math.log, + "re": _re_search, "re_count": _re_count, "re_find": _re_find, + "get": _get, "coalesce": _coalesce, + "json": lambda x: json.dumps(unwrap(x), ensure_ascii=False, sort_keys=True), + "words": lambda s: len(str(s or "").split()), + "lines": lambda s: len(str(s or "").splitlines()), +} + +_ALLOWED = ( + ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp, ast.Call, ast.Name, ast.Load, + ast.Store, ast.Attribute, ast.Subscript, ast.Slice, ast.Constant, ast.List, ast.Tuple, ast.Dict, ast.Set, + ast.ListComp, ast.GeneratorExp, ast.SetComp, ast.DictComp, ast.comprehension, ast.keyword, + ast.And, ast.Or, ast.Not, ast.USub, ast.UAdd, ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, + ast.Pow, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn, ast.Is, ast.IsNot, + ast.JoinedStr, ast.FormattedValue, +) +_BLOCKED_ATTRS = {"format", "format_map", "mro", "gi_frame", "f_globals"} + + +class ExprError(NodeError): + pass + + +@lru_cache(maxsize=4096) +def compile_expr(src: str): + try: + tree = ast.parse(src.strip(), mode="eval") + except SyntaxError as e: + raise ExprError(f"syntax error in expression {src!r}: {e.msg}") from None + for node in ast.walk(tree): + if not isinstance(node, _ALLOWED): + raise ExprError(f"{type(node).__name__} is not allowed in expressions ({src!r})") + if isinstance(node, ast.Attribute) and (node.attr.startswith("_") or node.attr in _BLOCKED_ATTRS): + raise ExprError(f"attribute {node.attr!r} is not allowed ({src!r})") + if isinstance(node, ast.Name) and node.id.startswith("_"): + raise ExprError(f"name {node.id!r} is not allowed ({src!r})") + return compile(tree, "", "eval") + + +def names_in(src: str) -> set[str]: + tree = ast.parse(src.strip(), mode="eval") + bound = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)} + return {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)} - bound + + +def item_scope(item: Any, extra: dict | None = None) -> dict: + scope = { + "payload": wrap(item.payload), "labels": wrap(item.labels), "key": item.key, "kind": item.kind, + "id": item.id, "provenance": item.provenance, + "item": wrap({"id": item.id, "key": item.key, "kind": item.kind, "payload": item.payload, + "labels": item.labels, "provenance": item.provenance, "parents": list(item.parents)}), + } + if extra: + scope.update({k: wrap(v) for k, v in extra.items()}) + return scope + + +def evaluate(src: str, scope: dict) -> Any: + code = compile_expr(src) + try: + return unwrap(eval(code, {"__builtins__": {}, **FUNCTIONS, **scope})) # noqa: S307 - AST-whitelisted + except ExprError: + raise + except Exception as e: + raise ExprError(f"error evaluating {src!r}: {type(e).__name__}: {e}") from None + + +def eval_item(src: str, item: Any, extra: dict | None = None) -> Any: + return evaluate(src, item_scope(item, extra)) + + +def check_expr(src: str, allowed_names: set[str] | None = None) -> str | None: + """None if `src` compiles (and only uses known names), else an error message.""" + try: + compile_expr(src) + except ExprError as e: + return str(e) + if allowed_names is not None: + unknown = names_in(src) - allowed_names - set(FUNCTIONS) - {"True", "False", "None"} + if unknown: + return f"unknown name(s) {sorted(unknown)} in {src!r}; available: {sorted(allowed_names)}" + return None + + +ITEM_NAMES = {"payload", "labels", "key", "kind", "id", "provenance", "item"} + +_TEMPLATE = _rx.compile(r"\{\{(.+?)\}\}", _rx.S) + + +def render(template: str, scope: dict) -> str: + def sub(m: _rx.Match) -> str: + v = evaluate(m.group(1), scope) + if v is None: + return "" + if isinstance(v, (dict, list)): + return json.dumps(v, ensure_ascii=False, indent=2) + return str(v) + + return _TEMPLATE.sub(sub, template) + + +def render_item(template: str, item: Any, extra: dict | None = None) -> str: + return render(template, item_scope(item, extra)) + + +def template_exprs(template: str) -> list[str]: + return [m.group(1) for m in _TEMPLATE.finditer(template)] diff --git a/src/pipewright/graph.py b/src/pipewright/graph.py new file mode 100644 index 0000000..1fbb559 --- /dev/null +++ b/src/pipewright/graph.py @@ -0,0 +1,346 @@ +"""Graph specs (the JSON/YAML file format) and the Python builder API. + +A graph file is a mapping of node ids to node specs; edges live on the consuming +node's `inputs` (ComfyUI style), so adding/removing a node is a local edit: + + name: qa-labeling + nodes: + records: {type: source.jsonl, params: {path: data/records.jsonl, kind: issue}} + labels: {type: label.expr, inputs: {in: records}, params: {labels: {long: "len(payload.body) > 400"}}} + route: {type: route.expr, inputs: {in: labels.out}, params: {routes: {long: "labels.long"}}} + +An input reference is `node` (meaning `node.out`) or `node.port`. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from typing import Any + +import yaml +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator + +from .errors import ConfigError +from .hashing import digest + + +class RetryPolicy(BaseModel): + """Attempts per error class within one run (in addition to the first try).""" + + model_config = ConfigDict(extra="forbid") + provider: int = 3 + infra: int = 2 + node: int = 0 + + +class NodeSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + type: str + params: dict[str, Any] = Field(default_factory=dict) + inputs: dict[str, list[str]] = Field(default_factory=dict) + timeout: float | None = Field(None, gt=0, description="seconds per item (per attempt)") + retries: RetryPolicy | None = None + description: str | None = None + + @field_validator("inputs", mode="before") + @classmethod + def _listify(cls, v: Any) -> Any: + if isinstance(v, dict): + out = {} + for k, x in v.items(): + refs = [x] if isinstance(x, str) else list(x) + out[k] = [r if "." in r else f"{r}.out" for r in refs] # normalize `node` -> `node.out` + return out + return v + + +class ImportSpec(BaseModel): + """Another graph whose outputs this graph consumes (cross-graph edges by reference). + + Inputs then refer to `:.`; each run reads the items that flowed + out of that port in the selected run(s) of the imported graph. Item ids are kept, + so items processed before stay memoized and only new upstream items cost work. + """ + + model_config = ConfigDict(extra="forbid") + graph: str = Field(description="graph file (relative to this graph file), or `self` for this graph's own " + "earlier runs, or a graph NAME when `store` is given") + project: str | None = Field(None, description="project file of the imported graph (default: discovered " + "next to/above its graph file)") + store: str | None = Field(None, description="store directory to read (instead of the imported graph's project)") + run: str = Field("latest", description="latest | previous | all | : which upstream run(s) to read") + where: str | None = Field(None, description="expression filtering imported items, e.g. labels.pass_rate >= 0.75") + + +class GraphSpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + name: str + description: str = "" + version: int = 1 + plugins: list[str] = Field(default_factory=list, description="python modules to import (local node packs)") + imports: dict[str, ImportSpec] = Field(default_factory=dict, + description="alias -> another graph whose outputs are inputs here") + nodes: dict[str, NodeSpec] = Field(default_factory=dict) + _base_dir: Path | None = PrivateAttr(default=None) + + def __eq__(self, other: object) -> bool: # the file location is not part of the graph + if not isinstance(other, GraphSpec): + return NotImplemented + return self.model_dump() == other.model_dump() + + __hash__ = None # type: ignore[assignment] + + @property + def base_dir(self) -> Path: + """Directory of the graph file (relative import paths resolve against it).""" + return self._base_dir or Path.cwd() + + # ------------------------------------------------------------------ edges + def edges(self) -> list[tuple[str, str, str, str]]: + """(src_node, src_port, dst_node, dst_port) for every connection.""" + out = [] + for dst, spec in self.nodes.items(): + for dport, refs in spec.inputs.items(): + for ref in refs: + src, sport = split_ref(ref) + out.append((src, sport, dst, dport)) + return out + + def upstream(self, node: str) -> set[str]: + return {split_ref(r)[0] for refs in self.nodes[node].inputs.values() for r in refs} + + def ancestors(self, node: str) -> set[str]: + seen: set[str] = set() + stack = [node] + while stack: + n = stack.pop() + for u in self.upstream(n) if n in self.nodes else (): + if u not in seen: + seen.add(u) + stack.append(u) + return seen + + def topo_order(self) -> list[str]: + """Nodes in dependency order; raises ConfigError on a cycle.""" + order: list[str] = [] + state: dict[str, int] = {} + + def visit(n: str, path: list[str]) -> None: + if state.get(n) == 2: + return + if state.get(n) == 1: + raise ConfigError(f"cycle: {' -> '.join(path + [n])}") + state[n] = 1 + for u in sorted(self.upstream(n)): + if u in self.nodes: + visit(u, path + [n]) + state[n] = 2 + order.append(n) + + for n in self.nodes: + visit(n, []) + return order + + def hash(self) -> str: + return digest(self.model_dump(mode="json")) + + def dump(self, path: str | Path) -> None: + save_graph(self, path) + + +def split_ref(ref: str) -> tuple[str, str]: + node, _, port = ref.partition(".") + return node, port or "out" + + +def is_import_ref(node: str) -> bool: + """`alias:node` refers to a node of an imported graph.""" + return ":" in node + + +# ---------------------------------------------------------------------- files +def _resolve_plugins(spec: GraphSpec, base: Path) -> None: + """Make local plugin modules importable relative to the graph file.""" + if spec.plugins and str(base) not in sys.path: + sys.path.insert(0, str(base)) + + +def load_graph(path: str | Path) -> GraphSpec: + path = Path(path) + if not path.exists(): + raise ConfigError(f"graph file not found: {path}") + if path.suffix == ".py": + name = f"_pw_graph_{digest(str(path.resolve()), 8)}" + sys.path.insert(0, str(path.parent.resolve())) + mod_spec = importlib.util.spec_from_file_location(name, path) + assert mod_spec and mod_spec.loader + module = importlib.util.module_from_spec(mod_spec) + sys.modules[name] = module + mod_spec.loader.exec_module(module) + obj = getattr(module, "graph", None) + if obj is None and hasattr(module, "build"): + obj = module.build() + if isinstance(obj, Graph): + obj = obj.to_spec() + if not isinstance(obj, GraphSpec): + raise ConfigError(f"{path}: define `graph` (a pipewright.Graph) or `build()` returning one") + spec = obj + else: + text = path.read_text() + try: + data = json.loads(text) if path.suffix == ".json" else yaml.safe_load(text) + except (ValueError, yaml.YAMLError) as e: + raise ConfigError(f"{path}: cannot parse: {e}") from e + try: + spec = GraphSpec.model_validate(data) + except Exception as e: # pydantic ValidationError + raise ConfigError(f"{path}: invalid graph file: {e}") from e + _resolve_plugins(spec, path.parent.resolve()) + spec._base_dir = path.parent.resolve() + return spec + + +def graph_to_data(spec: GraphSpec) -> dict: + data = spec.model_dump(mode="json", exclude_defaults=True) + data.setdefault("name", spec.name) + for n in data.get("nodes", {}).values(): + ins = n.get("inputs") or {} + for k, v in list(ins.items()): + if len(v) == 1: + ins[k] = v[0] + return data + + +class _BlockDumper(yaml.SafeDumper): + """Multi-line strings (prompts, code) as literal `|` blocks.""" + + +def _str_presenter(dumper: yaml.SafeDumper, value: str): + if "\n" in value: + value = "\n".join(line.rstrip() for line in value.split("\n")) # literal blocks forbid trailing spaces + return dumper.represent_scalar("tag:yaml.org,2002:str", value, style="|") + return dumper.represent_scalar("tag:yaml.org,2002:str", value) + + +_BlockDumper.add_representer(str, _str_presenter) + + +def save_graph(spec: GraphSpec, path: str | Path) -> None: + path = Path(path) + data = graph_to_data(spec) + if path.suffix == ".json": + text = json.dumps(data, indent=2) + "\n" + elif path.suffix in (".yaml", ".yml"): + text = yaml.dump(data, Dumper=_BlockDumper, sort_keys=False, allow_unicode=True, width=100) + else: + raise ConfigError(f"can only write .json/.yaml graph files, not {path.suffix}") + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(text) + tmp.replace(path) + + +# ---------------------------------------------------------------------- builder +class PortRef: + def __init__(self, node: "NodeRef", port: str): + self.node, self.port = node, port + + def __str__(self) -> str: + return f"{self.node.id}.{self.port}" + + +class NodeRef: + def __init__(self, graph: "Graph", id: str): + self.graph, self.id = graph, id + + def port(self, name: str) -> PortRef: + return PortRef(self, name) + + __getitem__ = port + + @property + def out(self) -> PortRef: + return PortRef(self, "out") + + def __str__(self) -> str: + return f"{self.id}.out" + + +Ref = str | NodeRef | PortRef + + +class ImportRef: + def __init__(self, graph: "Graph", alias: str): + self.graph, self.alias = graph, alias + + def node(self, name: str) -> NodeRef: + return NodeRef(self.graph, f"{self.alias}:{name}") + + __getitem__ = node + + +class Graph: + """Typed Python builder that round-trips to a graph file. + + g = Graph("demo") + src = g.add("records", "source.jsonl", path="data.jsonl", kind="issue") + lab = g.add("labels", LabelExpr.Params(labels={"long": "len(payload.body) > 400"}), input=src) + g.add("export", "sink.jsonl", path="out/labelled.jsonl", input=lab) + g.save("graph.yaml") + + Params are validated against the registered node type as soon as you add the node, + so typos fail at the line that made them. + """ + + def __init__(self, name: str, description: str = "", plugins: list[str] | None = None, validate: bool = True): + self.spec = GraphSpec(name=name, description=description, plugins=plugins or []) + self.validate = validate + + def add(self, id: str, type: Any, *, input: Ref | list[Ref] | None = None, + inputs: dict[str, Ref | list[Ref]] | None = None, timeout: float | None = None, + retries: RetryPolicy | dict | None = None, description: str | None = None, **params: Any) -> NodeRef: + from .registry import registry + + if id in self.spec.nodes: + raise ConfigError(f"duplicate node id {id!r}") + if isinstance(type, BaseModel): # typed params object: node type from its class + type_name = getattr(type.__class__, "__node_type__", None) + if not type_name: + raise ConfigError(f"{type.__class__.__name__} is not a node Params class") + params = {**type.model_dump(mode="json", exclude_unset=True), **params} + type = type_name + elif not isinstance(type, str): + type = type.name # a NodeType class + all_inputs: dict[str, list[str]] = {} + if input is not None: + all_inputs["in"] = [str(r) for r in (input if isinstance(input, list) else [input])] + for port, refs in (inputs or {}).items(): + all_inputs[port] = [str(r) for r in (refs if isinstance(refs, list) else [refs])] + if self.validate: + nt = registry.node_types.get(type) + if nt is not None: + nt.Params.model_validate(params) + self.spec.nodes[id] = NodeSpec(type=type, params=params, inputs=all_inputs, timeout=timeout, + retries=RetryPolicy.model_validate(retries) if retries else None, + description=description) + return NodeRef(self, id) + + def import_graph(self, alias: str, graph: str, *, project: str | None = None, store: str | None = None, + run: str = "latest", where: str | None = None) -> "ImportRef": + """Consume another graph's outputs: `up = g.import_graph("build", "graph_build.py")`, + then `input=up.node("bucket").port("too_easy")`. Use graph="self" (with run="previous") + to feed this graph's own earlier results back in (re-entrant loops across runs).""" + if ":" in alias or "." in alias: + raise ConfigError(f"import alias {alias!r} may not contain ':' or '.'") + self.spec.imports[alias] = ImportSpec(graph=graph, project=project, store=store, run=run, where=where) + return ImportRef(self, alias) + + def to_spec(self) -> GraphSpec: + return self.spec.model_copy(deep=True) + + def save(self, path: str | Path) -> None: + save_graph(self.spec, path) diff --git a/src/pipewright/harness/__init__.py b/src/pipewright/harness/__init__.py new file mode 100644 index 0000000..66ea289 --- /dev/null +++ b/src/pipewright/harness/__init__.py @@ -0,0 +1,5 @@ +"""Agent harnesses: base interface, built-in tool-calling agent, CLI adapter, verifiers adapter.""" + +from .base import AgentTask, Harness, Trajectory + +__all__ = ["AgentTask", "Harness", "Trajectory"] diff --git a/src/pipewright/harness/base.py b/src/pipewright/harness/base.py new file mode 100644 index 0000000..831fcfb --- /dev/null +++ b/src/pipewright/harness/base.py @@ -0,0 +1,88 @@ +"""Agent harnesses: "run an agent with tools on a task inside a sandbox and return +its trajectory". + +A Harness gets an AgentTask (prompt, limits), a live Sandbox (already set up by the +node: task files written) and a HarnessContext (model clients bound to the run's +accounting, the shared logging proxy), and returns a Trajectory. + +Failure contract — the important part: + +- The agent finished, gave up, ran out of turns or time: return a Trajectory + (status completed / max_turns / timeout). That is a RESULT and gets graded. +- A model call failed and the agent stopped because of it (including CLI agents + that "complete" after their last call errored): raise ProviderError. The engine + retries the item; it is never graded as a failure of the model under test. +- The harness/sandbox infrastructure broke: raise InfraError. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Literal + +from pydantic import BaseModel, Field + +if TYPE_CHECKING: + from ..models.base import ModelClient + from ..models.proxy import LoggingProxy + from ..project import Project + from ..sandbox.base import Sandbox + + +class AgentTask(BaseModel): + prompt: str + system: str | None = None + max_turns: int | None = None + timeout: float | None = None + env: dict[str, str] = Field(default_factory=dict) + metadata: dict[str, Any] = Field(default_factory=dict) + + +class Trajectory(BaseModel): + harness: str + status: Literal["completed", "max_turns", "timeout", "error"] + messages: list[dict] = Field(default_factory=list) + final: str | None = None + turns: int = 0 + usage: dict[str, float] = Field(default_factory=dict) + error: dict | None = None + logs: dict[str, str] = Field(default_factory=dict) + duration: float = 0.0 + + +class HarnessContext: + """What a harness may use from the engine.""" + + def __init__(self, model_factory, proxy_factory, cache_salt: str | None = None): + self._model_factory = model_factory + self._proxy_factory = proxy_factory + self.cache_salt = cache_salt + + def model(self, alias: str) -> "ModelClient": + return self._model_factory(alias, self.cache_salt) + + async def proxy(self) -> "LoggingProxy": + return await self._proxy_factory() + + +class Harness(ABC): + type: str = "abstract" + owns_sandbox: bool = False + """True if the harness provisions its own runtime (the node then leases no sandbox).""" + + def __init__(self, name: str, config: dict, project: "Project | None" = None): + self.name, self.config, self.project = name, config, project + + @property + def model_alias(self) -> str | None: + return self.config.get("model") + + @abstractmethod + async def run(self, task: AgentTask, sandbox: "Sandbox | None", ctx: HarnessContext) -> Trajectory: ... + + +def truncate(text: str, limit: int) -> str: + if len(text) <= limit: + return text + half = limit // 2 + return f"{text[:half]}\n... [{len(text) - limit} chars truncated] ...\n{text[-half:]}" diff --git a/src/pipewright/harness/builtin_agent.py b/src/pipewright/harness/builtin_agent.py new file mode 100644 index 0000000..0ca1c3d --- /dev/null +++ b/src/pipewright/harness/builtin_agent.py @@ -0,0 +1,126 @@ +"""A minimal tool-calling agent: OpenAI-compatible chat with bash/read/write tools +executed in the sandbox. + + harnesses: + mini: + type: builtin + model: solver # model alias + max_turns: 30 + tool_timeout: 120 # seconds per bash call + max_output_chars: 8000 # tool output shown to the model (head + tail) + system: "..." # optional override + +Small on purpose: it is the reference harness for tests and for probing models +without installing a third-party agent. +""" + +from __future__ import annotations + +import asyncio +import json +import time + +from ..errors import ConfigError +from ..registry import register_harness +from .base import AgentTask, Harness, HarnessContext, Trajectory, truncate + +SYSTEM = """You are an autonomous software agent working in a sandboxed Linux shell. +Your working directory is {workdir}. Use the tools to inspect files, run commands and edit code. +When you are done, call `finish` with a short summary. Do not ask the user questions.""" + +TOOLS = [ + {"type": "function", "function": { + "name": "bash", "description": "Run a shell command in the working directory; returns exit code and output.", + "parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}}}, + {"type": "function", "function": { + "name": "read_file", "description": "Read a text file.", + "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}, + {"type": "function", "function": { + "name": "write_file", "description": "Create or overwrite a text file with the given content.", + "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, + "required": ["path", "content"]}}}, + {"type": "function", "function": { + "name": "finish", "description": "Finish the task.", + "parameters": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": ["summary"]}}}, +] + + +class BuiltinAgent(Harness): + type = "builtin" + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + if not config.get("model"): + raise ConfigError(f"harness {name}: `model` (an alias) is required") + + async def run(self, task: AgentTask, sandbox, ctx: HarnessContext) -> Trajectory: + client = ctx.model(self.config["model"]) + max_turns = task.max_turns or int(self.config.get("max_turns", 30)) + limit = int(self.config.get("max_output_chars", 8000)) + system = task.system or self.config.get("system") or SYSTEM.format(workdir=sandbox.workdir) + messages: list[dict] = [{"role": "system", "content": system}, {"role": "user", "content": task.prompt}] + usage = {"input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0} + start = time.time() + status, final, turns = "max_turns", None, 0 + + async def loop() -> None: + nonlocal status, final, turns + for _ in range(max_turns): + turns += 1 + res = await client.chat(messages, tools=TOOLS) # ProviderError propagates: retryable, not a result + usage["input_tokens"] += res.usage.input_tokens + usage["output_tokens"] += res.usage.output_tokens + usage["cost_usd"] += res.usage.cost_usd or 0.0 + msg = {"role": "assistant", "content": res.content} + if res.tool_calls: + msg["tool_calls"] = res.tool_calls + messages.append(msg) + if not res.tool_calls: + status, final = "completed", res.content + return + finished = False + for call in res.tool_calls: + fn = call.get("function") or {} + name = fn.get("name") + try: + args = json.loads(fn.get("arguments") or "{}") + if not isinstance(args, dict): + raise ValueError("arguments must be an object") + out = await self._tool(name, args, sandbox, limit) + if name == "finish": + finished, final = True, str(args.get("summary", "")) + except (ValueError, TypeError, KeyError) as e: + out = f"error: bad arguments for {name}: {e}" + except FileNotFoundError as e: + out = f"error: {e}" + messages.append({"role": "tool", "tool_call_id": call.get("id"), "content": out}) + if finished: + status = "completed" + return + + try: + if task.timeout: + await asyncio.wait_for(loop(), task.timeout) + else: + await loop() + except asyncio.TimeoutError: + status = "timeout" + return Trajectory(harness=self.name, status=status, messages=messages, final=final, turns=turns, + usage=usage, duration=time.time() - start) + + async def _tool(self, name: str | None, args: dict, sandbox, limit: int) -> str: + if name == "bash": + r = await sandbox.exec(str(args["command"]), timeout=float(self.config.get("tool_timeout", 120))) + body = r.stdout + (f"\n[stderr]\n{r.stderr}" if r.stderr.strip() else "") + return truncate(f"exit code {r.exit_code}{' (timed out)' if r.timed_out else ''}\n{body}", limit) + if name == "read_file": + return truncate((await sandbox.read(str(args["path"]))).decode(errors="replace"), limit) + if name == "write_file": + await sandbox.write(str(args["path"]), str(args["content"])) + return f"wrote {len(str(args['content']))} chars to {args['path']}" + if name == "finish": + return "ok" + return f"error: unknown tool {name!r}; available: bash, read_file, write_file, finish" + + +register_harness("builtin", BuiltinAgent) diff --git a/src/pipewright/harness/cli.py b/src/pipewright/harness/cli.py new file mode 100644 index 0000000..a92cc94 --- /dev/null +++ b/src/pipewright/harness/cli.py @@ -0,0 +1,100 @@ +"""Run an external agent CLI inside the sandbox. + + harnesses: + opencode: + type: cli + model: solver # alias served through the logging proxy + install: ["npm i -g some-agent"] # run once per sandbox before the agent + command: "some-agent --model {{model}} --prompt-file {{prompt_file}}" + env: {AGENT_FLAG: "1"} + timeout: 1800 + nonzero_exit: infra # infra (retry) | result (grade it anyway) + +The agent talks to the model through pipewright's logging proxy: it gets +OPENAI_BASE_URL / OPENAI_API_BASE pointing at the proxy and OPENAI_API_KEY set to a +per-run session token (the real key never enters the sandbox). Every turn is +recorded into the trajectory, and the provider's rate limits, quirk adapters, retries +and accounting apply. If the agent exits after its last model call failed, the run +raises ProviderError (retry) instead of returning a result. + +Template variables: {{model}}, {{prompt_file}}, {{workdir}}, {{base_url}}. +""" + +from __future__ import annotations + +import time + +from ..errors import ConfigError, InfraError, ProviderError +from ..expr import render +from ..registry import register_harness +from .base import AgentTask, Harness, HarnessContext, Trajectory, truncate + + +class CLIHarness(Harness): + type = "cli" + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + if not config.get("command"): + raise ConfigError(f"harness {name}: `command` is required") + if not config.get("model"): + raise ConfigError(f"harness {name}: `model` (an alias) is required") + + async def run(self, task: AgentTask, sandbox, ctx: HarnessContext) -> Trajectory: + client = ctx.model(self.config["model"]) + proxy = await ctx.proxy() + reverse = getattr(sandbox, "reverse", None) + addr = None + if reverse is not None: # remote sandboxes: a tunnel back to a local listener + addr = await reverse(await proxy.listen("127.0.0.1")) + if addr is None: + inside_host, bind = sandbox.host_address() + addr = f"{inside_host}:{await proxy.listen(bind)}" + session = proxy.open_session(client) + base_url = f"http://{addr}/v1" + start = time.time() + try: + for cmd in self.config.get("install") or []: + r = await sandbox.exec(cmd, timeout=self.config.get("install_timeout", 900)) + if not r.ok: + raise InfraError(f"harness {self.name}: install failed: {cmd!r}: {r.summary(600)}") + prompt_file = sandbox.path(".pw/prompt.md") + await sandbox.write(prompt_file, (task.system + "\n\n" if task.system else "") + task.prompt) + scope = {"model": client.model, "prompt_file": prompt_file, "workdir": sandbox.workdir, + "base_url": base_url} + command = render(self.config["command"], scope) + env = {"OPENAI_BASE_URL": base_url, "OPENAI_API_BASE": base_url, "OPENAI_API_KEY": session.token, + "PW_MODEL": client.model, **{k: str(v) for k, v in (self.config.get("env") or {}).items()}, + **task.env} + timeout = task.timeout or self.config.get("timeout") + r = await sandbox.exec(command, timeout=timeout, env=env) + usage = {"input_tokens": 0, "output_tokens": 0} + for t in session.turns: + u = t.get("usage") or {} + usage["input_tokens"] += u.get("prompt_tokens", 0) or 0 + usage["output_tokens"] += u.get("completion_tokens", 0) or 0 + logs = {"stdout": truncate(r.stdout, 20000), "stderr": truncate(r.stderr, 20000), + "turns": str(len(session.turns))} + if session.failed_last_call: + raise ProviderError( + f"agent stopped after its last model call failed ({session.last_error}); not a result", + status=(session.last_error or {}).get("status")) + if r.timed_out: + status = "timeout" + elif r.exit_code != 0: + if self.config.get("nonzero_exit", "infra") == "infra": + raise InfraError(f"agent CLI exited {r.exit_code}: {r.stderr[-500:]}") + status = "error" + else: + status = "completed" + final = None + msgs = session.messages() + if msgs and msgs[-1].get("role") == "assistant": + final = msgs[-1].get("content") + return Trajectory(harness=self.name, status=status, messages=msgs, final=final, + turns=len(session.turns), usage=usage, logs=logs, duration=time.time() - start) + finally: + proxy.close_session(session.token) + + +register_harness("cli", CLIHarness) diff --git a/src/pipewright/harness/verifiers_adapter.py b/src/pipewright/harness/verifiers_adapter.py new file mode 100644 index 0000000..00a6c24 --- /dev/null +++ b/src/pipewright/harness/verifiers_adapter.py @@ -0,0 +1,102 @@ +"""Adapter for prime-intellect `verifiers` v1 harnesses (EXPERIMENTAL, optional extra). + +Runs any verifiers v1 harness (bash, mini_swe_agent, codex, claude_code, pi, ...) on +a pipewright item through `verifiers.v1.Agent`, with the model routed through +pipewright's logging proxy so pacing, quirk handling, retries and accounting are the +same as for every other model call. + + harnesses: + vf-bash: + type: verifiers + model: solver # pipewright model alias + harness: {id: bash} # a verifiers HarnessConfig (id + fields) + runtime: {type: docker, image: python:3.12-slim} # a verifiers RuntimeConfig + max_turns: 30 + +verifiers provisions its own runtime, so this harness `owns_sandbox` and the +`agent.run` node does not lease a pipewright sandbox for it; grading commands that +need the agent's final workspace must run inside the verifiers task instead. A +pipewright Taskset adapter (items -> verifiers Tasks with `setup`/`validate` hooks) +is on the roadmap; see docs/roadmap.md. + +Error mapping: a trace whose last error is a verifiers `ProviderError` (or an +InterceptionError caused by one) raises pipewright ProviderError; `SandboxError` / +`HarnessError` / `TunnelError` raise InfraError; everything else is a result. + +Not covered by the test suite (verifiers is not a dependency). Smoke-tested by hand +against verifiers v1 (bash harness, subprocess runtime, fake model through the proxy): +a completed rollout maps to a Trajectory, and a rollout ending on a 503 raises +ProviderError. Install with `pip install 'pipewright[verifiers]'`. +""" + +from __future__ import annotations + +import os +import time + +from ..errors import ConfigError, InfraError, ProviderError +from ..registry import register_harness +from .base import AgentTask, Harness, HarnessContext, Trajectory + +INFRA_TYPES = {"SandboxError", "HarnessError", "TunnelError", "InterceptionError", "ToolsetError"} + + +class VerifiersHarness(Harness): + type = "verifiers" + owns_sandbox = True + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + if not config.get("model"): + raise ConfigError(f"harness {name}: `model` (an alias) is required") + + async def run(self, task: AgentTask, sandbox, ctx: HarnessContext) -> Trajectory: + try: + import verifiers.v1 as vf + from verifiers.v1.utils.loaders import harness_config_type + except ImportError as e: # pragma: no cover - optional dependency + raise ConfigError("the verifiers harness needs `pip install 'pipewright[verifiers]'`") from e + + client = ctx.model(self.config["model"]) + proxy = await ctx.proxy() + port = await proxy.listen("127.0.0.1") + session = proxy.open_session(client) + key_var = f"PW_VF_SESSION_{abs(hash(session.token)) % 10**8}" + os.environ[key_var] = session.token + start = time.time() + try: + hcfg = dict(self.config.get("harness") or {"id": "bash"}) + harness_cfg = harness_config_type(hcfg["id"])(**hcfg) + runtime_cfg = self.config.get("runtime") or {"type": "subprocess"} + agent_cfg = vf.AgentConfig( + harness=harness_cfg, + runtime=runtime_cfg, + model=client.model, + client=vf.EvalClientConfig(base_url=f"http://127.0.0.1:{port}/v1", api_key_var=key_var), + max_turns=task.max_turns or self.config.get("max_turns"), + ) + vf_task = vf.Task(vf.TaskData(prompt=task.prompt, system_prompt=task.system)) + async with vf.Agent(agent_cfg) as agent: + trace = await agent.run(vf_task) + errors = list(getattr(trace, "errors", None) or []) + last = errors[-1] if errors else None + if session.failed_last_call or (last is not None and getattr(last, "type", "") == "ProviderError"): + raise ProviderError(f"verifiers rollout ended on a provider error: {last or session.last_error}", + status=getattr(last, "status_code", None)) + if last is not None and getattr(last, "type", "") in INFRA_TYPES: + raise InfraError(f"verifiers {last.type}: {getattr(last, 'message', '')[:500]}") + try: + messages = [m.model_dump(mode="json") if hasattr(m, "model_dump") else m for m in trace.messages] + except Exception: + messages = session.messages() + return Trajectory(harness=self.name, status="completed" if last is None else "error", + messages=messages, turns=len(session.turns), + error={"type": last.type, "message": last.message} if last is not None else None, + duration=time.time() - start, + logs={"rewards": str(getattr(trace, "rewards", {}))}) + finally: + os.environ.pop(key_var, None) + proxy.close_session(session.token) + + +register_harness("verifiers", VerifiersHarness) diff --git a/src/pipewright/hashing.py b/src/pipewright/hashing.py new file mode 100644 index 0000000..7343150 --- /dev/null +++ b/src/pipewright/hashing.py @@ -0,0 +1,32 @@ +"""Canonical JSON and content hashes used for item ids, memo keys and caches.""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any + +from pydantic import BaseModel + + +def _default(obj: Any) -> Any: + if isinstance(obj, BaseModel): + return obj.model_dump(mode="json") + if isinstance(obj, (set, frozenset)): + return sorted(obj) + if isinstance(obj, bytes): + return {"$bytes": hashlib.sha256(obj).hexdigest()} + if isinstance(obj, tuple): + return list(obj) + raise TypeError(f"not JSON serialisable: {type(obj).__name__}") + + +def canonical(obj: Any) -> str: + """Deterministic JSON: sorted keys, no whitespace, UTF-8.""" + return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=_default) + + +def digest(obj: Any, n: int = 24) -> str: + """Short sha256 of the canonical JSON of `obj` (n hex chars).""" + data = obj if isinstance(obj, bytes) else canonical(obj).encode() + return hashlib.sha256(data).hexdigest()[:n] diff --git a/src/pipewright/hosts/__init__.py b/src/pipewright/hosts/__init__.py new file mode 100644 index 0000000..233864e --- /dev/null +++ b/src/pipewright/hosts/__init__.py @@ -0,0 +1,6 @@ +"""Host pools: machines (VMs, servers) that run sandboxes, with placement and autoscaling.""" + +from .base import Host, HostProvider, Requirements, Resources, parse_size +from .pool import HostLease, HostPool + +__all__ = ["Host", "HostLease", "HostPool", "HostProvider", "Requirements", "Resources", "parse_size"] diff --git a/src/pipewright/hosts/base.py b/src/pipewright/hosts/base.py new file mode 100644 index 0000000..5ba3022 --- /dev/null +++ b/src/pipewright/hosts/base.py @@ -0,0 +1,250 @@ +"""Hosts: machines that run sandboxes (Docker containers), and providers that make them. + +A HostProvider creates/deletes/extends machines reachable over SSH (VMs from an API, +a fixed list of servers, fakes for tests). A HostPool (`pool.py`) owns the lifecycle +on top: placement by capabilities and locality, autoscaling within min/max and an +hours/$ budget, setup hooks, health, TTL extension, idle shutdown, images. + +The orchestration stays local: sandboxes on a host are Docker containers driven with +`docker -H ssh://...` from this machine, so nothing needs to be synced to hosts. +""" + +from __future__ import annotations + +import os +import re +import shlex +import shutil +import time +from abc import ABC, abstractmethod +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from ..errors import ConfigError + +if TYPE_CHECKING: + from ..project import Project + +_UNITS = {"": 1, "b": 1, "k": 1024, "kb": 1024, "m": 1024**2, "mb": 1024**2, "g": 1024**3, "gb": 1024**3, + "t": 1024**4, "tb": 1024**4, "ki": 1024, "mi": 1024**2, "gi": 1024**3, "ti": 1024**4} + + +def parse_size(v: Any) -> float: + """Bytes from `16g`, `512m`, `2GiB`, or a number (bytes).""" + if v is None: + return 0.0 + if isinstance(v, (int, float)): + return float(v) + m = re.fullmatch(r"\s*([\d.]+)\s*([a-zA-Z]*)\s*", str(v)) + if not m: + raise ConfigError(f"cannot parse size {v!r} (use e.g. 16g, 512m)") + unit = m.group(2).lower() + if unit.endswith("ib"): + unit = unit[:-2] + elif unit.endswith("b"): + unit = unit[:-1] + if unit not in _UNITS: + raise ConfigError(f"unknown size unit in {v!r}") + return float(m.group(1)) * _UNITS[unit] + + +def fmt_size(b: float) -> str: + return f"{b / 1024**3:.1f}g" + + +@dataclass +class Resources: + """Divisible host resources. Memory/disk in bytes.""" + + cpus: float = 0.0 + memory: float = 0.0 + disk: float = 0.0 + + @classmethod + def parse(cls, d: dict | None) -> "Resources": + d = d or {} + return cls(float(d.get("cpus") or 0), parse_size(d.get("memory")), parse_size(d.get("disk"))) + + def fits_in(self, free: "Resources") -> bool: + eps = 1e-6 + return (self.cpus <= free.cpus + eps and self.memory <= free.memory + eps + and (self.disk <= free.disk + eps or free.disk == 0 and self.disk == 0)) + + def __add__(self, o: "Resources") -> "Resources": + return Resources(self.cpus + o.cpus, self.memory + o.memory, self.disk + o.disk) + + def __sub__(self, o: "Resources") -> "Resources": + return Resources(self.cpus - o.cpus, self.memory - o.memory, self.disk - o.disk) + + def view(self) -> dict: + return {"cpus": round(self.cpus, 2), "memory": fmt_size(self.memory), + **({"disk": fmt_size(self.disk)} if self.disk else {})} + + +@dataclass +class Requirements: + """What one sandbox needs from its host.""" + + resources: Resources = field(default_factory=Resources) + kvm: bool = False + gpu: bool = False + labels: frozenset[str] = frozenset() + """Host labels that must be present (hard).""" + prefer: frozenset[str] = frozenset() + """Host labels that make a host a better fit (locality: images, warm volumes).""" + + def view(self) -> dict: + return {"resources": self.resources.view(), "kvm": self.kvm, "gpu": self.gpu, + "labels": sorted(self.labels), "prefer": sorted(self.prefer)} + + +@dataclass +class Host: + id: str + pool: str + docker_host: str + """Value for `docker -H`, e.g. ssh://pw-abc123 (alias in ssh_config) or ssh://user@host:22.""" + capacity: Resources = field(default_factory=Resources) + labels: set[str] = field(default_factory=set) + kvm: bool = False + gpu: bool = False + ssh_config: str | None = None + """Path of an ssh config defining the alias in docker_host (keys, known_hosts, ControlMaster).""" + expires: float | None = None + """Provider TTL (wall clock), extended by the pool while the host is needed.""" + meta: dict[str, Any] = field(default_factory=dict) + """Provider data, e.g. the VM id.""" + state: str = "creating" # creating | setup | ready | draining | deleted | broken + created: float = field(default_factory=time.time) + ready_at: float | None = None + allocated: Resources = field(default_factory=Resources) + leases: int = 0 + last_used: float = field(default_factory=time.time) + state_dir: str | None = None + + @property + def free(self) -> Resources: + return self.capacity - self.allocated + + @property + def ssh_target(self) -> str: + return self.docker_host.removeprefix("ssh://") + + def ssh_argv(self, command: str | None = None) -> list[str]: + """argv running `command` on the host over SSH (None: just the connection prefix).""" + argv = [shutil.which("ssh") or "ssh", "-o", "BatchMode=yes"] + if self.ssh_config: + argv += ["-F", self.ssh_config, self.ssh_target] + else: + target = self.ssh_target + m = re.fullmatch(r"(?:(?P[^@]+)@)?(?P[^:]+)(?::(?P\d+))?", target) + if m and m.group("port"): + argv += ["-p", m.group("port")] + target = (m.group("user") + "@" if m.group("user") else "") + m.group("host") + argv += [target] + if command is not None: + argv += ["--", command] + return argv + + def docker_env(self) -> dict[str, str] | None: + """Environment for `docker -H ssh://...`: Docker's SSH helper runs plain `ssh`, so a + per-host wrapper directory on PATH injects `-F `.""" + if not self.ssh_config or not self.state_dir: + return None + bindir = Path(self.state_dir) / "bin" + wrapper = bindir / "ssh" + if not wrapper.exists(): + bindir.mkdir(parents=True, exist_ok=True) + real = shutil.which("ssh") or "/usr/bin/ssh" + wrapper.write_text(f"#!/bin/sh\nexec {shlex.quote(real)} -F {shlex.quote(self.ssh_config)} \"$@\"\n") + wrapper.chmod(0o755) + return {**os.environ, "PATH": f"{bindir}{os.pathsep}{os.environ.get('PATH', '')}"} + + def to_dict(self) -> dict: + d = asdict(self) + d["labels"] = sorted(self.labels) + d["capacity"] = asdict(self.capacity) + d["allocated"] = asdict(self.allocated) + return d + + @classmethod + def from_dict(cls, d: dict) -> "Host": + d = dict(d) + d["labels"] = set(d.get("labels") or []) + d["capacity"] = Resources(**(d.get("capacity") or {})) + d["allocated"] = Resources() + d["leases"] = 0 + return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) + + def view(self) -> dict: + return {"id": self.id, "pool": self.pool, "state": self.state, "docker_host": self.docker_host, + "capacity": self.capacity.view(), "allocated": self.allocated.view(), "leases": self.leases, + "labels": sorted(self.labels), "kvm": self.kvm, "gpu": self.gpu, + "age_s": round(time.time() - self.created, 1), + "expires_in_s": round(self.expires - time.time()) if self.expires else None, + **({"vm": self.meta.get("vm_id")} if self.meta.get("vm_id") else {})} + + +class HostProvider(ABC): + """Makes machines. Implement `create` and `delete`; `extend`, `list_remote` and + `alive` are optional. The pool handles setup, health, placement and scaling. + + Config keys every provider understands (under `hosts.:` in the project file): + `capacity: {cpus, memory, disk}` (else probed with `docker info`), `labels: [...]`, + `kvm`, `gpu`, `cost_per_hour`. + """ + + type: str = "abstract" + default_capacity: dict[str, Any] = {} + default_labels: tuple[str, ...] = () + supports_kvm: bool = False + supports_gpu: bool = False + + def __init__(self, name: str, config: dict, project: "Project | None" = None): + self.name, self.config, self.project = name, config, project + + @property + def cost_per_hour(self) -> float: + return float(self.config.get("cost_per_hour", 0) or 0) + + def capacity(self) -> Resources | None: + """Configured capacity of a new host (None: probe it after creation).""" + cap = self.config.get("capacity") or self.default_capacity + return Resources.parse(cap) if cap else None + + def labels(self) -> set[str]: + return set(self.config.get("labels") or self.default_labels) + + def kvm(self) -> bool: + return bool(self.config.get("kvm", self.supports_kvm)) + + def gpu(self) -> bool: + return bool(self.config.get("gpu", self.supports_gpu)) + + @abstractmethod + async def create(self, host_id: str, state_dir: Path) -> Host: + """Provision a machine and return it reachable over SSH (docker_host set).""" + + @abstractmethod + async def delete(self, host: Host) -> None: ... + + async def extend(self, host: Host, seconds: float) -> float | None: + """Extend the host's TTL; return the new expiry (wall clock) or None.""" + return None + + async def list_remote(self) -> list[dict]: + """Hosts the provider knows about that belong to this pool (for orphan cleanup): + dicts with at least `id` (provider id) and `name`.""" + return [] + + async def delete_remote(self, remote: dict) -> None: + """Delete a provider-side host by its `list_remote` entry (orphan cleanup).""" + raise ConfigError(f"host provider {self.type} cannot delete orphans") + + async def alive(self, host: Host) -> bool: + """Provider-side liveness (used when adopting hosts from an earlier process).""" + return True + + async def aclose(self) -> None: + pass diff --git a/src/pipewright/hosts/pool.py b/src/pipewright/hosts/pool.py new file mode 100644 index 0000000..56f4e8b --- /dev/null +++ b/src/pipewright/hosts/pool.py @@ -0,0 +1,793 @@ +"""HostPool: placement, autoscaling and lifecycle of hosts that run sandboxes. + + hosts: + vms: + type: boat # a registered host provider (boat, static, fake, ...) + min: 0 # hosts kept while the pool is in use + max: 4 # never more than this many + capacity: {cpus: 8, memory: 16g} # per host (default: provider default, else probed) + reserve: {cpus: 0.5, memory: 1g} # kept free for the host itself + labels: [kvm] # static labels; image: / volume: are added as they appear + docker_kvm_runtime: true # install a runc wrapper: every container gets /dev/kvm (mode 0666) + setup: ["sudo apt-get install -y jq"] # commands run on each new host (over SSH) + idle_shutdown: 300 # delete a host idle this long (above `min`) + ttl: 3600 # provider TTL; extended while the host is needed + extend_margin: 900 # extend when less than this is left + budget: {hours: 4, usd: 20} # host-hours / $ for this pool (per process lifetime) + cost_per_hour: 0.5 # for the $ budget and run budgets + persist: false # keep hosts at the end of a run (adopted by the next run) + +Sandbox pools place containers on it with `hosts: vms` (see sandbox/docker.py), giving +per-sandbox requirements (`cpus`, `memory`, `requires: {kvm, gpu, labels, disk}`) and +preferences (`prefer: [labels]`; the image and named volumes are preferred automatically). + +Placement: a request waits (priority-ordered: deeper graph nodes first) until a ready +host has the capabilities, the required labels and enough FREE resources; among +fitting hosts it prefers the most preferred labels (locality: the image is already +there, a warm volume exists), then the tightest fit (bin packing, so other hosts drain +and can be shut down). Capacity is resources, not slots: two 8 GB VM tests never land +on one 16 GB host with a 1 GB reserve. + +Scaling: when requests cannot be placed, the pool simulates packing them onto hosts +that are already being created and starts as many new hosts as still needed, within +`max` and the budget. Idle hosts above `min` are deleted after `idle_shutdown`. +Creation failures are retried; after `create_retries` consecutive failures with no +usable host, waiting requests fail with InfraError (the engine retries per policy). +""" + +from __future__ import annotations + +import asyncio +import heapq +import itertools +import json +import logging +import time +import uuid +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from ..errors import BudgetExceeded, ConfigError, InfraError +from ..sandbox.base import ExecResult +from .base import Host, HostProvider, Requirements, Resources + +if TYPE_CHECKING: + from ..project import Project + from ..scheduler import BudgetTracker + +log = logging.getLogger("pipewright.hosts") +_seq = itertools.count() + +# runc wrapper: every container gets /dev/kvm with mode 0666 (nested VMs at full speed, +# also for non-root users in the container). Installed as Docker's default runtime. +KVM_RUNTIME_SCRIPT = r""" +set -e +RUNC=$(command -v runc || echo /usr/bin/runc) +sudo tee /usr/local/bin/runc-kvm > /dev/null </dev/null 2>&1 && break; sleep 1; done +""" + + +# TCP relay run on a host: listens on the Docker bridge gateway and forwards to the +# loopback end of an SSH reverse tunnel (sshd binds -R ports to loopback only). +RELAY_SCRIPT = r""" +import asyncio, sys +bind, port, target = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) +async def pipe(r, w): + try: + while True: + d = await r.read(65536) + if not d: + break + w.write(d) + await w.drain() + finally: + w.close() +async def handle(r, w): + try: + ur, uw = await asyncio.open_connection("127.0.0.1", target) + except OSError: + w.close() + return + await asyncio.gather(pipe(r, uw), pipe(ur, w), return_exceptions=True) +async def main(): + server = await asyncio.start_server(handle, bind, port) + async with server: + await server.serve_forever() +asyncio.run(main()) +""" + + +def _bridge_subnet(gateway: str) -> str: + return ".".join(gateway.split(".")[:2]) + ".0.0/16" + + +def _shq(s: str) -> str: + import shlex + + return shlex.quote(s) + + +class HostLease: + """A share of one host's resources, held while a sandbox runs on it.""" + + def __init__(self, pool: "HostPool", host: Host, req: Requirements): + self.pool, self.host, self.req = pool, host, req + self.released = False + self.at = time.time() + + def release(self) -> None: + self.pool.release(self) + + +@dataclass(order=True) +class _Want: + priority: int + seq: int + req: Requirements = field(compare=False) + future: asyncio.Future = field(compare=False) + since: float = field(compare=False, default_factory=time.time) + + +class HostPool: + def __init__(self, name: str, config: dict, provider: HostProvider, project: "Project | None" = None): + self.name, self.config, self.provider, self.project = name, config, provider, project + self.min = int(config.get("min", 0)) + self.max = int(config.get("max", 1)) + if self.max < max(1, self.min): + raise ConfigError(f"hosts.{name}: max ({self.max}) must be >= max(1, min)") + self.idle_shutdown = float(config.get("idle_shutdown", 300)) + self.ttl = float(config["ttl"]) if config.get("ttl") else None + self.extend_margin = float(config.get("extend_margin", 900)) + self.setup_cmds: list[str] = list(config.get("setup") or []) + self.kvm_runtime = bool(config.get("docker_kvm_runtime", False)) + self.reserve = Resources.parse(config.get("reserve")) + budget = config.get("budget") or {} + self.budget_hours = budget.get("hours") + self.budget_usd = budget.get("usd") + self.persist = bool(config.get("persist", False)) + self.create_retries = int(config.get("create_retries", 2)) + self.create_limit = int(config.get("create_limit", 3 * self.max + 2)) + """Hard cap on host creations per pool lifetime (a guard against runaway billing).""" + self.create_backoff = float(config.get("create_backoff", 5)) + self._create_blocked_until = 0.0 + self.tick = float(config.get("tick", 5)) + self.ssh_wait = float(config.get("ssh_wait", 300)) + self.docker_bin = config.get("docker", "docker") + base = project.store_dir if project is not None else Path(".pipewright") + self.state_dir = Path(config.get("state_dir") or base / "hosts" / name) + self.hosts: dict[str, Host] = {} + self.pending: dict[str, asyncio.Task] = {} + self.wants: list[_Want] = [] + self.used_hours = 0.0 + self.exhausted: str | None = None + self.failures = 0 + self.last_error: str | None = None + self.budgets: list["BudgetTracker"] = [] + self.events: list[dict] = [] + self.stats: dict[str, Any] = {"created": 0, "deleted": 0, "failed_create": 0, "placed": 0, + "waited_s": 0.0, "extended": 0, "peak_hosts": 0, "adopted": 0} + self._image_locks: dict[tuple[str, str], asyncio.Lock] = {} + self._tunnels: dict[tuple[str, int], tuple[Any, str, int, int]] = {} + self._tunnel_lock: asyncio.Lock | None = None + self._loop: asyncio.AbstractEventLoop | None = None + self._ticker: asyncio.Task | None = None + self._start_lock: asyncio.Lock | None = None + self._last_tick = time.time() + + # ------------------------------------------------------------------ public + def requirements(self, resources: Resources, *, kvm: bool = False, gpu: bool = False, + labels: set[str] | frozenset[str] = frozenset(), + prefer: set[str] | frozenset[str] = frozenset()) -> Requirements: + req = Requirements(resources, kvm, gpu, frozenset(labels), frozenset(prefer)) + shape = self.host_shape() + if shape is not None and not req.resources.fits_in(shape): + raise ConfigError(f"hosts.{self.name}: a sandbox needing {req.resources.view()} can never fit a host " + f"with {shape.view()} usable (capacity minus reserve)") + if kvm and not self.provider.kvm(): + raise ConfigError(f"hosts.{self.name}: sandboxes require kvm but the hosts do not provide it") + if gpu and not self.provider.gpu(): + raise ConfigError(f"hosts.{self.name}: sandboxes require a gpu but the hosts do not provide one") + return req + + def host_shape(self) -> Resources | None: + cap = self.provider.capacity() + return cap - self.reserve if cap is not None else None + + async def acquire(self, req: Requirements, priority: int = 0, + budget: "BudgetTracker | None" = None) -> HostLease: + """Wait for (and reserve) room on a host satisfying `req`.""" + await self._start() + if budget is not None and all(b is not budget for b in self.budgets): + self.budgets.append(budget) + loop = asyncio.get_running_loop() + w = _Want(priority, next(_seq), req, loop.create_future()) + heapq.heappush(self.wants, w) + self._kick() + try: + lease = await w.future + except asyncio.CancelledError: + if w.future.done() and not w.future.cancelled() and w.future.exception() is None: + w.future.result().release() + else: + self.wants = [x for x in self.wants if x is not w] + heapq.heapify(self.wants) + raise + self.stats["waited_s"] += time.time() - w.since + return lease + + def release(self, lease: HostLease) -> None: + if lease.released: + return + lease.released = True + h = lease.host + h.allocated = h.allocated - lease.req.resources + h.leases -= 1 + h.last_used = time.time() + self._kick() + + def add_label(self, host: Host, label: str) -> None: + if label not in host.labels: + host.labels.add(label) + self._save() + + async def run(self, host: Host, command: str, *, timeout: float | None = 600, + stdin: bytes | None = None) -> ExecResult: + """Run a shell command on the host (over SSH, or however the provider reaches it).""" + run = getattr(self.provider, "run", None) + if run is not None: + return await run(host, command, timeout=timeout, stdin=stdin) + from ..sandbox.local import run_process + + return await run_process(host.ssh_argv(command), timeout=timeout, env=None, cwd=None, stdin=stdin) + + async def docker(self, host: Host, *args: str, timeout: float | None = 600, stdin: bytes | None = None, + stdin_path: Path | None = None) -> ExecResult: + """Run `docker -H ...` locally.""" + from ..sandbox.local import run_process + + argv = [self.docker_bin, "-H", host.docker_host, *args] + if stdin_path is not None: + start = time.time() + with open(stdin_path, "rb") as f: + proc = await asyncio.create_subprocess_exec(*argv, stdin=f, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, env=host.docker_env()) + out, err = await asyncio.wait_for(proc.communicate(), timeout) + return ExecResult(proc.returncode or 0, out.decode(errors="replace"), err.decode(errors="replace"), + False, time.time() - start) + return await run_process(argv, timeout=timeout, env=host.docker_env(), cwd=None, stdin=stdin) + + async def ensure_image(self, host: Host, image: str, source: dict | None = None) -> None: + """Make sure `image` exists on `host` (inspect; else build / load / pull per + `source`), and record it as the host label `image:` for locality.""" + label = f"image:{image}" + if label in host.labels: + return + lock = self._image_locks.setdefault((host.id, image), asyncio.Lock()) + async with lock: + if label in host.labels: + return + r = await self.docker(host, "image", "inspect", "--format", "{{.Id}}", image, timeout=120) + if r.exit_code != 0: + source = source or {} + t = time.time() + if source.get("build"): + ctx = self._path(source["build"]) + args = ["build", "-q", "-t", image] + if source.get("dockerfile"): + args += ["-f", str(self._path(source["dockerfile"]))] + for k, v in (source.get("build_args") or {}).items(): + args += ["--build-arg", f"{k}={v}"] + r = await self.docker(host, *args, str(ctx), timeout=source.get("timeout", 3600)) + elif source.get("load"): + r = await self.docker(host, "load", timeout=source.get("timeout", 3600), + stdin_path=self._path(source["load"])) + if r.exit_code == 0 and source.get("tag_from"): + r = await self.docker(host, "tag", source["tag_from"], image, timeout=60) + else: + r = await self.docker(host, "pull", source.get("pull") or image, + timeout=source.get("timeout", 3600)) + if r.exit_code == 0 and source.get("pull") and source["pull"] != image: + r = await self.docker(host, "tag", source["pull"], image, timeout=60) + if r.exit_code != 0: + raise InfraError(f"host {host.id}: cannot provide image {image}: {r.stderr.strip()[-500:]}") + self._event("image", host=host.id, image=image, seconds=round(time.time() - t, 1)) + self.add_label(host, label) + + async def reverse(self, host: Host, local_port: int, *, loopback: bool = False) -> int: + """A port on `host`'s Docker bridge gateway that connects to 127.0.0.1:`local_port` + here: an SSH reverse tunnel (`ssh -N -R`, one per host and local port, kept until + drain) plus a small relay on the host, because sshd binds -R ports to loopback. + Bridge containers reach it as host.docker.internal:; with `loopback` the + loopback port itself is returned (for containers on the host network).""" + import random + + + key = (host.id, local_port) + if key in self._tunnels and self._tunnels[key][0].returncode is None: + return self._tunnels[key][3 if loopback else 2] + if self._tunnel_lock is None: + self._tunnel_lock = asyncio.Lock() + async with self._tunnel_lock: + if key in self._tunnels and self._tunnels[key][0].returncode is None: + return self._tunnels[key][3 if loopback else 2] + r = await self.docker(host, "network", "inspect", "bridge", "--format", + "{{(index .IPAM.Config 0).Gateway}}", timeout=60) + gateway = r.stdout.strip() + if r.exit_code != 0 or not gateway: + raise InfraError(f"host {host.id}: cannot find the Docker bridge gateway: {r.stderr[-300:]}") + base = host.ssh_argv(None) + last = "tunnel did not come up" + for _ in range(5): + rport, relay = random.randint(20000, 40000), random.randint(40001, 60000) + proc = await asyncio.create_subprocess_exec( + *base[:-1], "-N", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", + "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=30", "-R", + f"127.0.0.1:{rport}:127.0.0.1:{local_port}", base[-1], + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.PIPE, start_new_session=True) + start = await self.run(host, f"nohup python3 -c {_shq(RELAY_SCRIPT)} {gateway} {relay} {rport} " + f">/dev/null 2>&1 & echo $!", timeout=60) + # hosts often drop container->host traffic in INPUT; open just this port (best effort) + await self.run(host, f"sudo -n iptables -I INPUT -s {_bridge_subnet(gateway)} -d {gateway} -p tcp " + f"--dport {relay} -j ACCEPT 2>/dev/null || true", timeout=60) + pid = start.stdout.strip().splitlines()[-1] if start.stdout.strip() else "" + code = (f"import socket, time\nfor i in range(60):\n try:\n" + f" socket.create_connection(('{gateway}', {relay}), 1).close()\n" + f" socket.create_connection(('127.0.0.1', {rport}), 1).close()\n" + f" break\n except OSError:\n time.sleep(0.25)\n" + f"else:\n raise SystemExit(1)\n") + probe = f"python3 -c {_shq(code)}" + ok = await self.run(host, probe, timeout=60) + if ok.exit_code == 0 and proc.returncode is None: + self._tunnels[key] = (proc, pid, relay, rport) + self._event("tunnel", host=host.id, local_port=local_port, relay_port=relay, loopback_port=rport) + return rport if loopback else relay + if proc.returncode is None: + proc.kill() + err = (await proc.stderr.read()).decode(errors="replace") if proc.stderr else "" + last = f"{err.strip()[-300:]} {ok.stderr.strip()[-200:]}" + if pid: + await self.run(host, f"kill {pid} 2>/dev/null || true", timeout=30) + raise InfraError(f"host {host.id}: reverse tunnel failed: {last}") + + async def _close_tunnels(self) -> None: + for (hid, _), (proc, pid, _, _) in list(self._tunnels.items()): + if proc.returncode is None: + proc.kill() + h = self.hosts.get(hid) + if pid and h is not None and h.state == "ready": + try: + await self.run(h, f"kill {pid} 2>/dev/null || true", timeout=30) + except Exception: + pass + self._tunnels.clear() + self._tunnel_lock = None + + def snapshot(self) -> dict: + return {"hosts": [h.view() for h in self.hosts.values()], "pending_creates": len(self.pending), + "waiting": len([w for w in self.wants if not w.future.done()]), + "used_hours": round(self.used_hours, 4), "usd": round(self.used_hours * self.provider.cost_per_hour, 4), + "exhausted": self.exhausted, "last_error": self.last_error, **self.stats} + + # ------------------------------------------------------------------ lifecycle + async def _start(self) -> None: + loop = asyncio.get_running_loop() + if self._loop is loop and self._ticker is not None and not self._ticker.done(): + return + if self._start_lock is None or self._loop is not loop: + self._start_lock = asyncio.Lock() + self._loop = loop + async with self._start_lock: + if self._ticker is not None and not self._ticker.done(): + return + self.state_dir.mkdir(parents=True, exist_ok=True) + if self.persist: + await self._adopt() + self._last_tick = time.time() + self._ticker = asyncio.create_task(self._tick_loop(), name=f"hostpool:{self.name}") + + async def _adopt(self) -> None: + """Take over hosts a previous process left running (`persist: true`).""" + for hid, d in self._load().items(): + if hid in self.hosts or d.get("state") not in ("ready",): + continue + host = Host.from_dict(d) + try: + ok = await self.provider.alive(host) and (await self.docker(host, "info", "--format", "{{.NCPU}}", + timeout=60)).exit_code == 0 + except Exception: + ok = False + if ok: + host.last_used = time.time() + self.hosts[hid] = host + self.stats["adopted"] += 1 + self._event("adopted", host=hid) + else: + self._event("adopt_failed", host=hid) + self._save() + + async def drain(self) -> None: + """End of a run: fail waiters, finish pending creations, delete hosts (unless + `persist`), and account the final host time.""" + if self._ticker is not None: + self._ticker.cancel() + try: + await self._ticker + except (asyncio.CancelledError, Exception): + pass + self._ticker = None + for w in self.wants: + if not w.future.done(): + w.future.set_exception(InfraError(f"host pool {self.name} is draining")) + self.wants = [] + if self.pending: + await asyncio.gather(*list(self.pending.values()), return_exceptions=True) + await self._close_tunnels() + self._account() + if not self.persist: + await asyncio.gather(*(self._delete(h, "drain") for h in list(self.hosts.values())), + return_exceptions=True) + self._save() + self._loop = None + self._start_lock = None + + async def scale_to(self, n: int) -> list[str]: + """Create hosts until `n` exist (for `pw hosts up`); returns errors.""" + await self._start() + n = min(n, self.max) + while len(self._alive()) + len(self.pending) < n: + self._start_create() + if self.pending: + await asyncio.gather(*list(self.pending.values()), return_exceptions=True) + return [self.last_error] if self.last_error and len(self._alive()) < n else [] + + # ------------------------------------------------------------------ placement + def _fits(self, h: Host, req: Requirements) -> bool: + return (h.state == "ready" and (h.kvm or not req.kvm) and (h.gpu or not req.gpu) + and req.labels <= h.labels and req.resources.fits_in(h.free)) + + def _place(self, req: Requirements) -> Host | None: + best, best_score = None, None + for h in self.hosts.values(): + if not self._fits(h, req): + continue + left = h.free - req.resources + score = (-len(req.prefer & h.labels), left.cpus + left.memory / 2**30, h.created) + if best_score is None or score < best_score: + best, best_score = h, score + return best + + def _kick(self) -> None: + if not self.wants: + return + remaining: list[_Want] = [] + for w in sorted(self.wants): + if w.future.done(): + continue + h = self._place(w.req) + if h is None: + remaining.append(w) + continue + h.allocated = h.allocated + w.req.resources + h.leases += 1 + h.last_used = time.time() + self.stats["placed"] += 1 + w.future.set_result(HostLease(self, h, w.req)) + self.wants = remaining + heapq.heapify(self.wants) + if self.wants: + self._scale_up() + + def _alive(self) -> list[Host]: + return [h for h in self.hosts.values() if h.state in ("creating", "setup", "ready")] + + def _scale_up(self) -> None: + if self.exhausted: + if not self._alive() and not self.pending: + self._fail_wants(BudgetExceeded(f"host pool {self.name}: {self.exhausted}")) + return + if self.failures > self.create_retries and not any(h.state == "ready" for h in self.hosts.values()) \ + and not self.pending: + self._fail_wants(InfraError(f"host pool {self.name}: cannot create hosts " + f"({self.failures} failures): {self.last_error}")) + self.failures = 0 # the engine retries the items; allow fresh attempts then + return + if time.time() < self._create_blocked_until: + return # backing off after a failed creation; the ticker kicks again + shape = self.host_shape() + # capacity that is on its way: hosts being created/set up (free = full shape) + bins: list[Resources] = [] + for h in self.hosts.values(): + if h.state in ("creating", "setup"): + bins.append(h.capacity - h.allocated if h.capacity.cpus else (shape or Resources())) + bins += [shape or Resources()] * len([t for hid, t in self.pending.items() if hid not in self.hosts]) + unknown = shape is None + new = 0 + room = self.max - len(self._alive()) - len([hid for hid in self.pending if hid not in self.hosts]) + for w in sorted(self.wants): + static = self.provider.labels() | {"kvm"} + if {lbl for lbl in w.req.labels - static if not lbl.startswith(("image:", "volume:"))}: + continue # needs a label new hosts will not have; wait for existing hosts + if unknown: + if bins: + continue + if new < room: + bins.append(Resources()) + new += 1 + continue + for i, b in enumerate(bins): + if w.req.resources.fits_in(b): + bins[i] = b - w.req.resources + break + else: + if new < room: + bins.append(shape - w.req.resources) # type: ignore[operator] + new += 1 + if new and self._budget_room() <= 0: + self.exhausted = self.exhausted or "budget exhausted" + return + for _ in range(new): + self._start_create() + + def _fail_wants(self, exc: Exception) -> None: + for w in self.wants: + if not w.future.done(): + w.future.set_exception(exc) + self.wants = [] + + def _budget_room(self) -> float: + """Remaining host-hours (inf if unlimited).""" + room = float("inf") + if self.budget_hours is not None: + room = min(room, float(self.budget_hours) - self.used_hours) + if self.budget_usd is not None and self.provider.cost_per_hour: + room = min(room, (float(self.budget_usd) - self.used_hours * self.provider.cost_per_hour) + / self.provider.cost_per_hour) + return room + + # ------------------------------------------------------------------ hosts + def _start_create(self) -> None: + attempts = self.stats["created"] + self.stats["failed_create"] + len(self.pending) + if attempts >= self.create_limit: + if not self.exhausted: + self.exhausted = f"create limit reached ({self.create_limit} host creations)" + self._event("create_limit", limit=self.create_limit) + return + hid = f"{self.name}-{uuid.uuid4().hex[:6]}" + self.pending[hid] = asyncio.create_task(self._create(hid), name=f"host-create:{hid}") + + async def _create(self, hid: str) -> None: + d = self.state_dir / hid + d.mkdir(parents=True, exist_ok=True) + host: Host | None = None + t = time.time() + self._event("creating", host=hid) + try: + host = await self.provider.create(hid, d) + host.id, host.pool, host.state_dir, host.state = hid, self.name, str(d), "setup" + host.kvm = host.kvm or self.provider.kvm() + host.gpu = host.gpu or self.provider.gpu() + host.labels |= self.provider.labels() + self.hosts[hid] = host + self.stats["peak_hosts"] = max(self.stats["peak_hosts"], len(self._alive())) + self._save() + self._event("created", host=hid, seconds=round(time.time() - t, 1)) + await self._setup(host) + host.state, host.ready_at, host.last_used = "ready", time.time(), time.time() + self.failures = 0 + self.stats["created"] += 1 + self._save() + self._event("ready", host=hid, seconds=round(time.time() - t, 1), capacity=host.capacity.view()) + except asyncio.CancelledError: + if host is not None: + await asyncio.shield(self._delete(host, "cancelled")) + raise + except Exception as e: + self.failures += 1 + self.stats["failed_create"] += 1 + self._create_blocked_until = time.time() + min(120.0, self.create_backoff * 2 ** (self.failures - 1)) + self.last_error = f"{type(e).__name__}: {str(e)[:400]}" + self._event("create_failed", host=hid, error=self.last_error) + log.warning("host pool %s: creating %s failed: %s", self.name, hid, self.last_error) + if host is not None: + try: + await self._delete(host, "setup failed") + except Exception as de: # pragma: no cover + self._event("delete_failed", host=hid, error=str(de)[:300]) + finally: + self.pending.pop(hid, None) + self._kick() + + async def _setup(self, host: Host) -> None: + deadline = time.time() + self.ssh_wait + while True: + try: + r = await self.run(host, "true", timeout=60) + if r.exit_code == 0: + break + err = r.stderr.strip()[-300:] + except InfraError as e: + err = str(e) + if time.time() > deadline: + raise InfraError(f"host {host.id}: not reachable over SSH: {err}") + await asyncio.sleep(3) + if self.kvm_runtime: + r = await self.run(host, "bash -s", timeout=600, stdin=KVM_RUNTIME_SCRIPT.encode()) + if r.exit_code != 0: + raise InfraError(f"host {host.id}: kvm runtime setup failed: {r.summary(600)}") + for cmd in self.setup_cmds: + r = await self.run(host, cmd, timeout=self.config.get("setup_timeout", 1800)) + if r.exit_code != 0: + raise InfraError(f"host {host.id}: setup command failed: {cmd!r}: {r.summary(600)}") + r = await self.docker(host, "info", "--format", "{{.NCPU}} {{.MemTotal}}", timeout=120) + if r.exit_code != 0: + raise InfraError(f"host {host.id}: docker not usable: {r.stderr.strip()[-400:]}") + cap = self.provider.capacity() + if cap is None: + try: + ncpu, mem = r.stdout.split()[:2] + cap = Resources(float(ncpu), float(mem)) + except ValueError as e: + raise InfraError(f"host {host.id}: cannot read capacity from docker info: {r.stdout!r}") from e + host.capacity = cap - self.reserve + if host.kvm: + k = await self.run(host, "test -c /dev/kvm", timeout=60) + if k.exit_code != 0: + host.kvm = False + self._event("no_kvm", host=host.id) + else: + host.labels.add("kvm") + imgs = await self.docker(host, "image", "ls", "--format", "{{.Repository}}:{{.Tag}}", timeout=120) + if imgs.exit_code == 0: + host.labels |= {f"image:{x}" for x in imgs.stdout.split() if not x.endswith(":")} + + async def _delete(self, host: Host, why: str) -> None: + if host.state == "deleted": + return + host.state = "draining" + try: + await asyncio.shield(self.provider.delete(host)) + except Exception as e: + host.state = "broken" + self._event("delete_failed", host=host.id, error=f"{type(e).__name__}: {str(e)[:300]}") + self._save() + raise + host.state = "deleted" + self.hosts.pop(host.id, None) + self.stats["deleted"] += 1 + self._event("deleted", host=host.id, why=why, age_s=round(time.time() - host.created, 1)) + self._save() + + # ------------------------------------------------------------------ background + def _account(self) -> None: + now = time.time() + dt = max(0.0, now - self._last_tick) + self._last_tick = now + n = len([h for h in self.hosts.values() if h.state != "deleted"]) + hours = n * dt / 3600 + if not hours: + return + self.used_hours += hours + for b in self.budgets: + b.add(vm_hours=hours, usd=hours * self.provider.cost_per_hour) + if self._budget_room() <= 0 and not self.exhausted: + self.exhausted = f"budget exhausted ({self.used_hours:.3f} host-hours)" + self._event("budget_exhausted", used_hours=round(self.used_hours, 3)) + + async def _tick_loop(self) -> None: + while True: + await asyncio.sleep(self.tick) + try: + await self._tick() + except asyncio.CancelledError: + raise + except Exception as e: # pragma: no cover - keep the pool alive + log.warning("host pool %s tick: %s", self.name, e) + + async def _tick(self) -> None: + self._account() + now = time.time() + if self.ttl: + for h in list(self.hosts.values()): + if h.state in ("ready", "setup") and h.expires and h.expires - now < self.extend_margin: + try: + new = await self.provider.extend(h, self.ttl) + if new: + h.expires = new + self.stats["extended"] += 1 + self._event("extended", host=h.id, expires_in_s=round(new - now)) + except Exception as e: + self._event("extend_failed", host=h.id, error=str(e)[:300]) + ready = [h for h in self.hosts.values() if h.state == "ready"] + waiting = any(not w.future.done() for w in self.wants) + if not waiting: + for h in sorted(ready, key=lambda x: x.last_used): + if len(ready) <= self.min: + break + if h.leases == 0 and now - h.last_used >= self.idle_shutdown: + ready.remove(h) + try: + await self._delete(h, f"idle {now - h.last_used:.0f}s") + except Exception: + pass + if not self.exhausted and len(self._alive()) + len(self.pending) < self.min: + self._start_create() + self._kick() + + # ------------------------------------------------------------------ state + def _path(self, p: str) -> Path: + return self.project.resolve_path(p) if self.project is not None else Path(p).expanduser().resolve() + + def _event(self, what: str, **kw: Any) -> None: + ev = {"at": round(time.time(), 1), "event": what, **kw} + self.events.append(ev) + del self.events[:-200] + log.info("host pool %s: %s", self.name, ev) + try: + self.state_dir.mkdir(parents=True, exist_ok=True) + with open(self.state_dir / "events.jsonl", "a") as f: + f.write(json.dumps(ev) + "\n") + except OSError: + pass + + def _load(self) -> dict[str, dict]: + p = self.state_dir / "state.json" + try: + return json.loads(p.read_text()).get("hosts", {}) + except (OSError, ValueError): + return {} + + def _save(self) -> None: + try: + self.state_dir.mkdir(parents=True, exist_ok=True) + p = self.state_dir / "state.json" + tmp = p.with_suffix(".tmp") + tmp.write_text(json.dumps({"pool": self.name, "type": self.provider.type, "updated": time.time(), + "hosts": {h.id: h.to_dict() for h in self.hosts.values()}}, indent=1)) + tmp.replace(p) + except OSError as e: # pragma: no cover + log.warning("host pool %s: cannot save state: %s", self.name, e) diff --git a/src/pipewright/hosts/static.py b/src/pipewright/hosts/static.py new file mode 100644 index 0000000..f953d21 --- /dev/null +++ b/src/pipewright/hosts/static.py @@ -0,0 +1,101 @@ +"""Built-in host providers: `static` (a fixed list of SSH hosts) and `fake` (tests). + + hosts: + lab: + type: static + addresses: [ssh://me@build-1, ssh://me@build-2:2222] + max: 2 # defaults to len(addresses) + capacity: {cpus: 32, memory: 128g} # optional; else probed with docker info + +`static` never creates or deletes machines; "create" claims the next unused address and +"delete" releases it (containers it started are removed by the sandbox provider). + +`fake` makes in-memory hosts for tests of placement and scaling. Host commands are +only RECORDED (never executed locally — setup scripts use sudo and reconfigure Docker); +they succeed unless they match a `fail_commands` regex. Pair it with a fake `docker` +binary (the `docker:` config key). +""" + +from __future__ import annotations + +import asyncio +import time +from pathlib import Path + +from ..errors import ConfigError, InfraError +from ..registry import register_host_provider +from .base import Host, HostProvider + + +class StaticHosts(HostProvider): + type = "static" + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + self.addresses: list[str] = list(config.get("addresses") or []) + if not self.addresses: + raise ConfigError(f"hosts.{name}: static hosts need `addresses: [ssh://user@host, ...]`") + config.setdefault("max", len(self.addresses)) + self.claimed: set[str] = set() + + async def create(self, host_id: str, state_dir: Path) -> Host: + for a in self.addresses: + if a not in self.claimed: + self.claimed.add(a) + return Host(id=host_id, pool=self.name, docker_host=a if a.startswith("ssh://") else f"ssh://{a}", + meta={"address": a}) + raise InfraError(f"hosts.{self.name}: all {len(self.addresses)} static hosts are in use") + + async def delete(self, host: Host) -> None: + self.claimed.discard(host.meta.get("address", "")) + + +class FakeHosts(HostProvider): + """Hosts that exist only in memory; host commands are recorded, not run. Config: + `create_delay` (s), `fail_create` (inject N failures), `fail_commands` (regexes), + `capacity`, `kvm`.""" + + type = "fake" + default_capacity = {"cpus": 4, "memory": "8g"} + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + self.fail_create = int(config.get("fail_create", 0)) + self.created: list[str] = [] + self.deleted: list[str] = [] + self.extended: list[str] = [] + self.commands: list[tuple[str, str]] = [] + + async def create(self, host_id: str, state_dir: Path) -> Host: + await asyncio.sleep(float(self.config.get("create_delay", 0))) + if self.fail_create > 0: + self.fail_create -= 1 + raise InfraError("injected host create failure") + self.created.append(host_id) + ttl = self.config.get("ttl") + return Host(id=host_id, pool=self.name, docker_host=f"ssh://fake-{host_id}", + expires=time.time() + float(ttl) if ttl else None, meta={"vm_id": f"vm-{host_id}"}) + + async def delete(self, host: Host) -> None: + self.deleted.append(host.id) + + async def extend(self, host: Host, seconds: float) -> float | None: + self.extended.append(host.id) + return time.time() + seconds + + async def run(self, host: Host, command: str, *, timeout=None, stdin=None): + import re + + from ..sandbox.base import ExecResult + + self.commands.append((host.id, command)) + if command.startswith("test -c /dev/kvm"): + return ExecResult(0 if self.config.get("kvm") else 1, "", "") + for rx in self.config.get("fail_commands") or []: + if re.search(rx, command): + return ExecResult(1, "", f"injected failure for {command!r}") + return ExecResult(0, "", "") + + +register_host_provider("static", StaticHosts) +register_host_provider("fake", FakeHosts) diff --git a/src/pipewright/hosts/vmapi.py b/src/pipewright/hosts/vmapi.py new file mode 100644 index 0000000..83f9a3a --- /dev/null +++ b/src/pipewright/hosts/vmapi.py @@ -0,0 +1,126 @@ +"""Base class for host providers backed by an HTTP "VM API" (create with TTL, register +an SSH key, extend, delete). Subclasses implement the API calls; this class handles +the secret, the HTTP client, the per-host SSH config (pinned host key, ControlMaster +so `docker -H ssh://` and setup commands reuse one connection) and waiting for SSH. + + hosts: + vms: + type: # e.g. boat (pipewright.contrib.boat) + api_key: {file: ~/.config/x/secrets, var: API_KEY} # secret ref; never logged + ssh_key: ~/.ssh/id_ed25519 # private key; .pub is registered with the VM + ttl: 3600 # the pool extends it while the host is needed +""" + +from __future__ import annotations + +import asyncio +import shlex +from pathlib import Path +from typing import Any + +import httpx + +from ..errors import ConfigError, InfraError +from .base import Host, HostProvider + + +class VMApiHostProvider(HostProvider): + api_base: str = "" + name_prefix: str = "pw" + + def __init__(self, name, config, project=None): + super().__init__(name, config, project) + self.base = str(config.get("api_base") or self.api_base).rstrip("/") + if not self.base: + raise ConfigError(f"hosts.{name}: `api_base` is required") + if not isinstance(config.get("api_key"), dict): + raise ConfigError(f"hosts.{name}: `api_key` must be a secret reference ({{env: VAR}} or " + "{file: path, var: KEY}); literal keys are rejected") + self.ssh_key = Path(config.get("ssh_key", "~/.ssh/id_ed25519")).expanduser() + self.ttl = int(config.get("ttl", 3600)) + self.prefix = str(config.get("name_prefix") or f"{self.name_prefix}-{name}") + self._client: httpx.AsyncClient | None = None + + # ------------------------------------------------------------------ http + def _key(self) -> str: + from ..project import SecretRef + + return SecretRef.model_validate(self.config["api_key"]).resolve() + + def client(self) -> httpx.AsyncClient: + loop = asyncio.get_running_loop() + if self._client is None or getattr(self, "_client_loop", None) is not loop: + self._client = httpx.AsyncClient(timeout=float(self.config.get("http_timeout", 60))) + self._client_loop = loop + return self._client + + async def request(self, method: str, path: str, *, json: Any = None, headers: dict | None = None, + ok: tuple[int, ...] = (200, 201, 202, 204), retries: int = 4) -> Any: + """HTTP call with bearer auth; retries 429/5xx/transport. Errors never include the key.""" + url = f"{self.base}{path}" + delay = 2.0 + for attempt in range(retries + 1): + try: + r = await self.client().request(method, url, json=json, headers={ + "Authorization": f"Bearer {self._key()}", "Content-Type": "application/json", + **(headers or {})}) + except httpx.HTTPError as e: + if attempt == retries: + raise InfraError(f"{self.type} API {method} {path}: {type(e).__name__}: {e}") from None + else: + if r.status_code in ok: + return r.json() if r.content and "json" in r.headers.get("content-type", "") else None + if r.status_code not in (408, 429) and r.status_code < 500 or attempt == retries: + raise InfraError(f"{self.type} API {method} {path}: HTTP {r.status_code}: {r.text[:300]}") + await asyncio.sleep(delay) + delay = min(30.0, delay * 2) + + # ------------------------------------------------------------------ ssh + def public_key(self) -> str: + pub = self.ssh_key.with_name(self.ssh_key.name + ".pub") + if not pub.exists(): + raise ConfigError(f"hosts.{self.name}: public key {pub} not found (set `ssh_key`)") + return pub.read_text().strip() + + def write_ssh_config(self, state_dir: Path, alias: str, hostname: str, port: int, user: str, + host_key: str | None, key_alias: str) -> Path: + state_dir.mkdir(parents=True, exist_ok=True) + kh = state_dir / "known_hosts" + if host_key: + kh.write_text(f"{key_alias} {host_key}\n") + cfg = state_dir / "ssh_config" + cfg.write_text("\n".join([ + f"Host {alias}", + f" HostName {hostname}", + f" Port {port}", + f" User {user}", + f" IdentityFile {self.ssh_key}", + " IdentitiesOnly yes", + f" HostKeyAlias {key_alias}", + f" UserKnownHostsFile {kh}", + f" StrictHostKeyChecking {'yes' if host_key else 'accept-new'}", + " ServerAliveInterval 30", + " ConnectTimeout 30", + " ControlMaster auto", + " ControlPath /tmp/pw-ssh-%C", + " ControlPersist 600", + " LogLevel ERROR", + "", + ])) + return cfg + + @staticmethod + def quote(s: str) -> str: + return shlex.quote(s) + + async def aclose(self) -> None: + if self._client is not None: + try: + await self._client.aclose() + except RuntimeError: + pass + self._client = None + + def _host(self, host_id: str, state_dir: Path, alias: str, cfg: Path, **meta: Any) -> Host: + return Host(id=host_id, pool=self.name, docker_host=f"ssh://{alias}", ssh_config=str(cfg), + state_dir=str(state_dir), meta=meta) diff --git a/src/pipewright/imports.py b/src/pipewright/imports.py new file mode 100644 index 0000000..6a566da --- /dev/null +++ b/src/pipewright/imports.py @@ -0,0 +1,161 @@ +"""Cross-graph edges: building new work on top of earlier results. + +A graph may declare `imports` (alias -> another graph) and refer to that graph's +outputs as `alias:node.port` in its inputs: + + imports: + build: {graph: graph_build.yaml} # or graph: self, run: previous + nodes: + harden: {type: llm.generate, inputs: {in: "build:bucket.too_easy"}, ...} + +Before checking or running, `expand_imports` turns every referenced `alias:node` +into a virtual source node of type `graph.import` (node id `alias:node`, one output +per referenced port) that reads the items which flowed out of that port in the +selected upstream run(s). The edges stay exactly as written, so funnels, reports and +`--upto` treat imported ports like any other upstream node. Imported items keep their +ids, so work done on them before is memoized and only new upstream items cost anything. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from .errors import ConfigError +from .graph import GraphSpec, NodeSpec, is_import_ref, load_graph, split_ref +from .nodes.base import ANY, SAME + +if TYPE_CHECKING: + from .project import Project + + +@dataclass +class ResolvedImport: + alias: str + graph: str + """Name of the imported graph (as recorded in its runs).""" + store: Path + same_store: bool + spec: GraphSpec | None + run: str + where: str | None + source: str + """Human-readable origin (file path or `self`).""" + + +def resolve_import(spec: GraphSpec, alias: str, project: "Project") -> ResolvedImport: + from .project import Project + + imp = spec.imports.get(alias) + if imp is None: + raise ConfigError(f"unknown import alias {alias!r}; declared: {sorted(spec.imports)}") + here = project.store_dir.resolve() + if imp.graph in ("self", "."): + return ResolvedImport(alias, spec.name, here, True, spec, imp.run if imp.run != "latest" else "previous", + imp.where, "self") + if imp.store: + store = (spec.base_dir / Path(imp.store).expanduser()).resolve() + return ResolvedImport(alias, imp.graph, store, store == here, None, imp.run, imp.where, str(store)) + path = (spec.base_dir / Path(imp.graph).expanduser()).resolve() + if not path.exists(): + raise ConfigError(f"import {alias!r}: graph file not found: {path}") + ispec = load_graph(path) + iproj = Project.discover(path.parent, (spec.base_dir / imp.project).resolve() if imp.project else None) + store = iproj.store_dir.resolve() + return ResolvedImport(alias, ispec.name, store, store == here, ispec, imp.run, imp.where, str(path)) + + +def port_kinds(spec: GraphSpec, project: "Project | None" = None) -> dict[tuple[str, str], str]: + """Item kind produced on every (node, port), inferred along the DAG (`same` resolved).""" + from .registry import registry + + produced: dict[tuple[str, str], str] = {} + try: + order = spec.topo_order() + except ConfigError: + return produced + for nid in order: + n = spec.nodes[nid] + cls = registry.node_types.get(n.type) + if cls is None: + continue + try: + p = cls.Params.model_validate(n.params) + except Exception: + continue + ins = {produced.get(split_ref(r), ANY) for r in n.inputs.get("in", [])} + same = next(iter(ins)) if len(ins) == 1 else ANY + for port, sp in cls.output_ports(p).items(): + produced[(nid, port)] = same if sp.kind == SAME else sp.kind + return produced + + +def import_refs(spec: GraphSpec) -> dict[str, set[str]]: + """`alias:node` -> referenced ports.""" + out: dict[str, set[str]] = {} + for n in spec.nodes.values(): + for refs in n.inputs.values(): + for r in refs: + node, port = split_ref(r) + if is_import_ref(node): + out.setdefault(node, set()).add(port) + return out + + +def expand_imports(spec: GraphSpec, project: "Project", *, strict: bool = True, + problems: list[tuple[str, str, str]] | None = None, _depth: int = 0) -> GraphSpec: + """A copy of `spec` where each referenced `alias:node` is a `graph.import` node. + + Problems (unknown alias, missing upstream node/port) raise ConfigError when + `strict`, else are appended to `problems` as (node_id, port, message).""" + refs = import_refs(spec) + if not refs or all(v in spec.nodes for v in refs): + return spec + if _depth > 8: + raise ConfigError("imports nested too deeply (cycle between graphs?)") + out = spec.model_copy(deep=True) + out._base_dir = spec._base_dir + resolved: dict[str, ResolvedImport] = {} + + def problem(nid: str, port: str, msg: str) -> None: + if strict: + raise ConfigError(msg) + if problems is not None: + problems.append((nid, port, msg)) + + for vnode, ports in sorted(refs.items()): + if vnode in spec.nodes: + continue # already expanded + alias, _, unode = vnode.partition(":") + try: + if alias not in resolved: + resolved[alias] = resolve_import(spec, alias, project) + ri = resolved[alias] + except ConfigError as e: + problem(vnode, "", str(e)) + continue + kinds: dict[str, str] = {p: ANY for p in ports} + if ri.spec is not None: + if unode not in ri.spec.nodes: + problem(vnode, "", f"import {alias!r}: graph {ri.graph!r} has no node {unode!r}; " + f"nodes: {sorted(ri.spec.nodes)}") + continue + uspec = ri.spec if ri.source == "self" else expand_imports(ri.spec, project, strict=False, + _depth=_depth + 1) + pk = port_kinds(uspec) + for p in ports: + if (unode, p) not in pk: + avail = sorted(pp for (nn, pp) in pk if nn == unode) + problem(vnode, p, f"import {alias!r}: node {unode!r} of graph {ri.graph!r} has no output " + f"port {p!r}; ports: {avail}") + kinds[p] = pk.get((unode, p), ANY) + out.nodes[vnode] = NodeSpec( + type="graph.import", + params={"graph": ri.graph, "store": None if ri.same_store else str(ri.store), "node": unode, + "ports": kinds, "run": ri.run, "where": ri.where, "alias": alias, "source": ri.source}, + description=f"imported from {ri.source} ({ri.graph}:{unode}, run={ri.run})") + # imported sources first (funnels and reports list nodes in this order) + out.nodes = {**{k: v for k, v in out.nodes.items() if k not in spec.nodes}, + **{k: v for k, v in out.nodes.items() if k in spec.nodes}} + return out diff --git a/src/pipewright/items.py b/src/pipewright/items.py new file mode 100644 index 0000000..e993d79 --- /dev/null +++ b/src/pipewright/items.py @@ -0,0 +1,128 @@ +"""Items: immutable records flowing through a graph. + +An item never changes after creation. A node that "labels" or "rewrites" an item +creates a new item whose `parents` name the input(s) and whose `producer` names the +node. The `id` is a content hash over everything that defines the item, including its +lineage, so identical work yields identical ids (which is what makes per-item +memoization and dedup work), and `key` is a human-readable logical identity that is +inherited through derivations (e.g. `issue#123`, `issue#123/rollout-1`). +""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from .hashing import digest + +Provenance = Literal["real", "derived", "synthetic"] + + +class ArtifactRef(BaseModel): + """A blob in the content-addressed store.""" + + model_config = ConfigDict(frozen=True) + + sha256: str + size: int + media_type: str = "application/octet-stream" + name: str | None = None + + +class Item(BaseModel): + model_config = ConfigDict(frozen=True) + + id: str = "" + key: str + kind: str + payload: dict[str, Any] = Field(default_factory=dict) + labels: dict[str, Any] = Field(default_factory=dict) + artifacts: dict[str, ArtifactRef] = Field(default_factory=dict) + parents: tuple[str, ...] = () + producer: str | None = None + """Node id that produced this item (None for items created outside a graph).""" + op: str | None = None + """Node type and version that produced it, e.g. `llm.label@1`.""" + provenance: Provenance = "real" + + @model_validator(mode="after") + def _fill_id(self) -> "Item": + if not self.id: + object.__setattr__(self, "id", self.compute_id()) + return self + + def compute_id(self) -> str: + return digest( + { + "key": self.key, + "kind": self.kind, + "payload": self.payload, + "labels": self.labels, + "artifacts": {k: v.sha256 for k, v in self.artifacts.items()}, + "parents": list(self.parents), + "producer": self.producer, + "provenance": self.provenance, + } + ) + + @property + def content_hash(self) -> str: + """Hash of the content alone (no lineage).""" + return digest({"kind": self.kind, "payload": self.payload, "labels": self.labels, + "artifacts": {k: v.sha256 for k, v in self.artifacts.items()}}) + + def derive( + self, + *, + key: str | None = None, + kind: str | None = None, + payload: dict | None = None, + labels: dict | None = None, + update_payload: dict | None = None, + update_labels: dict | None = None, + artifacts: dict[str, ArtifactRef] | None = None, + provenance: Provenance | None = None, + extra_parents: tuple[str, ...] = (), + ) -> "Item": + """A new item derived from this one (the engine fills producer/op).""" + new_payload = dict(self.payload if payload is None else payload) + if update_payload: + new_payload.update(update_payload) + new_labels = dict(self.labels if labels is None else labels) + if update_labels: + new_labels.update(update_labels) + return Item( + key=key or self.key, + kind=kind or self.kind, + payload=new_payload, + labels=new_labels, + artifacts=dict(self.artifacts) if artifacts is None else artifacts, + parents=(self.id, *extra_parents), + provenance=provenance or self.provenance, + ) + + def stamped(self, producer: str, op: str) -> "Item": + """This item with lineage stamped by the engine (recomputes the id).""" + data = self.model_dump() + data.update(id="", producer=producer, op=op) + return Item(**data) + + def get(self, path: str, default: Any = None) -> Any: + """Dotted lookup: `payload.title`, `labels.score`, `key`.""" + cur: Any = {"id": self.id, "key": self.key, "kind": self.kind, "payload": self.payload, + "labels": self.labels, "provenance": self.provenance, "producer": self.producer} + for part in path.split("."): + if isinstance(cur, dict) and part in cur: + cur = cur[part] + elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur): + cur = cur[int(part)] + else: + return default + return cur + + +def new_item(key: str, kind: str, payload: dict | None = None, *, labels: dict | None = None, + provenance: Provenance = "real", parents: tuple[str, ...] = ()) -> Item: + return Item(key=key, kind=kind, payload=payload or {}, labels=labels or {}, + provenance=provenance, parents=parents) diff --git a/src/pipewright/mcp_server.py b/src/pipewright/mcp_server.py new file mode 100644 index 0000000..72b292e --- /dev/null +++ b/src/pipewright/mcp_server.py @@ -0,0 +1,152 @@ +"""MCP server exposing the same operations as the CLI (`pw mcp`, stdio transport). + +A thin layer: every tool calls a function in `pipewright.ops` and returns its JSON +result. Needs the `mcp` extra (`pip install 'pipewright[mcp]'`); works with the mcp +SDK 1.x (FastMCP) and 2.x (MCPServer). +""" + +from __future__ import annotations + +from typing import Any + +from . import ops + +INSTRUCTIONS = """pipewright builds and runs data pipelines as graphs of typed nodes. +Workflow: nodes_list / nodes_describe to learn node types -> write or patch a graph file +-> check_graph until it has no errors -> preview (small sample, upto a node) -> run_graph -> +funnel / items / status to inspect, lineage to trace an item. Graph paths are files on the +server's filesystem (.yaml/.json, or .py builder files for reading).""" + + +def _server_class(): + try: + from mcp.server.mcpserver import MCPServer + + return MCPServer + except ImportError: + try: + from mcp.server.fastmcp import FastMCP + + return FastMCP + except ImportError as e: # pragma: no cover + raise SystemExit("the MCP server needs `pip install 'pipewright[mcp]'`") from e + + +def build_server(): + server = _server_class()(name="pipewright", instructions=INSTRUCTIONS) + + @server.tool() + def nodes_list() -> list[dict]: + """List node types (type, kind, one-line summary).""" + return ops.nodes_list() + + @server.tool() + def nodes_describe(type: str) -> dict: + """Ports, params JSON schema, resources, cost hints and a working example for a node type.""" + return ops.nodes_describe(type) + + @server.tool() + def check_graph(graph: str, project: str | None = None) -> dict: + """Validate a graph file: types, wiring, port kinds, resources, budgets. Fix every error.""" + return ops.check_graph(graph, project) + + @server.tool() + def patch_graph(graph: str, ops_list: list[dict], dry_run: bool = False, force: bool = False, + project: str | None = None) -> dict: + """Apply graph ops (add_node, remove_node, rename_node, connect, disconnect, set_param, set_node); + the file is written only if the patched graph has no errors (unless force).""" + return ops.patch_graph(graph, ops_list, dry_run=dry_run, force=force, project=project) + + @server.tool() + async def preview(graph: str, upto: str | None = None, n: int = 5, project: str | None = None) -> dict: + """Run on the first n source items up to a node and return what came out of it.""" + spec, _ = ops.load(graph, project) + target = upto or spec.topo_order()[-1] + summary = await ops.run_graph_async(graph, project=project, upto=target, limit=n, mode="preview") + res = ops.items(graph, target, run_id=summary["run_id"], n=n, project=project) + return {"run_id": summary["run_id"], "status": summary["status"], "node": target, + "funnel": summary["funnel"], "errors": summary["errors"], "items": res["items"]} + + @server.tool() + async def run_graph(graph: str, upto: str | None = None, limit: int | None = None, + retry_errors: bool = False, project: str | None = None, shard: str | None = None, + group: str | None = None) -> dict: + """Run (or resume) the graph; memoized results are reused. Returns funnel, usage, errors. + shard="I/N" processes only that share of the source items (several workers, one store).""" + return await ops.run_graph_async(graph, project=project, upto=upto, limit=limit, retry_errors=retry_errors, + shard=shard, group=group) + + @server.tool() + def status(graph: str, run_id: str | None = None, project: str | None = None) -> dict: + """State of the latest (or given) run: per-node stats, usage, errors.""" + return ops.status(graph, run_id, project) + + @server.tool() + def funnel(graph: str, run_id: str | None = None, project: str | None = None, group: str | None = None) -> dict: + """Item counts per node, port and edge (imported nodes carry `imported_from`); group= sums + the runs of a run group (e.g. shards).""" + return ops.funnel(graph, run_id, project, group=group) + + @server.tool() + def items(graph: str, node: str, port: str | None = None, n: int = 5, sample: bool = False, + errors: bool = False, run_id: str | None = None, project: str | None = None) -> dict: + """Items that came out of a node (or, with errors=true, its failures and their inputs).""" + return ops.items(graph, node, port=port, n=n, sample=sample, errors=errors, run_id=run_id, project=project) + + @server.tool() + def lineage(graph: str, item_id: str, project: str | None = None, descendants: bool = False, + roots: bool = False) -> dict: + """An item (id, id prefix or key) and its ancestors across graphs sharing the store, with + the graph/run that made each; descendants=true adds every item derived from it (all + variants), roots=true returns only its root sources.""" + return ops.lineage(graph, item_id, project, descendants=descendants, roots=roots) + + @server.tool() + def query(graph: str, node: str | None = None, port: str | None = None, run: str = "latest", + of_graph: str | None = None, where: str | None = None, labels: dict | None = None, + kind: str | None = None, provenance: str | None = None, derived_from: str | None = None, + n: int = 20, project: str | None = None) -> dict: + """Select stored results (e.g. node=bucket, port=too_easy, where='labels.pass_rate >= 0.75', + run=latest|all|group:|); returns items plus the equivalent `store.query` node + to seed a new graph with them.""" + return ops.query(graph, node=node, port=port, run=run, of_graph=of_graph, where=where, labels=labels, + kind=kind, provenance=provenance, derived_from=derived_from, n=n, project=project) + + @server.tool() + async def hosts(action: str = "list", pool: str | None = None, count: int = 1, project: str | None = None, + directory: str = ".") -> dict: + """Host pools: action=list (recorded + provider hosts), up (create `count` hosts and keep + them), down (delete recorded hosts), orphans (delete unrecorded provider hosts).""" + from pathlib import Path + + from .project import Project + + proj = Project.discover(Path(directory), project) + names = [pool] if pool else sorted(proj.config.hosts) + return await ops._hosts(proj, action, names, count) + + @server.tool() + def export(graph: str, node: str, out: str, port: str | None = None, fields: list[str] | None = None, + run_id: str | None = None, project: str | None = None) -> dict: + """Write a node's output items to a JSONL/JSON file.""" + return ops.export(graph, node, out, port=port, fields=fields, run_id=run_id, project=project) + + @server.tool() + def report(graph: str, out: str | None = None, run_id: str | None = None, project: str | None = None) -> dict: + """Write the static HTML report (graph with per-edge counts, samples) and return its path.""" + return ops.report(graph, out, run_id, project) + + @server.tool() + def review(graph: str, node: str, approve: list[str] | None = None, reject: list[str] | None = None, + note: str = "", project: str | None = None) -> dict[str, Any]: + """List items parked at a review node, or approve/reject them by id.""" + if approve or reject: + return ops.review_decide(graph, node, approve or reject or [], + "approved" if approve else "rejected", note, project) + return ops.review_list(graph, node, project=project) + + return server + + +def serve() -> None: + build_server().run() diff --git a/src/pipewright/models/__init__.py b/src/pipewright/models/__init__.py new file mode 100644 index 0000000..a1a2fe2 --- /dev/null +++ b/src/pipewright/models/__init__.py @@ -0,0 +1,5 @@ +"""Model providers: base interface, OpenAI-compatible client, fake provider, logging proxy.""" + +from .base import ChatResult, ModelClient, ModelProvider, Usage + +__all__ = ["ChatResult", "ModelClient", "ModelProvider", "Usage"] diff --git a/src/pipewright/models/base.py b/src/pipewright/models/base.py new file mode 100644 index 0000000..6ef40fd --- /dev/null +++ b/src/pipewright/models/base.py @@ -0,0 +1,240 @@ +"""Model providers and the alias-bound client nodes use. + +A ModelProvider speaks one wire protocol (OpenAI-compatible chat completions in v0) +and owns the provider's RateLimiter. Its single job: `complete(payload) -> dict` +(a non-streaming chat.completion object), raising ProviderError with a real status +for every failure — including the quirky ones (an HTTP 200 whose stream or body is an +error). Retrying, pacing, caching and accounting are layered on top by ModelClient, +so a provider plugin stays small. +""" + +from __future__ import annotations + +import asyncio +import json +import random +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable + +from ..errors import ConfigError, ProviderError, backoff_scale +from ..hashing import digest +from ..scheduler import BudgetTracker, RateLimiter, SharedLedger + +if TYPE_CHECKING: + from ..project import ModelAlias, Project + + +@dataclass +class Usage: + input_tokens: int = 0 + output_tokens: int = 0 + cost_usd: float | None = None + + +@dataclass +class ChatResult: + message: dict + usage: Usage + finish_reason: str | None = None + cached: bool = False + raw: dict = field(default_factory=dict) + + @property + def content(self) -> str: + c = self.message.get("content") + if isinstance(c, list): + return "".join(p.get("text", "") for p in c if isinstance(p, dict)) + return c or "" + + @property + def tool_calls(self) -> list[dict]: + return self.message.get("tool_calls") or [] + + @property + def reasoning(self) -> str | None: + return self.message.get("reasoning_content") or self.message.get("reasoning") + + +def rate_limiter_from(cfg: dict | None, name: str | None = None, base_dir=None) -> RateLimiter: + """Build a provider's RateLimiter from its `rate:` dict. + + `shared: true` (key = provider `name`) or `shared: ""` paces jointly with every + other process using the same key through a SQLite ledger in `shared_dir` + (default ~/.cache/pipewright/rate; relative paths resolve against `base_dir`).""" + cfg = cfg or {} + shared = None + key = cfg.get("shared") + if key: + if key is True: + key = name or "default" + elif not isinstance(key, str): + raise ConfigError(f"rate.shared must be true or a key string, got {key!r}") + directory = cfg.get("shared_dir") + if directory is not None: + d = Path(str(directory)).expanduser() + if not d.is_absolute() and base_dir is not None: + d = Path(base_dir) / d + directory = d + shared = SharedLedger.for_key(key, directory) + return RateLimiter( + requests_per_minute=cfg.get("requests_per_minute"), + input_tokens_per_minute=cfg.get("input_tokens_per_minute"), + output_tokens_per_minute=cfg.get("output_tokens_per_minute"), + initial_output_estimate=cfg.get("output_estimate", 800), + shared=shared, + ) + + +class ModelProvider(ABC): + type: str = "abstract" + + def __init__(self, name: str, config: dict, project: "Project | None" = None): + self.name = name + self.config = config + self.project = project + self.limiter = rate_limiter_from(config.get("rate"), name, + getattr(project, "base_dir", None) if project is not None else None) + self.pricing = config.get("pricing") or {} + + @abstractmethod + async def complete(self, payload: dict) -> dict: + """One chat completion. Raise ProviderError(status=...) on any failure.""" + + def identity(self) -> dict: + return {"type": self.type, "base_url": self.config.get("base_url")} + + def cost(self, usage: dict | None) -> float | None: + if not usage: + return None + for k in ("cost", "total_cost", "cost_usd"): + if isinstance(usage.get(k), (int, float)): + return float(usage[k]) + if self.pricing: + return (usage.get("prompt_tokens", 0) * self.pricing.get("input_per_mtok", 0) + + usage.get("completion_tokens", 0) * self.pricing.get("output_per_mtok", 0)) / 1e6 + return None + + async def aclose(self) -> None: + pass + + +UsageSink = Callable[[str, str, str, Usage, bool], None] # alias, provider, model, usage, cached + + +def estimate_tokens(payload: dict) -> int: + return len(json.dumps(payload.get("messages", []), ensure_ascii=False)) // 4 + 16 + + +class ModelClient: + """An alias bound to its provider, with request cache, pacing, retries, accounting. + + `cache_salt` separates otherwise-identical requests that must not share a cached + answer (e.g. the k rollouts of one task); it defaults to none, so identical label + prompts are answered once. + """ + + def __init__(self, alias_name: str, alias: "ModelAlias", provider: ModelProvider, *, store=None, + on_usage: UsageSink | None = None, budget: BudgetTracker | None = None, priority: int = 0, + cache_salt: str | None = None, read_cache: bool = True): + self.alias_name, self.alias, self.provider = alias_name, alias, provider + self.read_cache = read_cache + self.store, self.on_usage, self.budget = store, on_usage, budget + self.priority, self.cache_salt = priority, cache_salt + self.calls = 0 + self.errors: list[dict] = [] + + @property + def model(self) -> str: + return self.alias.model + + def build_payload(self, messages: list[dict], **params: Any) -> dict: + payload = {**self.alias.params, **{k: v for k, v in params.items() if v is not None}} + payload["model"] = self.alias.model + payload["messages"] = messages + payload.pop("stream", None) + payload.pop("stream_options", None) + return payload + + async def chat(self, messages: list[dict], *, tools: list[dict] | None = None, + response_format: dict | None = None, **params: Any) -> ChatResult: + payload = self.build_payload(messages, tools=tools, response_format=response_format, **params) + raw, cached = await self.complete_raw(payload) + return _to_result(raw, self.provider, cached) + + async def complete_raw(self, payload: dict) -> tuple[dict, bool]: + """Run a full payload (model already set). Returns (completion, cached).""" + payload = dict(payload) + payload["model"] = self.alias.model + payload.pop("stream", None) + payload.pop("stream_options", None) + key = digest({"provider": self.provider.identity(), "payload": payload, "salt": self.cache_salt}, 32) + if self.alias.cache and self.read_cache and self.store is not None: + hit = self.store.cache_get(key) + if hit is not None: + self._account(hit, cached=True) + return hit, True + limiter = self.provider.limiter + last: ProviderError | None = None + for attempt in range(self.alias.max_retries + 1): + if self.budget is not None: + self.budget.check() + lease = await limiter.acquire(estimate_tokens(payload), self.priority) + self.calls += 1 + try: + raw = await self.provider.complete(payload) + _validate_completion(raw) + except ProviderError as e: + last = e + self.errors.append({"status": e.status, "message": str(e)[:300]}) + if e.status == 429: + limiter.reject(e.retry_after) + continue + if not e.retryable: + raise + await asyncio.sleep(min(30.0, 1.5 * 1.7 ** attempt) * (0.5 + random.random()) * backoff_scale()) + continue + limiter.accepted() + usage = raw.get("usage") or {} + lease.settle(usage.get("completion_tokens")) + if self.alias.cache and self.store is not None: + self.store.cache_put(key, raw) + self._account(raw, cached=False) + return raw, False + assert last is not None + raise ProviderError(f"{self.alias_name}: giving up after {self.alias.max_retries + 1} attempts: {last}", + status=last.status) + + def _account(self, raw: dict, cached: bool) -> None: + u = raw.get("usage") or {} + usage = Usage(u.get("prompt_tokens", 0) or 0, u.get("completion_tokens", 0) or 0, + None if cached else self.provider.cost(u)) + if not cached and self.budget is not None: + self.budget.add(input_tokens=usage.input_tokens, output_tokens=usage.output_tokens, + usd=usage.cost_usd or 0.0) + if self.on_usage: + self.on_usage(self.alias_name, self.provider.name, self.alias.model, usage, cached) + + +def _validate_completion(raw: dict) -> None: + if not isinstance(raw, dict): + raise ProviderError("completion is not a JSON object", status=502) + if raw.get("error") and not raw.get("choices"): + raise ProviderError(f"error object in completion: {str(raw['error'])[:300]}", status=502) + choices = raw.get("choices") + if not choices or not isinstance(choices[0], dict) or choices[0].get("message") is None: + raise ProviderError("completion has no choices/message", status=502) + + +def _to_result(raw: dict, provider: ModelProvider, cached: bool) -> ChatResult: + choice = raw["choices"][0] + u = raw.get("usage") or {} + return ChatResult( + message=choice["message"], + usage=Usage(u.get("prompt_tokens", 0) or 0, u.get("completion_tokens", 0) or 0, + None if cached else provider.cost(u)), + finish_reason=choice.get("finish_reason"), + cached=cached, + raw=raw, + ) diff --git a/src/pipewright/models/fake.py b/src/pipewright/models/fake.py new file mode 100644 index 0000000..b40247b --- /dev/null +++ b/src/pipewright/models/fake.py @@ -0,0 +1,144 @@ +"""A deterministic fake provider for tests, previews and dry runs. + + providers: + fake: + type: fake + rules: # first match on the last user/tool message wins + - {match: "classify", content: '{"category": "bug"}'} + script: mypack.fakes:agent # optional fn(payload) -> message dict | completion dict + fail: {first: 2, status: 429} # inject failures (first N calls) + latency: 0.01 + +Without a matching rule: a `json_schema` response_format gets a deterministic object +that satisfies the schema; anything else gets a short echo. +""" + +from __future__ import annotations + +import asyncio +import importlib +import json +import re +from typing import Any + +from ..errors import ProviderError +from ..hashing import digest +from ..registry import register_provider +from .base import ModelProvider + + +def sample_from_schema(schema: dict, seed: str, defs: dict | None = None) -> Any: + """A deterministic value satisfying a (simple) JSON schema.""" + defs = defs or schema.get("$defs") or schema.get("definitions") or {} + if "$ref" in schema: + return sample_from_schema(defs.get(schema["$ref"].split("/")[-1], {}), seed, defs) + h = int(digest(seed, 8), 16) + if "enum" in schema: + return schema["enum"][h % len(schema["enum"])] + if "const" in schema: + return schema["const"] + for comb in ("anyOf", "oneOf"): + if comb in schema: + opts = [o for o in schema[comb] if o.get("type") != "null"] or schema[comb] + return sample_from_schema(opts[h % len(opts)], seed, defs) + t = schema.get("type") + if isinstance(t, list): + t = next((x for x in t if x != "null"), "string") + if t == "object" or "properties" in schema: + props = schema.get("properties", {}) + return {k: sample_from_schema(v, f"{seed}/{k}", defs) for k, v in props.items()} + if t == "array": + n = max(schema.get("minItems", 1), 1) + return [sample_from_schema(schema.get("items", {}), f"{seed}/{i}", defs) for i in range(n)] + if t == "integer": + lo, hi = schema.get("minimum", 0), schema.get("maximum", lo_default(schema)) + return lo + h % (hi - lo + 1) + if t == "number": + lo, hi = schema.get("minimum", 0.0), schema.get("maximum", 1.0) + return round(lo + (h % 1000) / 999 * (hi - lo), 3) + if t == "boolean": + return bool(h % 2) + return f"fake-{seed[-6:]}" if t in (None, "string") else None + + +def lo_default(schema: dict) -> int: + return schema.get("minimum", 0) + 9 + + +class FakeProvider(ModelProvider): + type = "fake" + + def __init__(self, name: str, config: dict, project=None): + super().__init__(name, config, project) + self.rules = [(re.compile(r.get("match", ""), re.I | re.S), r) for r in config.get("rules", [])] + self.script = None + if config.get("script"): + mod, _, fn = config["script"].partition(":") + self.script = getattr(importlib.import_module(mod), fn) + self.fail = config.get("fail") or {} + self.calls = 0 + self.requests: list[dict] = [] + + def identity(self) -> dict: + return {"type": "fake", "name": self.name, "rules": self.config.get("rules"), + "script": self.config.get("script")} + + async def complete(self, payload: dict) -> dict: + self.calls += 1 + self.requests.append(payload) + if self.config.get("latency"): + await asyncio.sleep(float(self.config["latency"])) + if self.calls <= int(self.fail.get("first", 0)): + raise ProviderError("injected failure", status=int(self.fail.get("status", 429)), + retry_after=self.fail.get("retry_after", 0.01)) + message = None + if self.script is not None: + out = self.script(payload) + if asyncio.iscoroutine(out): + out = await out + if isinstance(out, dict) and "choices" in out: + return out + message = out + if message is None: + message = self._rule_message(payload) + if isinstance(message, str): + message = {"role": "assistant", "content": message} + message.setdefault("role", "assistant") + prompt_tokens = len(json.dumps(payload.get("messages", []))) // 4 + completion_tokens = max(1, len(json.dumps(message)) // 4) + return { + "id": f"fake-{self.calls}", + "object": "chat.completion", + "model": payload.get("model"), + "choices": [{"index": 0, "message": message, + "finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}], + "usage": {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, + "total_tokens": prompt_tokens + completion_tokens}, + } + + def _rule_message(self, payload: dict) -> dict: + msgs = payload.get("messages") or [] + last = next((m for m in reversed(msgs) if m.get("role") in ("user", "tool")), {}) + text = last.get("content") if isinstance(last.get("content"), str) else json.dumps(last.get("content")) + all_text = "\n".join(m.get("content") for m in msgs if isinstance(m.get("content"), str)) + for rx, rule in self.rules: + if rx.search(text or "") or (rule.get("anywhere") and rx.search(all_text)): + msg: dict = {"role": "assistant", "content": rule.get("content", "")} + if rule.get("tool_calls"): + msg["tool_calls"] = [ + {"id": f"call_{i}", "type": "function", + "function": {"name": c["name"], "arguments": json.dumps(c.get("arguments", {}))}} + for i, c in enumerate(rule["tool_calls"]) + ] + return msg + rf = payload.get("response_format") or {} + seed = digest(msgs, 16) + if rf.get("type") == "json_schema": + schema = (rf.get("json_schema") or {}).get("schema") or {} + return {"role": "assistant", "content": json.dumps(sample_from_schema(schema, seed))} + if rf.get("type") == "json_object": + return {"role": "assistant", "content": "{}"} + return {"role": "assistant", "content": f"fake answer {seed[:8]}: {(text or '')[:60]}"} + + +register_provider("fake", FakeProvider) diff --git a/src/pipewright/models/openai_compat.py b/src/pipewright/models/openai_compat.py new file mode 100644 index 0000000..64e3b9f --- /dev/null +++ b/src/pipewright/models/openai_compat.py @@ -0,0 +1,209 @@ +"""OpenAI-compatible chat completions over httpx, with quirk adapters. + +Config (project `providers.`): + + type: openai + base_url: https://api.example.com/v1 + api_key: {env: EXAMPLE_KEY} # or {file: ~/.secrets, var: EXAMPLE_KEY}; optional + stream: false # stream internally (needed for some providers) + timeout: 600 + headers: {X-Title: pipewright} + rate: {requests_per_minute: 1000, input_tokens_per_minute: 2000000, output_tokens_per_minute: 76000} + pricing: {input_per_mtok: 0.27, output_per_mtok: 1.1} # if the provider reports no cost + quirks: [stream_error_event, body_error] # default: both + +Quirk adapters turn provider misbehaviour into honest ProviderErrors: + +- stream_error_event: an HTTP 200 stream whose first data event is `{"error": ...}` + (after optional `: heartbeat` comments) becomes a 429/5xx — otherwise clients see an + empty completion and status-based retries never fire. +- body_error: an HTTP 200 JSON body with `error` and no `choices` becomes a 429/5xx. + +Add more with `register_quirk(name, fn)`; fn(event_or_body: dict) -> ProviderError | None. +""" + +from __future__ import annotations + +import json +from typing import Callable + +import httpx + +from ..errors import ProviderError +from ..registry import register_provider +from .base import ModelProvider + +RATE_CODES = {"capacity_saturated", "rate_limited", "rate_limit_exceeded", "too_many_requests", "overloaded"} + + +def error_from_event(event: dict) -> ProviderError | None: + """An in-band error object (stream event or body) -> ProviderError with a real status.""" + if not isinstance(event, dict): + return None + error = event.get("error") + if not error or event.get("choices"): + return None + code = error.get("code") if isinstance(error, dict) else None + etype = error.get("type") if isinstance(error, dict) else None + status = None + if isinstance(code, int) and 400 <= code < 600: + status = code + elif isinstance(code, str) and code.isdigit() and 400 <= int(code) < 600: + status = int(code) + elif code in RATE_CODES or etype in RATE_CODES: + status = 429 + else: + status = 502 + msg = error.get("message") if isinstance(error, dict) else str(error) + return ProviderError(f"in-band error: {msg or error}"[:500], status=status) + + +QUIRKS: dict[str, Callable[[dict], ProviderError | None]] = { + "stream_error_event": error_from_event, + "body_error": error_from_event, +} + + +def register_quirk(name: str, fn: Callable[[dict], ProviderError | None]) -> None: + QUIRKS[name] = fn + + +def retry_after(resp: httpx.Response) -> float | None: + for h in ("retry-after", "x-ratelimit-reset-after"): + v = resp.headers.get(h) + if v: + try: + return max(0.0, float(v)) + except ValueError: + return None + return None + + +def assemble_stream(events: list[dict]) -> dict: + """Reassemble streamed chat.completion.chunk events into one chat.completion.""" + content, reasoning, calls = [], [], {} + usage, finish, model, rid = None, None, None, None + for ev in events: + usage = ev.get("usage") or usage + model = ev.get("model") or model + rid = ev.get("id") or rid + for ch in ev.get("choices") or []: + delta = ch.get("delta") or {} + finish = ch.get("finish_reason") or finish + content.append(delta.get("content") or "") + reasoning.append(delta.get("reasoning_content") or delta.get("reasoning") or "") + for call in delta.get("tool_calls") or []: + slot = calls.setdefault(call.get("index", 0), + {"id": None, "type": "function", "function": {"name": "", "arguments": ""}}) + slot["id"] = call.get("id") or slot["id"] + fn = call.get("function") or {} + slot["function"]["name"] += fn.get("name") or "" + slot["function"]["arguments"] += fn.get("arguments") or "" + message: dict = {"role": "assistant", "content": "".join(content)} + if any(reasoning): + message["reasoning_content"] = "".join(reasoning) + if calls: + message["tool_calls"] = [calls[i] for i in sorted(calls)] + return {"id": rid, "object": "chat.completion", "model": model, + "choices": [{"index": 0, "message": message, "finish_reason": finish}], "usage": usage} + + +class OpenAICompatProvider(ModelProvider): + type = "openai" + + def __init__(self, name: str, config: dict, project=None): + super().__init__(name, config, project) + if not config.get("base_url"): + from ..errors import ConfigError + + raise ConfigError(f"provider {name}: base_url is required") + self.base_url = config["base_url"].rstrip("/") + self.stream = bool(config.get("stream", False)) + self.quirks = [QUIRKS[q] for q in config.get("quirks", ["stream_error_event", "body_error"]) if q in QUIRKS] + self._client: httpx.AsyncClient | None = None + self._transport = config.get("_transport") # tests inject httpx.MockTransport + + def _headers(self) -> dict: + from ..project import SecretRef + + headers = {"Content-Type": "application/json", **(self.config.get("headers") or {})} + key = self.config.get("api_key") + if isinstance(key, dict): + headers["Authorization"] = f"Bearer {SecretRef.model_validate(key).resolve()}" + elif isinstance(key, str) and key: + raise ProviderError("api_key must be a secret reference ({env: VAR} or {file: path}), " + "not a literal", status=400) + return headers + + @property + def client(self) -> httpx.AsyncClient: + if self._client is None: + self._client = httpx.AsyncClient( + timeout=httpx.Timeout(self.config.get("timeout", 600), connect=30), + limits=httpx.Limits(max_connections=None, max_keepalive_connections=64), + transport=self._transport, + ) + return self._client + + async def complete(self, payload: dict) -> dict: + url = f"{self.base_url}/chat/completions" + try: + if self.stream: + return await self._complete_stream(url, payload) + resp = await self.client.post(url, json=payload, headers=self._headers()) + except httpx.TimeoutException as e: + raise ProviderError(f"timeout: {type(e).__name__}", status=504) from None + except httpx.TransportError as e: + raise ProviderError(f"transport: {type(e).__name__}: {e}", status=502) from None + if resp.status_code != 200: + raise ProviderError(f"HTTP {resp.status_code}: {resp.text[:300]}", status=resp.status_code, + retry_after=retry_after(resp)) + try: + body = resp.json() + except ValueError: + raise ProviderError(f"non-JSON body: {resp.text[:200]}", status=502) from None + for q in self.quirks: + err = q(body) + if err is not None: + raise err + return body + + async def _complete_stream(self, url: str, payload: dict) -> dict: + body = {**payload, "stream": True, "stream_options": {"include_usage": True}} + events: list[dict] = [] + async with self.client.stream("POST", url, json=body, headers=self._headers()) as resp: + if resp.status_code != 200: + text = (await resp.aread()).decode(errors="replace") + raise ProviderError(f"HTTP {resp.status_code}: {text[:300]}", status=resp.status_code, + retry_after=retry_after(resp)) + async for line in resp.aiter_lines(): + if not line or line.startswith(":"): # heartbeat comments + continue + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + try: + ev = json.loads(data) + except ValueError: + continue + if not events: # the first event decides whether this is an in-band error + for q in self.quirks: + err = q(ev) + if err is not None: + raise err + elif isinstance(ev, dict) and ev.get("error") and not ev.get("choices"): + raise error_from_event(ev) or ProviderError("stream error", status=502) + events.append(ev) + if not events: + raise ProviderError("empty stream", status=502) + return assemble_stream(events) + + async def aclose(self) -> None: + if self._client is not None: + await self._client.aclose() + self._client = None + + +register_provider("openai", OpenAICompatProvider) diff --git a/src/pipewright/models/proxy.py b/src/pipewright/models/proxy.py new file mode 100644 index 0000000..35f5a96 --- /dev/null +++ b/src/pipewright/models/proxy.py @@ -0,0 +1,239 @@ +"""Logging/pacing proxy for external agents. + +External agent CLIs speak OpenAI-compatible HTTP. Instead of handing them the real +provider URL and key, a harness opens a proxy SESSION: the agent gets +`OPENAI_BASE_URL=http://:/v1` and `OPENAI_API_KEY=`. Every +request then goes through the same ModelClient as built-in nodes — the provider's +rate limiter, quirk adapters, retries, request cache and usage accounting — and every +turn is recorded on the session (so the trajectory of a third-party agent is +captured), and the real key never enters the sandbox. + +Streaming requests are answered with a synthesized SSE stream from the complete +response (latency per token does not matter for batch pipelines). + +After the agent exits, `session.failed_last_call` tells the harness whether the +agent "finished" only because its last model call failed — which is a provider +failure to retry, not a result. + +A small asyncio HTTP/1.1 server; no web framework dependency. +""" + +from __future__ import annotations + +import asyncio +import json +import secrets +import time +from dataclasses import dataclass, field +from pathlib import Path + +from ..errors import ProviderError +from .base import ModelClient + + +def normalized(message: dict) -> str: + role = message.get("role") + calls = [c.get("id") for c in message.get("tool_calls") or []] + if role == "assistant" and calls: + return json.dumps([role, calls]) + if role == "tool": + return json.dumps([role, message.get("tool_call_id")]) + content = message.get("content") + if isinstance(content, list): + content = " ".join(p.get("text", "") for p in content if isinstance(p, dict)) + return json.dumps([role, " ".join(str(content or "").split())]) + + +@dataclass +class ProxySession: + token: str + client: ModelClient + turns: list[dict] = field(default_factory=list) + conversations: dict[str, list[str]] = field(default_factory=dict) + last_status: int | None = None + last_error: dict | None = None + log_dir: Path | None = None + """If set, every turn is also appended to /.jsonl as it finishes.""" + + def record(self, turn: dict) -> None: + self.turns.append(turn) + if self.log_dir is not None: + self.log_dir.mkdir(parents=True, exist_ok=True) + with open(self.log_dir / f"{turn['conversation']}.jsonl", "a") as f: + f.write(json.dumps(turn, ensure_ascii=False) + "\n") + + def place(self, messages: list[dict]) -> tuple[str, int]: + """Which conversation a request continues (prefix match) and how many of its + messages were already logged; a non-continuation (e.g. compaction) starts a new one.""" + norm = [normalized(m) for m in messages] + best, best_len = None, -1 + for cid, seen in self.conversations.items(): + if len(seen) <= len(norm) and norm[: len(seen)] == seen and len(seen) > best_len: + best, best_len = cid, len(seen) + if best is None: + best, best_len = f"c{len(self.conversations)}", 0 + self.conversations[best] = norm + return best, best_len + + @property + def failed_last_call(self) -> bool: + return self.last_status is not None and self.last_status != 200 + + def messages(self) -> list[dict]: + """The longest conversation's messages, reconstructed from the turns.""" + out: dict[str, list[dict]] = {} + for t in self.turns: + conv = out.setdefault(t["conversation"], []) + conv.extend(t.get("new_messages") or []) + if t.get("response"): + conv.append(t["response"]) + return max(out.values(), key=len) if out else [] + + +class LoggingProxy: + def __init__(self) -> None: + self.sessions: dict[str, ProxySession] = {} + self.servers: dict[str, tuple[asyncio.AbstractServer, int]] = {} + self._lock = asyncio.Lock() + + async def listen(self, bind: str = "127.0.0.1", port: int = 0) -> int: + """Ensure a listener on `bind`; returns its port.""" + async with self._lock: + if bind not in self.servers: + server = await asyncio.start_server(self._handle, bind, port) + port = server.sockets[0].getsockname()[1] + self.servers[bind] = (server, port) + return self.servers[bind][1] + + def open_session(self, client: ModelClient, log_dir: Path | None = None) -> ProxySession: + token = "pws-" + secrets.token_urlsafe(24) + s = ProxySession(token, client, log_dir=log_dir) + self.sessions[token] = s + return s + + def close_session(self, token: str) -> None: + self.sessions.pop(token, None) + + async def aclose(self) -> None: + for server, _ in self.servers.values(): + server.close() + await server.wait_closed() + self.servers.clear() + + # ------------------------------------------------------------------ http + async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + while True: + line = await reader.readline() + if not line: + break + try: + method, path, _ = line.decode("latin-1").split(" ", 2) + except ValueError: + break + headers: dict[str, str] = {} + while True: + h = await reader.readline() + if h in (b"\r\n", b"\n", b""): + break + k, _, v = h.decode("latin-1").partition(":") + headers[k.strip().lower()] = v.strip() + body = b"" + if "content-length" in headers: + body = await reader.readexactly(int(headers["content-length"])) + elif headers.get("transfer-encoding", "").lower() == "chunked": + body = await _read_chunked(reader) + status, ctype, data = await self._route(method, path, headers, body) + keep = headers.get("connection", "").lower() != "close" + head = (f"HTTP/1.1 {status} {_REASONS.get(status, 'OK')}\r\nContent-Type: {ctype}\r\n" + f"Content-Length: {len(data)}\r\nConnection: {'keep-alive' if keep else 'close'}\r\n\r\n") + writer.write(head.encode() + data) + await writer.drain() + if not keep: + break + except (asyncio.IncompleteReadError, ConnectionError): + pass + finally: + try: + writer.close() + except Exception: # pragma: no cover + pass + + async def _route(self, method: str, path: str, headers: dict, body: bytes) -> tuple[int, str, bytes]: + auth = headers.get("authorization", "") + token = auth.split(" ", 1)[1].strip() if auth.lower().startswith("bearer ") else headers.get("x-api-key", "") + session = self.sessions.get(token) + if session is None: + return _json(401, {"error": {"message": "unknown proxy session", "code": 401}}) + path = path.split("?", 1)[0].rstrip("/") + if method == "GET" and path.endswith("/models"): + return _json(200, {"object": "list", "data": [{"id": session.client.model, "object": "model"}]}) + if method == "POST" and path.endswith("/chat/completions"): + try: + payload = json.loads(body or b"{}") + except ValueError: + return _json(400, {"error": {"message": "invalid JSON", "code": 400}}) + return await self._chat(session, payload) + return _json(404, {"error": {"message": f"not proxied: {method} {path}", "code": 404}}) + + async def _chat(self, session: ProxySession, payload: dict) -> tuple[int, str, bytes]: + stream = bool(payload.get("stream")) + cid, start = session.place(payload.get("messages") or []) + started = time.time() + turn = {"turn": len(session.turns) + 1, "conversation": cid, "time": started, + "new_messages": (payload.get("messages") or [])[start:]} + try: + raw, cached = await session.client.complete_raw(payload) + except ProviderError as e: + status = e.status or 502 + session.last_status, session.last_error = status, {"status": status, "message": str(e)[:500]} + turn.update(status=status, error=str(e)[:500], seconds=round(time.time() - started, 2)) + session.record(turn) + return _json(status, {"error": {"message": str(e)[:500], "code": status}}) + message = raw["choices"][0]["message"] + session.conversations[cid] = session.conversations[cid] + [normalized(message)] + session.last_status, session.last_error = 200, None + turn.update(status=200, response=message, usage=raw.get("usage"), cached=cached, + seconds=round(time.time() - started, 2)) + session.record(turn) + if not stream: + return _json(200, raw) + return 200, "text/event-stream", _as_sse(raw) + + +def _as_sse(raw: dict) -> bytes: + choice = raw["choices"][0] + msg = dict(choice["message"]) + delta: dict = {"role": "assistant", "content": msg.get("content") or ""} + if msg.get("tool_calls"): + delta["tool_calls"] = [{**c, "index": i} for i, c in enumerate(msg["tool_calls"])] + if msg.get("reasoning_content"): + delta["reasoning_content"] = msg["reasoning_content"] + base = {"id": raw.get("id") or "pw", "object": "chat.completion.chunk", "created": int(time.time()), + "model": raw.get("model")} + events = [ + {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": choice.get("finish_reason") or "stop"}]}, + ] + if raw.get("usage"): + events.append({**base, "choices": [], "usage": raw["usage"]}) + return b"".join(f"data: {json.dumps(e)}\n\n".encode() for e in events) + b"data: [DONE]\n\n" + + +def _json(status: int, obj: dict) -> tuple[int, str, bytes]: + return status, "application/json", json.dumps(obj).encode() + + +async def _read_chunked(reader: asyncio.StreamReader) -> bytes: + out = b"" + while True: + size = int((await reader.readline()).strip().split(b";")[0], 16) + if size == 0: + await reader.readline() + return out + out += await reader.readexactly(size) + await reader.readline() + + +_REASONS = {200: "OK", 400: "Bad Request", 401: "Unauthorized", 404: "Not Found", 429: "Too Many Requests", + 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout"} diff --git a/src/pipewright/nodes/__init__.py b/src/pipewright/nodes/__init__.py new file mode 100644 index 0000000..1acb58b --- /dev/null +++ b/src/pipewright/nodes/__init__.py @@ -0,0 +1 @@ +"""Node types. `base` defines the interface; `builtin` and `agentic` ship generic types.""" diff --git a/src/pipewright/nodes/agentic.py b/src/pipewright/nodes/agentic.py new file mode 100644 index 0000000..17b989d --- /dev/null +++ b/src/pipewright/nodes/agentic.py @@ -0,0 +1,212 @@ +"""Generic node types for sandboxed execution and agents.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from ..errors import ConfigError, NodeError +from ..expr import eval_item, render_item, template_exprs +from ..harness.base import AgentTask +from ..registry import register_node +from .base import SAME, NodeType, Port, ResourceRef +from .builtin import _check_exprs + + +class P(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class CheckSpec(P): + name: str + command: str = Field(description="template; runs in the sandbox workdir") + files: dict[str, str] = Field(default_factory=dict, description="path -> template, written before the command") + files_expr: str | None = Field(None, description="expression giving extra {path: content} for this check") + expect: Literal["pass", "fail"] = Field("pass", description="pass = exit 0 expected; fail = non-zero expected") + timeout: float = Field(300, gt=0) + + +class SandboxCheckParams(P): + pool: str = Field(description="sandbox pool from the project file") + files: dict[str, str] = Field(default_factory=dict, description="path -> template, written for every check") + files_expr: str | None = Field(None, description="expression giving {path: content} for every check, " + "e.g. payload.files") + checks: list[CheckSpec] = Field(min_length=1, description="each runs in a FRESH sandbox") + label: str = Field("valid", description="label set to true when every check met its expectation") + output_chars: int = Field(2000, description="tail of output kept per check") + + +async def write_files(sb, item, files: dict[str, str], files_expr: str | None) -> None: + for path, tmpl in files.items(): + await sb.write(render_item(path, item), render_item(tmpl, item)) + if files_expr: + extra = eval_item(files_expr, item) or {} + if not isinstance(extra, dict): + raise NodeError(f"files_expr {files_expr!r} must give a dict, got {type(extra).__name__}") + for path, content in extra.items(): + await sb.write(str(path), content if isinstance(content, str) else json.dumps(content)) + + +@register_node +class SandboxCheck(NodeType): + """Run commands in fresh sandboxes and label whether each met its expectation — + e.g. "the reference solution passes the tests" (expect pass) and "the untouched task + fails them" (expect fail). Labels: `