pipewright: graph-based data/task pipeline framework
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pipewright*/
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
.pytest_cache/
|
||||
examples/*/out/
|
||||
*.pwindex
|
||||
@@ -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 <type>` document every type: ports and their
|
||||
item kinds, the params JSON schema, the project resources it needs, cost hints and a
|
||||
working example.
|
||||
|
||||
**Project** — `pipewright.yaml` next to (or above) the graph binds the *names* a graph
|
||||
uses to concrete resources: model aliases → providers, sandbox pools, harnesses,
|
||||
budgets. Swap the project file (`--project`) to run the same graph on a fake model in
|
||||
tests and a real one in production.
|
||||
|
||||
**Memoization** — a node's result for an input item is stored under
|
||||
(node type + version + params + resolved resource identity, input item id). Re-running
|
||||
replays stored results and computes only what is new or changed; editing one node's
|
||||
params recomputes that node, and downstream nodes only for items whose content actually
|
||||
changed. LLM calls also go through a request cache keyed by payload hash. Transient
|
||||
failures (provider, infra) are not memoized; deterministic node errors are (rerun them
|
||||
with `--retry-errors`).
|
||||
|
||||
**Scheduling** — every item is processed as soon as it arrives (pipelined), limited
|
||||
only by resource leases: provider request/token budgets per minute (rejected requests
|
||||
count against the window; a 429 closes a shared gate for Retry-After), sandbox slots
|
||||
derived from capacity, and USD / token / VM-hour budgets per run. There are no worker
|
||||
counts to tune. Deeper nodes get priority so items finish instead of every stage being
|
||||
half done.
|
||||
|
||||
**Errors** — every failure is classified: `provider` (429/5xx/transport, in-stream
|
||||
errors, an agent whose last model call failed) and `infra` (sandbox/harness) are
|
||||
retried and never recorded as results; `node` errors are deterministic results.
|
||||
|
||||
**Building on results** — any node's outputs can seed new work:
|
||||
|
||||
- `store.query` selects stored items by graph, node, port, run (`latest`, `all`,
|
||||
`group:<g>`, a run id), kind, provenance, labels, an expression and lineage
|
||||
(`derived_from`), from this store or another project's (copied with lineage and blobs).
|
||||
- Cross-graph edges: a graph declares `imports` and uses `alias:node.port` as an input.
|
||||
Each run reads that port's items from the upstream graph's latest run; since item ids
|
||||
are kept, items handled before stay memoized and only new upstream items cost work.
|
||||
- Re-entrant loops across runs: `imports: {prev: {graph: self}}` reads this graph's
|
||||
previous run (e.g. audited failures of run N become generator seeds in run N+1) —
|
||||
no live cycle, every step memoized.
|
||||
- Lineage spans graphs that share a store: `pw lineage ITEM --roots` (the root source
|
||||
of a variant), `--descendants` (every variant derived from an item), each entry with
|
||||
the graph and run that made it. `pw query` shows what a `store.query` would select.
|
||||
|
||||
```python
|
||||
g = Graph("harden")
|
||||
build = g.import_graph("build", "graph_build.py") # another graph, by reference
|
||||
task = g.add("task", "map.expr", input=build.node("bucket").port("too_easy"), kind="task", fields={...})
|
||||
```
|
||||
|
||||
**Host pools** — `hosts:` in the project file defines pools of machines (a host
|
||||
provider: `boat` VMs, `static` SSH hosts, or a plugin) with capacity (cpus, memory,
|
||||
disk), capabilities (kvm, gpu), labels, a setup hook, `min`/`max`, `idle_shutdown`,
|
||||
TTL extension and an hours/$ budget. A Docker sandbox pool with `hosts: <pool>` runs
|
||||
each sandbox as a container on a pool host (`docker -H ssh://…` from this machine, so
|
||||
nothing is synced to hosts). Placement reserves the sandbox's `cpus`/`memory` on a host
|
||||
that has the required capabilities and labels, preferring hosts that already have the
|
||||
image or warm volume, then the tightest fit; when nothing fits the pool creates hosts
|
||||
(within `max` and budget), and idle hosts are deleted. Capacity is resources, not slots:
|
||||
two 8 GB tasks never share a 16 GB host. Images are ensured per host (`image_source:
|
||||
{build: dir | load: tar | pull: ref}`) and recorded as `image:<ref>` labels.
|
||||
|
||||
```yaml
|
||||
hosts:
|
||||
boat:
|
||||
type: boat # pipewright.contrib.boat (optional extra)
|
||||
api_key: {file: ~/.config/deepswe-eval/secrets, var: BOAT_API_KEY}
|
||||
max: 4
|
||||
idle_shutdown: 300
|
||||
reserve: {cpus: 0.5, memory: 1g}
|
||||
docker_kvm_runtime: true # every container gets /dev/kvm (mode 0666)
|
||||
budget: {hours: 4}
|
||||
sandboxes:
|
||||
vmtest: {type: docker, hosts: boat, image: nix-base:dev, image_source: {build: ./image},
|
||||
cpus: 4, memory: 7g, requires: {kvm: true}}
|
||||
```
|
||||
|
||||
**Scaling out** — `pw run --shard I/N --group G` processes only the source items whose
|
||||
key hashes to I (mod N); several processes or machines share one store (writes are
|
||||
buffered and committed in short batches, so the SQLite write lock is held for
|
||||
milliseconds). Sinks are skipped in shard runs; a final `pw run` without `--shard`
|
||||
replays everything from memo and writes them. `pw funnel --group G` sums the shards.
|
||||
Provider rate limits can be shared by every process on a machine (`rate: {shared:
|
||||
true}`), so concurrent runs pace jointly against one key's budget.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```python
|
||||
# graph.py
|
||||
from pipewright import Graph
|
||||
|
||||
g = Graph("triage")
|
||||
issues = g.add("issues", "source.file", path="data/issues.jsonl", kind="issue")
|
||||
heur = g.add("heur", "label.expr", input=issues,
|
||||
labels={"has_traceback": "re(r'traceback', payload.body)", "words": "words(payload.body)"})
|
||||
keep = g.add("keep", "filter.expr", input=heur, expr="labels.words >= 8")
|
||||
cls = g.add("classify", "llm.label", input=keep, model="labeler",
|
||||
prompt="Classify:\n\n{{ payload.title }}\n\n{{ payload.body }}",
|
||||
labels={"category": {"type": "string", "enum": ["bug", "feature", "question"]},
|
||||
"severity": {"type": "integer", "minimum": 0, "maximum": 3}})
|
||||
route = g.add("route", "route.expr", input=cls, routes={"urgent": "labels.severity >= 2"}, default="rest")
|
||||
g.add("export", "sink.jsonl", input=route.port("urgent"), path="out/urgent.jsonl")
|
||||
graph = g
|
||||
```
|
||||
|
||||
```yaml
|
||||
# pipewright.yaml
|
||||
providers:
|
||||
fake: {type: fake} # deterministic, schema-conforming answers
|
||||
morph:
|
||||
type: openai
|
||||
base_url: https://api.morphllm.com/v1
|
||||
api_key: {env: MORPH_SK, file: ~/.tmp, var: MORPH_SK}
|
||||
rate: {requests_per_minute: 200, input_tokens_per_minute: 500000, output_tokens_per_minute: 20000}
|
||||
models:
|
||||
labeler: {provider: fake, model: fake} # switch to {provider: morph, model: morph-dsv41flash-1017}
|
||||
budgets: {usd: 5, counters: {rollouts.solver: 60}} # counters: spent by nodes via ctx.count(name)
|
||||
```
|
||||
|
||||
```
|
||||
pw check graph.py && pw preview graph.py --upto classify -n 3 && pw run graph.py && pw funnel graph.py
|
||||
```
|
||||
|
||||
Typed authoring: instead of a type string you can pass the node's Params model,
|
||||
which gives IDE completion and immediate validation:
|
||||
`g.add("keep", FilterExpr.Params(expr="labels.words >= 8"), input=heur)`.
|
||||
|
||||
Expressions (`label.expr`, `filter.expr`, `route.expr`, `map.expr`, `join.group`) and
|
||||
`{{ templates }}` use a safe, whitelisted Python subset over `payload`, `labels`, `key`,
|
||||
`kind`, with helpers such as `re`, `re_count`, `re_find`, `words`, `mean`, `json`.
|
||||
Missing keys read as `None`.
|
||||
|
||||
## Examples (run end to end; also the integration tests)
|
||||
|
||||
- `examples/issue_triage` — read GitHub-style issues → heuristic labels → filter →
|
||||
structured LLM labels → route → export. `pipewright.yaml` uses the fake model;
|
||||
`pipewright.live.yaml` uses DeepSeek via Morph.
|
||||
- `examples/hardening` — two graphs on one store. `graph_build.py` synthesizes coding
|
||||
tasks, validates them in sandboxes, probes them with an agent (k=2) and buckets them
|
||||
by pass rate; `graph_harden.py` imports build's `bucket.too_easy`, asks an LLM for a
|
||||
harder variant of each, and validates + probes the variants again. Re-running harden
|
||||
after build found more too-easy tasks processes only the new ones.
|
||||
`pipewright.boat.yaml` runs the same graphs with sandboxes on boat.dev VMs
|
||||
(`live_boat.py` is the live end-to-end: 2 VMs, /dev/kvm in containers, idle
|
||||
scale-down, cleanup).
|
||||
- `examples/coding_tasks` — synthesize small coding tasks with an LLM → validate each
|
||||
in sandboxes (reference solution passes, empty stub fails) → probe with the built-in
|
||||
agent at k=2 → group rollouts → route by pass rate (too_easy / learnable / too_hard).
|
||||
`pipewright.yaml`: fake model + local sandbox; `pipewright.docker.yaml`: Docker with
|
||||
no network; `pipewright.live.yaml`: Morph + Docker.
|
||||
|
||||
## CLI
|
||||
|
||||
All commands accept `--json` and `--project FILE`.
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `pw nodes list` / `pw nodes describe TYPE` | node docs: ports, params schema, resources, cost hints, example |
|
||||
| `pw check GRAPH` | errors/warnings with codes and hints; budget estimate; exit 1 on errors |
|
||||
| `pw patch GRAPH OPS` | apply JSON ops (`add_node`, `remove_node`, `rename_node`, `connect`, `disconnect`, `set_param`, `set_node`); written only if the result checks clean. `--dry-run`, `--force`, `--schema` |
|
||||
| `pw preview GRAPH --upto NODE -n 5` | run the first n source items up to a node, show its output |
|
||||
| `pw run GRAPH [--upto N] [--limit N] [--force NODE] [--retry-errors]` | run/resume |
|
||||
| `pw status GRAPH` | latest run: per-node in/ok/cached/errors/running/pending/parked, usage, budget |
|
||||
| `pw funnel GRAPH` | counts per node, port and edge |
|
||||
| `pw items GRAPH NODE [--port P] [-n 5] [--sample] [--errors] [--full]` | inspect items / failures |
|
||||
| `pw run GRAPH --shard I/N --group G` | one worker's share of the source items (several workers, one store) |
|
||||
| `pw funnel GRAPH --group G` | funnel summed over a run group (e.g. all shards) |
|
||||
| `pw lineage GRAPH ITEM [--roots] [--descendants]` | an item (id, prefix or key) and its ancestors across graphs; root sources; all variants derived from it |
|
||||
| `pw query GRAPH [--of NAME] [--node N --port P] [--run latest\|all\|ID] [--where EXPR] [--label k=v] [--derived-from ITEM]` | select stored results; prints the equivalent `store.query` node |
|
||||
| `pw hosts list\|up\|down\|orphans [--pool P] [--count N]` | host pools outside a run: list, pre-create (kept for later runs with `persist: true`), delete, clean up unrecorded provider hosts |
|
||||
| `pw export GRAPH NODE -o out.jsonl [--fields a,b]` | export a node's output |
|
||||
| `pw report GRAPH [--watch S]` | static HTML report with per-edge counts and drill-down samples |
|
||||
| `pw review GRAPH NODE [--approve ID… \| --reject ID…]` | human review queue |
|
||||
| `pw convert GRAPH.py GRAPH.yaml` | builder → file (and between JSON/YAML) |
|
||||
| `pw proxy --model ALIAS --log-dir DIR` | standalone logging proxy for running an agent by hand |
|
||||
| `pw mcp` | the same operations as MCP tools (stdio) |
|
||||
|
||||
## Writing plugins
|
||||
|
||||
All five registries work the same way: register in-process (decorator/function), or
|
||||
ship a distribution with an entry point in the matching group (`pipewright.nodes`,
|
||||
`pipewright.providers`, `pipewright.harnesses`, `pipewright.sandboxes`,
|
||||
`pipewright.hosts`), or list local modules under `plugins:` in the project or graph file.
|
||||
|
||||
```toml
|
||||
[project.entry-points."pipewright.nodes"]
|
||||
mypack = "mypack.nodes" # importing the module registers its node types
|
||||
```
|
||||
|
||||
### Node types
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from pipewright import NodeType, Port, ResourceRef, register_node
|
||||
|
||||
class DedupParams(BaseModel):
|
||||
field: str = "title"
|
||||
|
||||
@register_node
|
||||
class NearDup(NodeType):
|
||||
"""Label items whose `field` was seen in an earlier run (cross-run feedback)."""
|
||||
name = "mypack.near_dup"
|
||||
kind = "map"
|
||||
version = "1" # bump when behaviour changes -> memo invalidated
|
||||
Params = DedupParams
|
||||
inputs = {"in": Port(kind="issue")}
|
||||
outputs = {"out": Port(kind="same")}
|
||||
example = {"field": "title"}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
seen = {i.payload.get(self.params.field) for i in ctx.prior_items("triage", "classify")}
|
||||
return item.derive(update_labels={"seen_before": item.payload.get(self.params.field) in seen})
|
||||
```
|
||||
|
||||
`ctx` gives `ctx.model(alias)` (paced, cached, accounted chat client),
|
||||
`async with ctx.sandbox(pool) as sb`, `ctx.harness(name)`, `ctx.put_blob(...)`,
|
||||
`ctx.prior_items(graph, node, port)`, `ctx.log(...)`. Declare `resources()` so
|
||||
`pw check` verifies aliases/pools exist and memo keys include what they resolve to;
|
||||
`cost_hint()` feeds budget estimates; `validate_params()` adds semantic checks.
|
||||
|
||||
### Model providers
|
||||
|
||||
The built-in `openai` type covers OpenAI-compatible APIs. A provider only implements
|
||||
`complete(payload) -> chat.completion dict` and raises `ProviderError(status=...)`;
|
||||
retries, pacing, caching and accounting are layered on top.
|
||||
|
||||
```python
|
||||
from pipewright import register_provider, ProviderError
|
||||
from pipewright.models.base import ModelProvider
|
||||
|
||||
class MyAPI(ModelProvider):
|
||||
type = "myapi"
|
||||
async def complete(self, payload):
|
||||
resp = await my_call(payload) # translate to/from your API
|
||||
if resp.overloaded:
|
||||
raise ProviderError("overloaded", status=429, retry_after=resp.retry_after)
|
||||
return {"choices": [{"index": 0, "message": {"role": "assistant", "content": resp.text}}],
|
||||
"usage": {"prompt_tokens": resp.n_in, "completion_tokens": resp.n_out, "cost": resp.usd}}
|
||||
|
||||
register_provider("myapi", MyAPI)
|
||||
```
|
||||
|
||||
Quirk adapters for misbehaving OpenAI-compatible providers are small functions
|
||||
(`pipewright.models.openai_compat.register_quirk`); `stream_error_event` (HTTP 200
|
||||
stream whose first data event is an error, after heartbeat comments → real 429/5xx) and
|
||||
`body_error` are on by default. Secrets are references (`{env: VAR}` or
|
||||
`{file: path, var: KEY}`), resolved at call time, never stored or logged; a literal key
|
||||
in the config is rejected.
|
||||
|
||||
### Agent harnesses
|
||||
|
||||
```python
|
||||
from pipewright import register_harness
|
||||
from pipewright.harness.base import Harness, Trajectory
|
||||
|
||||
class MyAgent(Harness):
|
||||
type = "myagent"
|
||||
async def run(self, task, sandbox, ctx):
|
||||
client = ctx.model(self.config["model"]) # or: proxy = await ctx.proxy() for CLI agents
|
||||
...
|
||||
return Trajectory(harness=self.name, status="completed", messages=msgs, turns=n)
|
||||
|
||||
register_harness("myagent", MyAgent)
|
||||
```
|
||||
|
||||
Contract: return a Trajectory for anything that is a *result* (completed, gave up, ran
|
||||
out of turns/time); raise `ProviderError` when the agent stopped because a model call
|
||||
failed, `InfraError` when the sandbox/harness broke. Shipped: `builtin` (minimal
|
||||
bash/read/write/finish tool-calling agent), `cli` (runs an external agent CLI in the
|
||||
sandbox, routed through the logging proxy so every turn is recorded, and raising
|
||||
ProviderError if its last model call failed), `verifiers` (experimental adapter for
|
||||
prime-intellect verifiers v1 harnesses).
|
||||
|
||||
### Sandbox / host providers
|
||||
|
||||
```python
|
||||
from pipewright import register_sandbox
|
||||
from pipewright.sandbox.base import Sandbox, SandboxProvider, ExecResult, Capabilities
|
||||
|
||||
class MyVMs(SandboxProvider):
|
||||
type = "myvms"
|
||||
capabilities = Capabilities(kvm=True, remote=True)
|
||||
async def create(self) -> Sandbox: ... # boot a VM, return a Sandbox with exec/read/write
|
||||
async def destroy(self, sandbox): ...
|
||||
async def extend(self, sandbox, seconds): ... # optional (TTL-based VMs)
|
||||
|
||||
register_sandbox("myvms", MyVMs)
|
||||
```
|
||||
|
||||
The base class provides the pooled lifecycle for every provider: slots, create, the
|
||||
pool's `setup` commands, health checks, optional reuse of healthy sandboxes
|
||||
(`reuse: true`), destroy on release, `drain()` at the end of a run, and VM-hour / $
|
||||
accounting (`cost_per_hour`). Shipped: `local` (temp dir on the host, no isolation),
|
||||
`docker` (fresh container per lease; `network: none | bridge | allowlist`, where
|
||||
`allowlist` uses an internal Docker network plus an allowlisting CONNECT proxy),
|
||||
`ssh_docker` (the same against a remote Docker daemon, `host: ssh://user@host`), and
|
||||
`fake` (in-memory, for tests). Docker pools with `hosts: <pool>` place containers on a
|
||||
host pool (see Host providers below).
|
||||
|
||||
### Host providers
|
||||
|
||||
A host provider makes machines; the pool (`pipewright.hosts.HostPool`) does setup,
|
||||
health, placement, scaling, TTL extension, images and accounting.
|
||||
|
||||
```python
|
||||
from pipewright import register_host_provider
|
||||
from pipewright.hosts import Host, HostProvider
|
||||
|
||||
class MyCloud(HostProvider):
|
||||
type = "mycloud"
|
||||
default_capacity = {"cpus": 16, "memory": "64g"}
|
||||
async def create(self, host_id, state_dir) -> Host:
|
||||
vm = await my_api.create(name=host_id) # boot, register an SSH key
|
||||
return Host(id=host_id, pool=self.name, docker_host=f"ssh://ubuntu@{vm.ip}")
|
||||
async def delete(self, host): await my_api.delete(host.meta["vm_id"])
|
||||
async def extend(self, host, seconds): ... # optional (TTL-based VMs)
|
||||
|
||||
register_host_provider("mycloud", MyCloud)
|
||||
```
|
||||
|
||||
`pipewright.hosts.vmapi.VMApiHostProvider` handles the common HTTP-VM-API parts (secret
|
||||
ref, retries, per-host SSH config with a pinned host key and ControlMaster);
|
||||
`pipewright.contrib.boat` is a complete example (~150 lines).
|
||||
|
||||
## Docs
|
||||
|
||||
- `docs/design.md` — architecture and decisions (what came from datatrove, DataDesigner,
|
||||
ComfyUI, and what was left out)
|
||||
- `docs/agents.md` — how an agent should author and debug a pipeline with the CLI
|
||||
- `docs/roadmap.md` — deferred work and known gaps
|
||||
- `docs/changes-for-plugins.md` — interface changes for plugin packs (host pools, imports, store)
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
+158
@@ -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:<cat>, 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: <pool>`
|
||||
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.
|
||||
@@ -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: {<pool>: {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: <pool>` (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 `<path>.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:<g> | <run id>`), `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 | "<key>"` 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`.
|
||||
+268
@@ -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:<ref>`
|
||||
recorded when an image is ensured, `volume:<name>` for warm named volumes), then the
|
||||
tightest fit, so other hosts drain and can be deleted. Scaling simulates packing the
|
||||
waiting requests onto hosts already being created and starts only the missing ones,
|
||||
within `max`, the hours/$ budget, a creation backoff, and a hard `create_limit` per
|
||||
pool lifetime (a guard against runaway billing when setup keeps failing). Host time is
|
||||
accounted per host lifetime (creation to deletion), not per lease. Sandboxes stay
|
||||
Docker containers driven from the orchestrating machine with `docker -H ssh://…`; each
|
||||
host gets an SSH config (pinned host key, ControlMaster) and Docker's SSH helper is
|
||||
pointed at it with a per-host `ssh` wrapper on PATH. Agents in those containers reach
|
||||
the local logging proxy through `Sandbox.reverse(port)`: one `ssh -N -R` tunnel per host
|
||||
(sshd binds it to the host's loopback) plus a tiny relay on the Docker bridge gateway,
|
||||
so CLI harnesses work unchanged on remote hosts. Host providers only create,
|
||||
delete and extend machines; everything else is shared. Hosts can persist across runs
|
||||
(`persist: true`; the next process adopts them after a health check) and `pw hosts`
|
||||
manages them between runs; every host event is appended to
|
||||
`<store>/hosts/<pool>/events.jsonl`, and the state file lets `pw hosts down|orphans`
|
||||
clean up after crashes.
|
||||
|
||||
### Many workers on one store
|
||||
The store buffers hot-path writes (items, lineage, flows, events, memo, usage, request
|
||||
cache) in memory and commits them with one `executemany` per statement inside a short
|
||||
`BEGIN IMMEDIATE` transaction (every 5000 rows or 0.5 s), so the write lock is held for
|
||||
milliseconds instead of while Python works. Readers in the same process share the
|
||||
connection (one per store path), memo/request-cache lookups consult in-memory overlays,
|
||||
and query-style reads flush first. Node memo entries are preloaded per signature at
|
||||
plan time, so replays do no per-item lookups. With this, `--shard I/N` workers scale
|
||||
on one SQLite file (4 workers: 2.6x on the benchmark); a store server remains on the
|
||||
roadmap for multi-machine sharding without a shared filesystem.
|
||||
|
||||
### Shared rate limits and incremental sinks
|
||||
`rate: {shared: true}` moves a provider's rolling window and 429 gate into a SQLite
|
||||
ledger (`~/.cache/pipewright/rate/<key>.sqlite`); admission checks the window and
|
||||
records the request in one `BEGIN IMMEDIATE` transaction, so rejected requests count
|
||||
for every process and a 429 in one closes the gate for all. Each process keeps its own
|
||||
priority queue and re-polls the ledger while waiting. `sink.jsonl` appends rows for new
|
||||
items only (a sidecar `<path>.pwindex` records written ids, the file size and a params
|
||||
hash; a mismatch triggers a full rewrite), so re-running a large graph does not rewrite
|
||||
its exports.
|
||||
|
||||
### Counter budgets
|
||||
Some budgets are counts, not dollars (e.g. "at most 60 rollouts of model X", when the
|
||||
provider reports no cost). `budgets: {counters: {name: limit}}` with `ctx.count(name)`
|
||||
in a node: over the limit only that call raises BudgetExceeded (the item is pending and
|
||||
resumes next run); other work continues.
|
||||
|
||||
## What came from where
|
||||
|
||||
**datatrove** — taken: steps independent of the executor; completion state per unit of
|
||||
work so reruns skip completed work; a request cache for LLM calls; stats per step;
|
||||
rank/world-size style sharding of sources (`--shard I/N`, by key hash, so all items
|
||||
derived from one source item stay in one shard). Not taken: file-shard outputs per rank
|
||||
— shards share one store and a final unsharded replay writes the sinks.
|
||||
|
||||
**NVIDIA DataDesigner** — taken: model *aliases* configured per project (graphs never
|
||||
name a concrete model); dependency-aware labels (structured LLM labels whose schema is
|
||||
declared next to the prompt, validated with a repair re-ask); validators/judges as
|
||||
ordinary nodes; preview vs. create (`pw preview` = the same engine on n items up to a
|
||||
node); plugins. Not taken: the column-centric dataset model — pipewright's unit is an
|
||||
item flowing through a graph, because tasks fan out (k rollouts), fan in (pass rates)
|
||||
and route, which columns model poorly.
|
||||
|
||||
**ComfyUI** — taken: typed node graph with ports checked at load time; workflow as a
|
||||
JSON file with links on the consuming node; cache per node by input hash so only what
|
||||
changed re-executes; custom node packs via a registry; "run up to a node" (`--upto`).
|
||||
Not taken: the UI, and caching only the latest execution — pipewright memoizes every
|
||||
result persistently, per item.
|
||||
|
||||
**Agent-authoring work** — ComfyBench/ComfyAgent (LLMs author graphs better as code →
|
||||
the Python builder), n8n-MCP (node docs + layered validation tools → `nodes describe`
|
||||
and `check`), Dagster Components/`dg` (schema-backed YAML, `dg check`, example values
|
||||
→ params schemas and tested examples), Spec Graph (schema-validated graph patches →
|
||||
`pw patch`).
|
||||
|
||||
## Deliberately not in v0
|
||||
|
||||
- Distributed execution without a shared filesystem (shards share one SQLite store).
|
||||
- A web UI (static HTML report only).
|
||||
- Streaming token-level responses to callers (batch pipelines do not need them).
|
||||
- DuckDB analytics (SQLite is stdlib; the index is plain SQL and can be attached).
|
||||
- Automatic schema inference for payloads (port kinds are names, not JSON schemas).
|
||||
See `roadmap.md`.
|
||||
@@ -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.
|
||||
@@ -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})}}]}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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}"}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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})}}]}
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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}
|
||||
@@ -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)",
|
||||
]
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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
|
||||
@@ -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 | <run id>")
|
||||
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 <dir>/<conversation>.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())
|
||||
@@ -0,0 +1 @@
|
||||
"""Optional plugins shipped with pipewright (loaded through entry points)."""
|
||||
@@ -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: <id>`; 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)
|
||||
@@ -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
|
||||
|
||||
@@ -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}")
|
||||
@@ -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, "<expr>", "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)]
|
||||
@@ -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 `<alias>:<node>.<port>`; 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 | <run id>: 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)
|
||||
@@ -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"]
|
||||
@@ -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:]}"
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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"]
|
||||
@@ -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<user>[^@]+)@)?(?P<host>[^:]+)(?::(?P<port>\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 <ssh_config>`."""
|
||||
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.<pool>:` 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
|
||||
@@ -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:<ref> / volume:<name> 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 <<EOF
|
||||
#!/usr/bin/env python3
|
||||
import json, os, sys
|
||||
args = sys.argv[1:]
|
||||
if any(a in ("create", "run") for a in args):
|
||||
bundle = os.getcwd()
|
||||
for flag in ("--bundle", "-b"):
|
||||
if flag in args:
|
||||
bundle = args[args.index(flag) + 1]
|
||||
path = os.path.join(bundle, "config.json")
|
||||
if os.path.exists(path) and os.path.exists("/dev/kvm"):
|
||||
spec = json.load(open(path))
|
||||
linux = spec.setdefault("linux", {})
|
||||
devices = linux.setdefault("devices", [])
|
||||
st = os.stat("/dev/kvm")
|
||||
major, minor = os.major(st.st_rdev), os.minor(st.st_rdev)
|
||||
kvm = [d for d in devices if d.get("path") == "/dev/kvm"]
|
||||
for d in kvm:
|
||||
d["fileMode"] = 0o666
|
||||
if not kvm:
|
||||
devices.append({"path": "/dev/kvm", "type": "c", "major": major, "minor": minor,
|
||||
"fileMode": 0o666, "uid": 0, "gid": 0})
|
||||
linux.setdefault("resources", {}).setdefault("devices", []).append(
|
||||
{"allow": True, "type": "c", "major": major, "minor": minor, "access": "rwm"})
|
||||
json.dump(spec, open(path, "w"))
|
||||
os.execv("$RUNC", ["runc"] + args)
|
||||
EOF
|
||||
sudo chmod +x /usr/local/bin/runc-kvm
|
||||
set +e
|
||||
sudo python3 - <<'PY'
|
||||
import json, os, sys
|
||||
p = "/etc/docker/daemon.json"
|
||||
cfg = json.load(open(p)) if os.path.exists(p) else {}
|
||||
want = {"path": "/usr/local/bin/runc-kvm"}
|
||||
if cfg.get("runtimes", {}).get("kvm") != want or cfg.get("default-runtime") != "kvm":
|
||||
cfg.setdefault("runtimes", {})["kvm"] = want
|
||||
cfg["default-runtime"] = "kvm"
|
||||
json.dump(cfg, open(p, "w"), indent=2)
|
||||
sys.exit(10)
|
||||
PY
|
||||
rc=$?
|
||||
set -e
|
||||
if [ $rc = 10 ]; then sudo systemctl restart docker; elif [ $rc != 0 ]; then exit $rc; fi
|
||||
for i in $(seq 30); do docker info >/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 <host> ...` 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:<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:<port>; 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(":<none>")}
|
||||
|
||||
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)
|
||||
@@ -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)
|
||||
@@ -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: <provider> # 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; <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)
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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:<g>|<run id>); 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()
|
||||
@@ -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"]
|
||||
@@ -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: "<key>"` 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,
|
||||
)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,209 @@
|
||||
"""OpenAI-compatible chat completions over httpx, with quirk adapters.
|
||||
|
||||
Config (project `providers.<name>`):
|
||||
|
||||
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)
|
||||
@@ -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://<host>:<port>/v1` and `OPENAI_API_KEY=<session token>`. 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 <log_dir>/<conversation>.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"}
|
||||
@@ -0,0 +1 @@
|
||||
"""Node types. `base` defines the interface; `builtin` and `agentic` ship generic types."""
|
||||
@@ -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: `<label>` (all met) and `checks.<name>`."""
|
||||
|
||||
name = "sandbox.check"
|
||||
kind = "map"
|
||||
Params = SandboxCheckParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {
|
||||
"pool": "docker",
|
||||
"files_expr": "payload.files",
|
||||
"checks": [
|
||||
{"name": "gold", "files": {"solution.py": "{{ payload.solution }}"},
|
||||
"command": "python -m pytest -q test_solution.py", "expect": "pass"},
|
||||
{"name": "empty", "files": {"solution.py": "{{ payload.stub }}"},
|
||||
"command": "python -m pytest -q test_solution.py", "expect": "fail"},
|
||||
],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
return [ResourceRef(type="sandbox", name=params.pool, param="pool")] if params else []
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
exprs: list[str] = []
|
||||
for c in params.checks:
|
||||
exprs += template_exprs(c.command)
|
||||
for k, v in c.files.items():
|
||||
exprs += template_exprs(k) + template_exprs(v)
|
||||
if c.files_expr:
|
||||
exprs.append(c.files_expr)
|
||||
for k, v in params.files.items():
|
||||
exprs += template_exprs(k) + template_exprs(v)
|
||||
if params.files_expr:
|
||||
exprs.append(params.files_expr)
|
||||
return _check_exprs(exprs)
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params):
|
||||
return {"sandbox_runs": len(params.checks), "sandbox_seconds": 15 * len(params.checks)}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
|
||||
async def run_check(check: CheckSpec) -> dict:
|
||||
async with ctx.sandbox(p.pool) as sb:
|
||||
await write_files(sb, item, p.files, p.files_expr)
|
||||
await write_files(sb, item, check.files, check.files_expr)
|
||||
r = await sb.exec(render_item(check.command, item), timeout=check.timeout)
|
||||
passed = r.ok
|
||||
return {"exit_code": r.exit_code, "timed_out": r.timed_out, "passed": passed,
|
||||
"met": passed if check.expect == "pass" else (not passed and not r.timed_out),
|
||||
"output": (r.stdout + r.stderr)[-p.output_chars:]}
|
||||
|
||||
outs = await asyncio.gather(*(run_check(c) for c in p.checks))
|
||||
results: dict[str, Any] = {c.name: o for c, o in zip(p.checks, outs, strict=False)}
|
||||
valid = all(v["met"] for v in results.values())
|
||||
return item.derive(update_labels={p.label: valid, "checks": results})
|
||||
|
||||
|
||||
class GradeSpec(P):
|
||||
command: str = Field(description="template; exit 0 = passed")
|
||||
files: dict[str, str] = Field(default_factory=dict, description="hidden files written AFTER the agent ran")
|
||||
files_expr: str | None = None
|
||||
timeout: float = Field(300, gt=0)
|
||||
|
||||
|
||||
class AgentRunParams(P):
|
||||
harness: str = Field(description="harness name from the project file")
|
||||
pool: str | None = Field(None, description="sandbox pool (not needed for harnesses that own their runtime)")
|
||||
prompt: str = Field(description="template for the task prompt")
|
||||
system: str | None = None
|
||||
files: dict[str, str] = Field(default_factory=dict, description="path -> template, the task's starting files")
|
||||
files_expr: str | None = Field(None, description="expression giving {path: content}, e.g. payload.files")
|
||||
grade: GradeSpec | None = Field(None, description="run after the agent finishes; sets label `passed`")
|
||||
max_turns: int | None = Field(None, ge=1)
|
||||
timeout: float | None = Field(None, gt=0, description="agent wall-clock seconds (a result, not an error)")
|
||||
keep_trajectory: bool = Field(True, description="store the trajectory as artifact `trajectory`")
|
||||
|
||||
|
||||
@register_node
|
||||
class AgentRun(NodeType):
|
||||
"""Run an agent harness on the item's task inside a sandbox, then (optionally) grade
|
||||
the final workspace. Labels: passed, agent_status, turns, input_tokens,
|
||||
output_tokens. Provider failures are retried, never recorded as a failed attempt.
|
||||
Put `flatmap.repeat` in front for k rollouts per task."""
|
||||
|
||||
name = "agent.run"
|
||||
kind = "map"
|
||||
Params = AgentRunParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {
|
||||
"harness": "mini",
|
||||
"pool": "docker",
|
||||
"prompt": "{{ payload.statement }}\n\nWrite your solution to solution.py.",
|
||||
"files_expr": "payload.files",
|
||||
"grade": {"command": "python -m pytest -q test_solution.py",
|
||||
"files": {"test_solution.py": "{{ payload.tests }}"}},
|
||||
"max_turns": 20,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
if params is None:
|
||||
return []
|
||||
out = [ResourceRef(type="harness", name=params.harness, param="harness")]
|
||||
if params.pool:
|
||||
out.append(ResourceRef(type="sandbox", name=params.pool, param="pool"))
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
exprs = template_exprs(params.prompt) + template_exprs(params.system or "")
|
||||
for k, v in params.files.items():
|
||||
exprs += template_exprs(k) + template_exprs(v)
|
||||
if params.files_expr:
|
||||
exprs.append(params.files_expr)
|
||||
if params.grade:
|
||||
exprs += template_exprs(params.grade.command)
|
||||
for k, v in params.grade.files.items():
|
||||
exprs += template_exprs(k) + template_exprs(v)
|
||||
return _check_exprs(exprs)
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params):
|
||||
turns = params.max_turns or 30
|
||||
return {"llm_calls": turns * 0.6, "input_tokens": turns * 0.6 * 4000, "output_tokens": turns * 0.6 * 300,
|
||||
"sandbox_runs": 1, "sandbox_seconds": 120}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
harness = ctx.harness(p.harness)
|
||||
task = AgentTask(prompt=render_item(p.prompt, item),
|
||||
system=render_item(p.system, item) if p.system else None,
|
||||
max_turns=p.max_turns, timeout=p.timeout)
|
||||
hctx = ctx.harness_context(cache_salt=item.id)
|
||||
labels: dict[str, Any] = {}
|
||||
if harness.owns_sandbox:
|
||||
traj = await harness.run(task, None, hctx)
|
||||
else:
|
||||
if not p.pool:
|
||||
raise ConfigError(f"{ctx.node_id}: harness {p.harness} needs a sandbox pool (`pool`)")
|
||||
async with ctx.sandbox(p.pool) as sb:
|
||||
await write_files(sb, item, p.files, p.files_expr)
|
||||
traj = await harness.run(task, sb, hctx)
|
||||
if p.grade:
|
||||
await write_files(sb, item, p.grade.files, p.grade.files_expr)
|
||||
r = await sb.exec(render_item(p.grade.command, item), timeout=p.grade.timeout)
|
||||
labels["passed"] = r.ok
|
||||
labels["grade_output"] = (r.stdout + r.stderr)[-1500:]
|
||||
labels.update({"agent_status": traj.status, "turns": traj.turns,
|
||||
"input_tokens": int(traj.usage.get("input_tokens", 0)),
|
||||
"output_tokens": int(traj.usage.get("output_tokens", 0))})
|
||||
artifacts = dict(item.artifacts)
|
||||
if p.keep_trajectory:
|
||||
artifacts["trajectory"] = ctx.put_blob(traj.model_dump_json(), "application/json", "trajectory.json")
|
||||
return item.derive(update_labels=labels, artifacts=artifacts)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Node types: the unit of domain behaviour.
|
||||
|
||||
A graph uses a small, fixed vocabulary of node KINDS (how items flow), and any
|
||||
number of registered node TYPES (what happens to them):
|
||||
|
||||
source () -> items generate()
|
||||
map 1 item -> 1 item process() returns an Item
|
||||
flatmap 1 item -> n items process() returns a list of Items
|
||||
filter 1 item -> out | rejected process() returns bool
|
||||
route 1 item -> named ports process() returns a port name (or list, or None)
|
||||
join all items -> items join() gets every input port's items at once
|
||||
retry 1 item -> out | exhausted bounded check -> fix loop (see nodes.builtin.Retry)
|
||||
review 1 item -> approved | rejected parks items for a human (engine-handled)
|
||||
sink all items -> (side effect) write()
|
||||
|
||||
Write a node type by subclassing NodeType, declaring `Params` (a pydantic model, which
|
||||
becomes the JSON schema shown by `pw nodes describe`) and implementing the method for
|
||||
its kind; register it with `@register_node`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, AsyncIterator, ClassVar, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from ..items import Item
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..engine import NodeContext
|
||||
from ..project import Project
|
||||
|
||||
Kind = Literal["source", "map", "flatmap", "filter", "route", "join", "retry", "review", "sink"]
|
||||
KINDS: tuple[str, ...] = ("source", "map", "flatmap", "filter", "route", "join", "retry", "review", "sink")
|
||||
ANY = "*"
|
||||
SAME = "same" # output kind = kind of the item on the input port
|
||||
|
||||
|
||||
class Port(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
kind: str = ANY
|
||||
"""Item kind carried: a concrete kind (`issue`), `*` (anything) or `same` (outputs only)."""
|
||||
description: str = ""
|
||||
optional: bool = False
|
||||
"""Input ports: may be left unconnected. Output ports: unconnected is not a warning."""
|
||||
|
||||
|
||||
class NoParams(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class ResourceRef(BaseModel):
|
||||
"""A project resource a node needs: a model alias, sandbox pool or harness."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
type: Literal["model", "sandbox", "harness"]
|
||||
name: str
|
||||
param: str = ""
|
||||
"""The param that names it (for error messages)."""
|
||||
|
||||
|
||||
class NodeType:
|
||||
name: ClassVar[str]
|
||||
kind: ClassVar[Kind]
|
||||
version: ClassVar[str] = "1"
|
||||
description: ClassVar[str] = ""
|
||||
Params: ClassVar[type[BaseModel]] = NoParams
|
||||
inputs: ClassVar[dict[str, Port]] = {"in": Port()}
|
||||
outputs: ClassVar[dict[str, Port]] = {"out": Port(kind=SAME)}
|
||||
example: ClassVar[dict[str, Any]] = {}
|
||||
"""Params for a working example (shown by `pw nodes describe`; tested to validate)."""
|
||||
cacheable: ClassVar[bool] = True
|
||||
"""Whether results are memoized per input item (sources: per params)."""
|
||||
|
||||
def __init__(self, node_id: str, params: BaseModel):
|
||||
self.id = node_id
|
||||
self.params = params
|
||||
|
||||
# ------------------------------------------------------------------ static info
|
||||
@classmethod
|
||||
def input_ports(cls, params: BaseModel) -> dict[str, Port]:
|
||||
return {} if cls.kind == "source" else dict(cls.inputs)
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params: BaseModel) -> dict[str, Port]:
|
||||
if cls.kind == "sink":
|
||||
return {}
|
||||
return dict(cls.outputs)
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params: BaseModel) -> list[ResourceRef]:
|
||||
"""Project resources this node needs (checked by `pw check`)."""
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def identity(cls, params: BaseModel, project: "Project") -> dict:
|
||||
"""Extra memo identity: resolved resources whose change should invalidate results
|
||||
(e.g. which concrete model an alias points to). Default: resolve `resources()`."""
|
||||
out: dict[str, Any] = {}
|
||||
for r in cls.resources(params):
|
||||
out[f"{r.type}:{r.name}"] = project.resource_identity(r)
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params: BaseModel) -> dict[str, float]:
|
||||
"""Per-item resource estimate for budget checks, e.g. {"llm_calls": 1,
|
||||
"input_tokens": 800, "output_tokens": 300, "sandbox_seconds": 20}."""
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params: BaseModel) -> list[str]:
|
||||
"""Semantic checks beyond the schema (expressions compile, inner types exist...).
|
||||
Return human-readable problems; `pw check` reports them."""
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def estimate_count(cls, params: BaseModel, project: "Project") -> int | None:
|
||||
"""Sources: how many items a run will produce, if cheaply knowable."""
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def estimate_factor(cls, params: BaseModel) -> float:
|
||||
"""Items out per item in (for budget estimates); filters/routes assume 1."""
|
||||
return 1.0
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict:
|
||||
p = cls.Params.model_validate(cls.example) if cls.example or cls.Params is NoParams else None
|
||||
return {
|
||||
"type": cls.name,
|
||||
"kind": cls.kind,
|
||||
"version": cls.version,
|
||||
"description": (cls.description or cls.__doc__ or "").strip(),
|
||||
"inputs": {k: v.model_dump() for k, v in cls.input_ports(p).items()} if p is not None
|
||||
else {k: v.model_dump() for k, v in cls.inputs.items()},
|
||||
"outputs": {k: v.model_dump() for k, v in cls.output_ports(p).items()} if p is not None
|
||||
else {k: v.model_dump() for k, v in cls.outputs.items()},
|
||||
"params_schema": cls.Params.model_json_schema(),
|
||||
"resources": [r.model_dump() for r in cls.resources(p)] if p is not None else [],
|
||||
"cost_hint": cls.cost_hint(p) if p is not None else {},
|
||||
"cacheable": cls.cacheable,
|
||||
"example": {"type": cls.name, "params": cls.example},
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ behaviour
|
||||
async def setup(self, ctx: "NodeContext") -> None:
|
||||
"""Called once per run before any item."""
|
||||
|
||||
async def generate(self, ctx: "NodeContext") -> AsyncIterator[Item]: # source
|
||||
raise NotImplementedError
|
||||
yield # pragma: no cover
|
||||
|
||||
async def process(self, item: Item, ctx: "NodeContext") -> Any: # map/flatmap/filter/route
|
||||
raise NotImplementedError
|
||||
|
||||
async def join(self, inputs: dict[str, list[Item]], ctx: "NodeContext") -> list[Item]: # join
|
||||
raise NotImplementedError
|
||||
|
||||
async def write(self, items: list[Item], ctx: "NodeContext") -> dict | None: # sink
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def params_class(node_type: str):
|
||||
"""Decorator for Params classes so typed builder calls know their node type."""
|
||||
|
||||
def wrap(cls):
|
||||
cls.__node_type__ = node_type
|
||||
return cls
|
||||
|
||||
return wrap
|
||||
@@ -0,0 +1,929 @@
|
||||
"""Generic built-in node types (no domain logic)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from ..errors import NodeError
|
||||
from ..expr import ITEM_NAMES, check_expr, eval_item, render_item, template_exprs
|
||||
from ..hashing import digest
|
||||
from ..items import Item
|
||||
from ..registry import register_node
|
||||
from .base import ANY, SAME, NodeType, Port, ResourceRef
|
||||
|
||||
|
||||
class P(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
def _callable(path: str):
|
||||
mod, _, fn = path.partition(":")
|
||||
if not fn:
|
||||
raise NodeError(f"callable must look like 'module:function', got {path!r}")
|
||||
return getattr(importlib.import_module(mod), fn)
|
||||
|
||||
|
||||
# ====================================================================== sources
|
||||
class SourceFileParams(P):
|
||||
path: str = Field(description="JSONL, JSON (array) or CSV file, relative to the project dir")
|
||||
kind: str = Field(description="item kind to assign, e.g. `issue`")
|
||||
key_field: str | None = Field("id", description="record field used as the item key (default: `id`; "
|
||||
"falls back to the row number)")
|
||||
provenance: Literal["real", "derived", "synthetic"] = "real"
|
||||
labels_field: str | None = Field(None, description="record field holding pre-existing labels")
|
||||
|
||||
|
||||
@register_node
|
||||
class SourceFile(NodeType):
|
||||
"""Read records from a local JSONL/JSON/CSV file; one item per record."""
|
||||
|
||||
name = "source.file"
|
||||
kind = "source"
|
||||
Params = SourceFileParams
|
||||
outputs = {"out": Port(kind=ANY, description="one item per record")}
|
||||
cacheable = False # re-read every run (cheap); downstream memoization keys on item content
|
||||
example = {"path": "data/records.jsonl", "kind": "issue", "key_field": "id"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
@staticmethod
|
||||
def read_records(path: Path) -> list[dict]:
|
||||
if path.suffix == ".csv":
|
||||
with path.open(newline="") as f:
|
||||
return list(csv.DictReader(f))
|
||||
text = path.read_text()
|
||||
if path.suffix == ".json":
|
||||
data = json.loads(text)
|
||||
return data if isinstance(data, list) else [data]
|
||||
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
||||
|
||||
@classmethod
|
||||
def estimate_count(cls, params, project) -> int | None:
|
||||
try:
|
||||
return len(cls.read_records(project.resolve_path(params.path)))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
async def generate(self, ctx):
|
||||
p = self.params
|
||||
path = ctx.resolve_path(p.path)
|
||||
if not path.exists():
|
||||
raise NodeError(f"source file not found: {path}")
|
||||
for i, rec in enumerate(self.read_records(path)):
|
||||
if not isinstance(rec, dict):
|
||||
rec = {"value": rec}
|
||||
key = str(rec.get(p.key_field)) if p.key_field and rec.get(p.key_field) is not None else f"{path.stem}#{i}"
|
||||
labels = rec.pop(p.labels_field, None) if p.labels_field else None
|
||||
yield Item(key=key, kind=p.kind, payload=rec, labels=labels or {}, provenance=p.provenance)
|
||||
|
||||
|
||||
class SourceInlineParams(P):
|
||||
kind: str
|
||||
records: list[dict[str, Any]] = Field(description="the records themselves")
|
||||
key_field: str | None = "id"
|
||||
provenance: Literal["real", "derived", "synthetic"] = "real"
|
||||
|
||||
|
||||
@register_node
|
||||
class SourceInline(NodeType):
|
||||
"""Items given inline in the graph file (small fixtures, smoke tests)."""
|
||||
|
||||
name = "source.inline"
|
||||
kind = "source"
|
||||
Params = SourceInlineParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
cacheable = False
|
||||
example = {"kind": "question", "records": [{"id": "q1", "text": "What is 2+2?"}]}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
@classmethod
|
||||
def estimate_count(cls, params, project) -> int | None:
|
||||
return len(params.records)
|
||||
|
||||
async def generate(self, ctx):
|
||||
p = self.params
|
||||
for i, rec in enumerate(p.records):
|
||||
key = str(rec.get(p.key_field)) if p.key_field and rec.get(p.key_field) is not None else f"inline#{i}"
|
||||
yield Item(key=key, kind=p.kind, payload=dict(rec), provenance=p.provenance)
|
||||
|
||||
|
||||
class SourcePriorParams(P):
|
||||
graph: str = Field(description="graph name whose earlier run to read")
|
||||
node: str
|
||||
port: str | None = None
|
||||
run_id: str | None = Field(None, description="default: latest completed run of that graph")
|
||||
kind: str = Field(ANY, description="declared kind of the items (for type checking)")
|
||||
|
||||
|
||||
@register_node
|
||||
class SourcePrior(NodeType):
|
||||
"""Items that flowed out of a node in a previous run — for feedback loops across runs
|
||||
(e.g. recalibrate a difficulty score from last week's probe results)."""
|
||||
|
||||
name = "source.prior_run"
|
||||
kind = "source"
|
||||
Params = SourcePriorParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
cacheable = False
|
||||
example = {"graph": "qa-labeling", "node": "route", "port": "triage", "kind": "issue"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
async def generate(self, ctx):
|
||||
p = self.params
|
||||
for item in ctx.prior_items(p.graph, p.node, p.port, p.run_id):
|
||||
yield item
|
||||
|
||||
|
||||
# ====================================================================== expressions
|
||||
def _check_exprs(exprs: dict[str, str] | list[str], extra: set[str] = frozenset()) -> list[str]:
|
||||
vals = exprs.values() if isinstance(exprs, dict) else exprs
|
||||
return [m for m in (check_expr(e, ITEM_NAMES | set(extra)) for e in vals) if m]
|
||||
|
||||
|
||||
class LabelExprParams(P):
|
||||
labels: dict[str, str] = Field(description="label name -> expression over the item")
|
||||
|
||||
|
||||
@register_node
|
||||
class LabelExpr(NodeType):
|
||||
"""Add heuristic labels computed by expressions (regex helpers: re, re_count, re_find)."""
|
||||
|
||||
name = "label.expr"
|
||||
kind = "map"
|
||||
Params = LabelExprParams
|
||||
inputs = {"in": Port()}
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {"labels": {"has_traceback": "re(r'traceback', payload.body)", "length": "len(payload.body)"}}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs(params.labels)
|
||||
|
||||
async def process(self, item, ctx):
|
||||
new = {k: eval_item(e, item) for k, e in self.params.labels.items()}
|
||||
return item.derive(update_labels=new)
|
||||
|
||||
|
||||
class MapExprParams(P):
|
||||
fields: dict[str, str] = Field(description="payload field -> expression; fields are set in order")
|
||||
kind: str | None = Field(None, description="change the item kind")
|
||||
drop: list[str] = Field(default_factory=list, description="payload fields to remove")
|
||||
key: str | None = Field(None, description="expression for a new item key (evaluated after `fields`), e.g. "
|
||||
"payload.name for a derived variant")
|
||||
|
||||
|
||||
@register_node
|
||||
class MapExpr(NodeType):
|
||||
"""Compute/rewrite payload fields with expressions (optionally change kind)."""
|
||||
|
||||
name = "map.expr"
|
||||
kind = "map"
|
||||
Params = MapExprParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {"fields": {"title": "payload.title.strip()", "n_words": "words(payload.body)"}}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params and params.kind else SAME)}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs(params.fields) + (_check_exprs([params.key]) if params.key else [])
|
||||
|
||||
async def process(self, item, ctx):
|
||||
payload = dict(item.payload)
|
||||
for k, e in self.params.fields.items():
|
||||
payload[k] = eval_item(e, item.model_copy(update={"payload": payload}))
|
||||
for k in self.params.drop:
|
||||
payload.pop(k, None)
|
||||
key = None
|
||||
if self.params.key:
|
||||
key = str(eval_item(self.params.key, item.model_copy(update={"payload": payload})))
|
||||
return item.derive(payload=payload, kind=self.params.kind, key=key)
|
||||
|
||||
|
||||
class FilterExprParams(P):
|
||||
expr: str = Field(description="keep the item when this is truthy")
|
||||
|
||||
|
||||
@register_node
|
||||
class FilterExpr(NodeType):
|
||||
"""Keep items for which the expression is truthy; others go to `rejected`."""
|
||||
|
||||
name = "filter.expr"
|
||||
kind = "filter"
|
||||
Params = FilterExprParams
|
||||
outputs = {"out": Port(kind=SAME), "rejected": Port(kind=SAME, optional=True)}
|
||||
example = {"expr": "len(payload.body) >= 80 and not labels.is_spam"}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs([params.expr])
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return bool(eval_item(self.params.expr, item))
|
||||
|
||||
|
||||
class RouteExprParams(P):
|
||||
routes: dict[str, str] = Field(description="output port -> expression, checked in order")
|
||||
default: str | None = Field("other", description="port for items matching no route (null: drop them)")
|
||||
multi: bool = Field(False, description="send to every matching port instead of the first")
|
||||
|
||||
|
||||
@register_node
|
||||
class RouteExpr(NodeType):
|
||||
"""Send each item to the first (or every) output port whose expression is truthy."""
|
||||
|
||||
name = "route.expr"
|
||||
kind = "route"
|
||||
Params = RouteExprParams
|
||||
outputs = {}
|
||||
example = {"routes": {"urgent": "labels.severity >= 2", "bugs": "labels.category == 'bug'"}, "default": "other"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
if params is None:
|
||||
return {}
|
||||
ports = {k: Port(kind=SAME) for k in params.routes}
|
||||
if params.default:
|
||||
ports[params.default] = Port(kind=SAME, optional=True)
|
||||
return ports
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs(params.routes)
|
||||
|
||||
async def process(self, item, ctx):
|
||||
hits = [port for port, e in self.params.routes.items() if eval_item(e, item)]
|
||||
if not self.params.multi:
|
||||
hits = hits[:1]
|
||||
if not hits and self.params.default:
|
||||
hits = [self.params.default]
|
||||
return hits
|
||||
|
||||
|
||||
# ====================================================================== python escape hatches
|
||||
class PyParams(P):
|
||||
function: str = Field(description="'module:function'; called as fn(item, **kwargs) (may be async)")
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
version: str = Field("1", description="bump to invalidate memoized results after changing the code")
|
||||
|
||||
|
||||
async def _call(fn, *args, **kw):
|
||||
import inspect
|
||||
|
||||
out = fn(*args, **kw)
|
||||
return await out if inspect.isawaitable(out) else out
|
||||
|
||||
|
||||
@register_node
|
||||
class PyMap(NodeType):
|
||||
"""Call a Python function per item; it returns an Item (e.g. item.derive(...)) or a
|
||||
dict of payload updates."""
|
||||
|
||||
name = "python.map"
|
||||
kind = "map"
|
||||
Params = PyParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
example = {"function": "mypack.steps:normalize", "kwargs": {}}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
out = await _call(_callable(self.params.function), item, **self.params.kwargs)
|
||||
if isinstance(out, dict):
|
||||
return item.derive(update_payload=out)
|
||||
return out
|
||||
|
||||
|
||||
@register_node
|
||||
class PyFilter(NodeType):
|
||||
"""Call a Python predicate per item."""
|
||||
|
||||
name = "python.filter"
|
||||
kind = "filter"
|
||||
Params = PyParams
|
||||
outputs = {"out": Port(kind=SAME), "rejected": Port(kind=SAME, optional=True)}
|
||||
example = {"function": "mypack.steps:is_interesting"}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return bool(await _call(_callable(self.params.function), item, **self.params.kwargs))
|
||||
|
||||
|
||||
@register_node
|
||||
class PyFlatMap(NodeType):
|
||||
"""Call a Python function per item that returns a list of Items."""
|
||||
|
||||
name = "python.flatmap"
|
||||
kind = "flatmap"
|
||||
Params = PyParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
example = {"function": "mypack.steps:split_into_chunks"}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return list(await _call(_callable(self.params.function), item, **self.params.kwargs))
|
||||
|
||||
|
||||
# ====================================================================== fan-out / fan-in
|
||||
class RepeatParams(P):
|
||||
k: int = Field(ge=1, le=1000, description="copies per item")
|
||||
label: str = Field("rollout", description="label holding the copy index (0..k-1)")
|
||||
|
||||
|
||||
@register_node
|
||||
class Repeat(NodeType):
|
||||
"""Fan an item out into k copies (e.g. k rollouts). Copies get key `<key>/<label><i>`,
|
||||
label `<label>` = i and label `group` = the original key (for join.group)."""
|
||||
|
||||
name = "flatmap.repeat"
|
||||
kind = "flatmap"
|
||||
Params = RepeatParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {"k": 2}
|
||||
|
||||
@classmethod
|
||||
def estimate_factor(cls, params) -> float:
|
||||
return params.k
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
return [item.derive(key=f"{item.key}/{p.label}{i}", update_labels={p.label: i, "group": item.key})
|
||||
for i in range(p.k)]
|
||||
|
||||
|
||||
AggFn = Literal["count", "mean", "sum", "min", "max", "any", "all", "list"]
|
||||
|
||||
|
||||
class GroupParams(P):
|
||||
by: str = Field("labels.group or key", description="expression giving the group key")
|
||||
kind: str = Field("group", description="kind of the group items")
|
||||
aggregates: dict[str, tuple[AggFn, str]] = Field(
|
||||
default_factory=dict, description="label -> [fn, expression per member]; fn in count/mean/sum/min/max/any/all/list")
|
||||
keep_members: bool = Field(True, description="store members (key, payload, labels) in payload.members")
|
||||
|
||||
|
||||
@register_node
|
||||
class JoinGroup(NodeType):
|
||||
"""Group items from all inputs by a key expression into one item per group, with
|
||||
aggregate labels (e.g. pass rate over k rollouts)."""
|
||||
|
||||
name = "join.group"
|
||||
kind = "join"
|
||||
Params = GroupParams
|
||||
inputs = {"in": Port()}
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
example = {"by": "labels.group", "aggregates": {"pass_rate": ["mean", "labels.passed"], "n": ["count", "1"]}}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs([params.by] + [e for _, e in params.aggregates.values()])
|
||||
|
||||
async def join(self, inputs, ctx):
|
||||
p = self.params
|
||||
groups: dict[str, list[Item]] = {}
|
||||
for items in inputs.values():
|
||||
for it in items:
|
||||
groups.setdefault(str(eval_item(p.by, it)), []).append(it)
|
||||
out = []
|
||||
for gkey, members in sorted(groups.items()):
|
||||
labels: dict[str, Any] = {}
|
||||
for name, (fn, expr) in p.aggregates.items():
|
||||
vals = [eval_item(expr, m) for m in members]
|
||||
labels[name] = _aggregate(fn, vals)
|
||||
payload: dict[str, Any] = {"group": gkey, "size": len(members)}
|
||||
if p.keep_members:
|
||||
payload["members"] = [{"key": m.key, "payload": m.payload, "labels": m.labels} for m in members]
|
||||
prov = "synthetic" if any(m.provenance == "synthetic" for m in members) else "derived"
|
||||
out.append(Item(key=gkey, kind=p.kind, payload=payload, labels=labels,
|
||||
parents=tuple(m.id for m in members), provenance=prov))
|
||||
return out
|
||||
|
||||
|
||||
def _aggregate(fn: str, vals: list) -> Any:
|
||||
nums = [float(v) for v in vals if isinstance(v, (int, float, bool))]
|
||||
if fn == "count":
|
||||
return len(vals)
|
||||
if fn == "list":
|
||||
return vals
|
||||
if fn == "any":
|
||||
return any(vals)
|
||||
if fn == "all":
|
||||
return all(vals)
|
||||
if not nums:
|
||||
return None
|
||||
return {"mean": lambda: sum(nums) / len(nums), "sum": lambda: sum(nums), "min": lambda: min(nums),
|
||||
"max": lambda: max(nums)}[fn]()
|
||||
|
||||
|
||||
class PairParams(P):
|
||||
left_key: str = Field("key", description="expression for the join key on `left` items")
|
||||
right_key: str = Field("key", description="expression for the join key on `right` items")
|
||||
kind: str = "pair"
|
||||
how: Literal["inner", "left"] = "inner"
|
||||
|
||||
|
||||
@register_node
|
||||
class JoinPair(NodeType):
|
||||
"""Pair items from `left` and `right` with equal join keys (inner or left join).
|
||||
Output payload: {left: {...}, right: {...} | null}."""
|
||||
|
||||
name = "join.pair"
|
||||
kind = "join"
|
||||
Params = PairParams
|
||||
inputs = {"left": Port(), "right": Port()}
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
example = {"left_key": "key", "right_key": "payload.source_key"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
async def join(self, inputs, ctx):
|
||||
p = self.params
|
||||
right: dict[str, list[Item]] = {}
|
||||
for it in inputs.get("right", []):
|
||||
right.setdefault(str(eval_item(p.right_key, it)), []).append(it)
|
||||
out = []
|
||||
for li in inputs.get("left", []):
|
||||
k = str(eval_item(p.left_key, li))
|
||||
matches = right.get(k, [])
|
||||
if not matches and p.how == "left":
|
||||
matches = [None]
|
||||
for ri in matches:
|
||||
view = lambda x: {"key": x.key, "payload": x.payload, "labels": x.labels} # noqa: E731
|
||||
out.append(Item(key=f"{li.key}+{ri.key}" if ri else li.key, kind=p.kind,
|
||||
payload={"left": view(li), "right": view(ri) if ri else None},
|
||||
parents=(li.id,) + ((ri.id,) if ri else ()), provenance="derived"))
|
||||
return out
|
||||
|
||||
|
||||
# ====================================================================== LLM
|
||||
class LLMGenerateParams(P):
|
||||
model: str = Field(description="model alias from the project file")
|
||||
prompt: str = Field(description="template; {{ expr }} is replaced, e.g. {{ payload.title }}")
|
||||
system: str | None = None
|
||||
output_field: str = Field("text", description="payload field receiving the response text")
|
||||
kind: str | None = Field(None, description="change the kind of the output item")
|
||||
params: dict[str, Any] = Field(default_factory=dict, description="extra request params (temperature, ...)")
|
||||
provenance: Literal["derived", "synthetic"] = "derived"
|
||||
|
||||
|
||||
@register_node
|
||||
class LLMGenerate(NodeType):
|
||||
"""Free-text LLM generation per item (rewrite, summarize, synthesize a variant)."""
|
||||
|
||||
name = "llm.generate"
|
||||
kind = "map"
|
||||
Params = LLMGenerateParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {"model": "labeler", "prompt": "Summarize in one sentence:\n\n{{ payload.body }}",
|
||||
"output_field": "summary"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params and params.kind else SAME)}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
return [ResourceRef(type="model", name=params.model, param="model")] if params else []
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs(template_exprs(params.prompt) + template_exprs(params.system or ""))
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params):
|
||||
return {"llm_calls": 1, "input_tokens": len(params.prompt) // 4 + 500, "output_tokens": 400}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
msgs = ([{"role": "system", "content": render_item(p.system, item)}] if p.system else [])
|
||||
msgs.append({"role": "user", "content": render_item(p.prompt, item)})
|
||||
res = await ctx.model(p.model).chat(msgs, **p.params)
|
||||
return item.derive(update_payload={p.output_field: res.content}, kind=p.kind, provenance=p.provenance)
|
||||
|
||||
|
||||
class LLMLabelParams(P):
|
||||
model: str
|
||||
prompt: str = Field(description="template; the label schema is appended automatically")
|
||||
system: str | None = None
|
||||
labels: dict[str, Any] = Field(description="label name -> JSON schema of its value "
|
||||
"(e.g. {type: integer, minimum: 0, maximum: 2})")
|
||||
prefix: str = Field("", description="prefix for the label names written to the item")
|
||||
structured: Literal["json_schema", "json_object", "none"] = Field(
|
||||
"json_schema", description="how to request structured output from the provider")
|
||||
repair_attempts: int = Field(1, ge=0, le=5, description="re-ask with the validation error this many times")
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _validate_value(name: str, schema: dict, v: Any) -> Any:
|
||||
t = schema.get("type")
|
||||
if v is None:
|
||||
if t == "null" or (isinstance(t, list) and "null" in t):
|
||||
return None
|
||||
raise ValueError(f"{name}: missing")
|
||||
if "enum" in schema and v not in schema["enum"]:
|
||||
raise ValueError(f"{name}: {v!r} not in {schema['enum']}")
|
||||
if t == "integer":
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)) or int(v) != v:
|
||||
raise ValueError(f"{name}: expected integer, got {v!r}")
|
||||
v = int(v)
|
||||
elif t == "number":
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
||||
raise ValueError(f"{name}: expected number, got {v!r}")
|
||||
elif t == "boolean":
|
||||
if isinstance(v, int) and v in (0, 1):
|
||||
v = bool(v)
|
||||
if not isinstance(v, bool):
|
||||
raise ValueError(f"{name}: expected boolean, got {v!r}")
|
||||
elif t == "string" and not isinstance(v, str):
|
||||
raise ValueError(f"{name}: expected string, got {v!r}")
|
||||
elif t == "array" and not isinstance(v, list):
|
||||
raise ValueError(f"{name}: expected array, got {v!r}")
|
||||
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
||||
if "minimum" in schema and v < schema["minimum"] or "maximum" in schema and v > schema["maximum"]:
|
||||
raise ValueError(f"{name}: {v} outside [{schema.get('minimum')}, {schema.get('maximum')}]")
|
||||
if isinstance(v, str) and "maxLength" in schema:
|
||||
v = v[: schema["maxLength"]]
|
||||
return v
|
||||
|
||||
|
||||
def parse_json_object(text: str) -> dict:
|
||||
text = text.strip()
|
||||
if text.startswith("```"):
|
||||
text = text.strip("`")
|
||||
text = text[text.find("\n") + 1:] if "\n" in text else text
|
||||
start, end = text.find("{"), text.rfind("}")
|
||||
if start < 0 or end < start:
|
||||
raise ValueError("no JSON object in the response")
|
||||
obj = json.loads(text[start:end + 1])
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("response JSON is not an object")
|
||||
return obj
|
||||
|
||||
|
||||
@register_node
|
||||
class LLMLabel(NodeType):
|
||||
"""Structured LLM labels: the model returns a JSON object with the declared label
|
||||
keys, validated against their schemas (with a repair re-ask), written to item.labels."""
|
||||
|
||||
name = "llm.label"
|
||||
kind = "map"
|
||||
Params = LLMLabelParams
|
||||
outputs = {"out": Port(kind=SAME)}
|
||||
example = {
|
||||
"model": "labeler",
|
||||
"prompt": "Classify this issue.\n\nTitle: {{ payload.title }}\n\n{{ payload.body }}",
|
||||
"labels": {"category": {"type": "string", "enum": ["bug", "feature", "question"]},
|
||||
"severity": {"type": "integer", "minimum": 0, "maximum": 2}},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
return [ResourceRef(type="model", name=params.model, param="model")] if params else []
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs(template_exprs(params.prompt) + template_exprs(params.system or ""))
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params):
|
||||
return {"llm_calls": 1, "input_tokens": len(params.prompt) // 4 + 600, "output_tokens": 300}
|
||||
|
||||
def schema(self) -> dict:
|
||||
return {"type": "object", "properties": self.params.labels, "required": list(self.params.labels),
|
||||
"additionalProperties": False}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
schema = self.schema()
|
||||
instructions = ("\n\nRespond with only a JSON object with exactly these keys and value schemas:\n"
|
||||
+ json.dumps(p.labels, indent=1))
|
||||
msgs = ([{"role": "system", "content": render_item(p.system, item)}] if p.system else [])
|
||||
msgs.append({"role": "user", "content": render_item(p.prompt, item) + instructions})
|
||||
kwargs = dict(p.params)
|
||||
if p.structured == "json_schema":
|
||||
kwargs["response_format"] = {"type": "json_schema",
|
||||
"json_schema": {"name": "labels", "schema": schema, "strict": True}}
|
||||
elif p.structured == "json_object":
|
||||
kwargs["response_format"] = {"type": "json_object"}
|
||||
client = ctx.model(p.model)
|
||||
last_err = ""
|
||||
for _attempt in range(p.repair_attempts + 1):
|
||||
res = await client.chat(msgs, **kwargs)
|
||||
try:
|
||||
obj = parse_json_object(res.content)
|
||||
labels = {f"{p.prefix}{k}": _validate_value(k, s, obj.get(k)) for k, s in p.labels.items()}
|
||||
return item.derive(update_labels=labels)
|
||||
except (ValueError, json.JSONDecodeError) as e:
|
||||
last_err = str(e)
|
||||
msgs = msgs + [{"role": "assistant", "content": res.content},
|
||||
{"role": "user", "content": f"That was invalid: {e}. Reply with only the corrected "
|
||||
"JSON object."}]
|
||||
raise NodeError(f"invalid structured output after {p.repair_attempts + 1} attempts: {last_err}")
|
||||
|
||||
|
||||
class LLMSynthParams(P):
|
||||
model: str
|
||||
prompt: str = Field(description="template; variables: {{ i }} (call index), {{ n }}, {{ batch }}")
|
||||
system: str | None = None
|
||||
calls: int = Field(1, ge=1, le=10000, description="number of generation calls")
|
||||
item_schema: dict[str, Any] = Field(description="JSON schema of one generated record (an object)")
|
||||
kind: str
|
||||
key_field: str | None = Field(None, description="record field to use as key (default: content hash)")
|
||||
batch: int = Field(5, ge=1, le=100, description="records requested per call")
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@register_node
|
||||
class LLMSynthesize(NodeType):
|
||||
"""Generate synthetic records with an LLM (provenance `synthetic`). Memoized per
|
||||
params, so re-running does not regenerate."""
|
||||
|
||||
name = "llm.synthesize"
|
||||
kind = "source"
|
||||
Params = LLMSynthParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
cacheable = True
|
||||
example = {"model": "generator", "kind": "task", "calls": 2, "batch": 3,
|
||||
"prompt": "Invent {{ batch }} distinct small Python exercises (variation #{{ i }}).",
|
||||
"item_schema": {"type": "object", "properties": {"title": {"type": "string"},
|
||||
"statement": {"type": "string"}},
|
||||
"required": ["title", "statement"]}}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=params.kind if params else ANY)}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
return [ResourceRef(type="model", name=params.model, param="model")] if params else []
|
||||
|
||||
@classmethod
|
||||
def estimate_count(cls, params, project) -> int | None:
|
||||
return params.calls * params.batch
|
||||
|
||||
@classmethod
|
||||
def cost_hint(cls, params):
|
||||
# per source run, not per item
|
||||
return {"llm_calls": params.calls, "input_tokens": params.calls * (len(params.prompt) // 4 + 300),
|
||||
"output_tokens": params.calls * params.batch * 400, "per_run": 1}
|
||||
|
||||
async def generate(self, ctx):
|
||||
import asyncio
|
||||
|
||||
p = self.params
|
||||
schema = {"type": "object", "properties": {"items": {"type": "array", "items": p.item_schema}},
|
||||
"required": ["items"], "additionalProperties": False}
|
||||
client = ctx.model(p.model)
|
||||
calls = p.calls if ctx.limit is None else min(p.calls, max(1, -(-ctx.limit // p.batch)))
|
||||
|
||||
async def one(i: int) -> list[dict]:
|
||||
from ..expr import render
|
||||
|
||||
prompt = render(p.prompt, {"i": i, "n": p.calls, "batch": p.batch})
|
||||
prompt += ("\n\nRespond with only a JSON object {\"items\": [...]} where each item matches:\n"
|
||||
+ json.dumps(p.item_schema))
|
||||
msgs = ([{"role": "system", "content": p.system}] if p.system else []) + [{"role": "user", "content": prompt}]
|
||||
res = await client.chat(msgs, response_format={"type": "json_schema", "json_schema": {
|
||||
"name": "items", "schema": schema}}, **p.params)
|
||||
try:
|
||||
recs = parse_json_object(res.content).get("items") or []
|
||||
except ValueError as e:
|
||||
raise NodeError(f"call {i}: unparseable synthesis output: {e}") from None
|
||||
return [r for r in recs if isinstance(r, dict)]
|
||||
|
||||
results = await asyncio.gather(*(one(i) for i in range(calls)))
|
||||
seen = set()
|
||||
for i, recs in enumerate(results):
|
||||
for _j, rec in enumerate(recs):
|
||||
key = str(rec.get(p.key_field)) if p.key_field and rec.get(p.key_field) else f"syn-{digest(rec, 10)}"
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
yield Item(key=key, kind=p.kind, payload=rec, labels={"synth_call": i}, provenance="synthetic")
|
||||
|
||||
|
||||
# ====================================================================== review / retry
|
||||
class ReviewParams(P):
|
||||
instructions: str = Field("", description="shown to the reviewer")
|
||||
auto_approve: str | None = Field(None, description="expression: approve without a human when truthy")
|
||||
auto_reject: str | None = Field(None, description="expression: reject without a human when truthy")
|
||||
|
||||
|
||||
@register_node
|
||||
class ReviewManual(NodeType):
|
||||
"""Park items for a human decision (`pw review`). Approved/rejected items continue on the
|
||||
matching port on the next run; undecided items stay parked."""
|
||||
|
||||
name = "review.manual"
|
||||
kind = "review"
|
||||
Params = ReviewParams
|
||||
outputs = {"approved": Port(kind=SAME), "rejected": Port(kind=SAME, optional=True)}
|
||||
cacheable = False
|
||||
example = {"instructions": "Is this task statement unambiguous?", "auto_approve": "labels.confidence >= 0.9"}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
if p.auto_reject and eval_item(p.auto_reject, item):
|
||||
return "rejected"
|
||||
if p.auto_approve and eval_item(p.auto_approve, item):
|
||||
return "approved"
|
||||
return None
|
||||
|
||||
|
||||
class InnerNode(P):
|
||||
type: str
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class RetryParams(P):
|
||||
check: InnerNode = Field(description="a filter or route node type; passing = `pass_port`")
|
||||
fix: InnerNode = Field(description="a map node type producing the next attempt from a failed one; it can "
|
||||
"read the failed check's labels")
|
||||
pass_port: str = Field("out", description="the check's port that means success")
|
||||
max_rounds: int = Field(3, ge=1, le=20, description="hard bound on check->fix rounds")
|
||||
|
||||
|
||||
@register_node
|
||||
class RetryLoop(NodeType):
|
||||
"""Bounded check -> fix loop around one item (e.g. validate -> repair -> validate, at
|
||||
most `max_rounds` times). Passing items leave on `out` (with label `rounds`),
|
||||
items still failing after `max_rounds` leave on `exhausted`. Each inner step is
|
||||
memoized per item like a graph node."""
|
||||
|
||||
name = "retry.loop"
|
||||
kind = "retry"
|
||||
Params = RetryParams
|
||||
outputs = {"out": Port(kind=SAME), "exhausted": Port(kind=SAME, optional=True)}
|
||||
example = {"check": {"type": "filter.expr", "params": {"expr": "labels.valid"}},
|
||||
"fix": {"type": "llm.generate", "params": {"model": "fixer", "prompt": "Fix: {{ payload.text }}",
|
||||
"output_field": "text"}},
|
||||
"max_rounds": 3}
|
||||
|
||||
@classmethod
|
||||
def resources(cls, params):
|
||||
from ..registry import registry
|
||||
|
||||
out = []
|
||||
if params is None:
|
||||
return out
|
||||
for inner in (params.check, params.fix):
|
||||
cls_ = registry.node_types.get(inner.type)
|
||||
if cls_ is not None:
|
||||
try:
|
||||
out += cls_.resources(cls_.Params.model_validate(inner.params))
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
from ..registry import registry
|
||||
|
||||
msgs = []
|
||||
for role, inner, kinds in (("check", params.check, ("filter", "route")), ("fix", params.fix, ("map",))):
|
||||
c = registry.node_types.get(inner.type)
|
||||
if c is None:
|
||||
msgs.append(f"{role}: unknown node type {inner.type!r}")
|
||||
continue
|
||||
if c.kind not in kinds:
|
||||
msgs.append(f"{role}: {inner.type} is a {c.kind} node; expected {' or '.join(kinds)}")
|
||||
try:
|
||||
c.Params.model_validate(inner.params)
|
||||
except Exception as e:
|
||||
msgs.append(f"{role}: invalid params for {inner.type}: {e}")
|
||||
return msgs
|
||||
|
||||
async def process(self, item, ctx):
|
||||
p = self.params
|
||||
current = item
|
||||
for rnd in range(1, p.max_rounds + 1):
|
||||
outs = await ctx.run_inner("check", p.check.type, p.check.params, current)
|
||||
passed = [(port, it) for port, it in outs if port == p.pass_port]
|
||||
checked = outs[0][1] if outs else current
|
||||
if passed:
|
||||
return ("out", passed[0][1].derive(update_labels={"rounds": rnd}))
|
||||
if rnd == p.max_rounds:
|
||||
return ("exhausted", checked.derive(update_labels={"rounds": rnd}))
|
||||
fixed = await ctx.run_inner("fix", p.fix.type, p.fix.params, checked)
|
||||
current = fixed[0][1] if fixed else checked
|
||||
return None # pragma: no cover
|
||||
|
||||
|
||||
# ====================================================================== sinks
|
||||
class SinkParams(P):
|
||||
path: str = Field(description="output file (.jsonl or .json), relative to the project dir")
|
||||
fields: list[str] | None = Field(None, description="dotted paths to export (default: whole item)")
|
||||
lineage: bool = Field(False, description="include parents/producer")
|
||||
mode: Literal["append", "rewrite"] = Field(
|
||||
"append", description="append: add rows only for items not yet in the file (sidecar `<path>.pwindex`); "
|
||||
"rewrite: rewrite the whole file every run. `.json` outputs always rewrite")
|
||||
|
||||
|
||||
@register_node
|
||||
class SinkJsonl(NodeType):
|
||||
"""Write arriving items to a JSONL (or JSON) file, sorted by key.
|
||||
|
||||
mode `append` (default, JSONL only): the file is an append-only log. A sidecar
|
||||
`<path>.pwindex` records the item ids already written, the file's byte size and a
|
||||
hash of the sink params; each run appends only rows for new items (sorted by key
|
||||
among themselves). Rows of items that no longer reach the sink STAY in the file.
|
||||
If the file is missing, its size differs from the recorded one (edited/truncated)
|
||||
or `fields`/`lineage` changed, the file is rewritten in full and the index rebuilt.
|
||||
mode `rewrite`: the whole file is rewritten every run (old behaviour). `.json`
|
||||
(array) outputs cannot be appended and are always rewritten.
|
||||
Returns {"path", "rows" (total rows in the file), "appended" (rows written this run)}."""
|
||||
|
||||
name = "sink.jsonl"
|
||||
kind = "sink"
|
||||
Params = SinkParams
|
||||
inputs = {"in": Port()}
|
||||
cacheable = False
|
||||
example = {"path": "out/labelled.jsonl", "fields": ["key", "payload.title", "labels"]}
|
||||
|
||||
def _row(self, it) -> dict:
|
||||
p = self.params
|
||||
if p.fields:
|
||||
row = {f: it.get(f) for f in p.fields}
|
||||
else:
|
||||
row = {"id": it.id, "key": it.key, "kind": it.kind, "payload": it.payload, "labels": it.labels,
|
||||
"provenance": it.provenance}
|
||||
if p.lineage:
|
||||
row["parents"] = list(it.parents)
|
||||
row["producer"] = it.producer
|
||||
return row
|
||||
|
||||
async def write(self, items, ctx):
|
||||
p = self.params
|
||||
path = ctx.resolve_path(p.path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
index_path = path.with_name(path.name + ".pwindex")
|
||||
if path.suffix == ".json" or p.mode == "rewrite":
|
||||
rows = [self._row(it) for it in items]
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
if path.suffix == ".json":
|
||||
tmp.write_text(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
|
||||
else:
|
||||
tmp.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
|
||||
tmp.replace(path)
|
||||
if p.mode == "rewrite":
|
||||
index_path.unlink(missing_ok=True) # a later append run must not trust a stale index
|
||||
return {"path": str(path), "rows": len(rows), "appended": len(rows)}
|
||||
|
||||
params_hash = digest({"fields": p.fields, "lineage": p.lineage})
|
||||
index = None
|
||||
try:
|
||||
index = json.loads(index_path.read_text())
|
||||
if (not path.exists() or path.stat().st_size != index.get("size")
|
||||
or index.get("params") != params_hash or not isinstance(index.get("ids"), list)):
|
||||
index = None
|
||||
except (OSError, ValueError):
|
||||
index = None
|
||||
|
||||
if index is None: # full rewrite, identical to rewrite mode
|
||||
rows = [self._row(it) for it in items]
|
||||
data = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows).encode()
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
ids = list(dict.fromkeys(it.id for it in items))
|
||||
total, appended, size = len(rows), len(rows), len(data)
|
||||
else:
|
||||
ids = index["ids"]
|
||||
seen = set(ids)
|
||||
new = []
|
||||
for it in items: # already sorted by key by the engine
|
||||
if it.id not in seen:
|
||||
seen.add(it.id)
|
||||
ids.append(it.id)
|
||||
new.append(it)
|
||||
new.sort(key=lambda i: (i.key, i.id))
|
||||
data = "".join(json.dumps(self._row(it), ensure_ascii=False) + "\n" for it in new).encode()
|
||||
if data:
|
||||
with path.open("ab") as f:
|
||||
f.write(data)
|
||||
f.flush()
|
||||
appended = len(new)
|
||||
total = int(index.get("rows", 0)) + appended
|
||||
size = index["size"] + len(data)
|
||||
tmp = index_path.with_name(index_path.name + ".tmp")
|
||||
tmp.write_text(json.dumps({"version": 1, "params": params_hash, "size": size, "rows": total, "ids": ids}))
|
||||
tmp.replace(index_path)
|
||||
return {"path": str(path), "rows": total, "appended": appended}
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Sources over stored results: reuse any node's outputs as seeds for new work.
|
||||
|
||||
- `store.query`: select items from this (or another project's) store by graph, node,
|
||||
port, run, kind, provenance, labels, an expression and lineage.
|
||||
- `graph.import`: the virtual source behind cross-graph edges (`alias:node.port`
|
||||
inputs; see `pipewright.imports`). Not usually written by hand.
|
||||
|
||||
Both emit the stored items unchanged (same ids), so downstream results computed for
|
||||
them before are memoized: re-running only processes items that are new upstream.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from ..errors import ConfigError
|
||||
from ..registry import register_node
|
||||
from ..store import Store
|
||||
from .base import ANY, NodeType, Port
|
||||
from .builtin import _check_exprs
|
||||
|
||||
|
||||
class P(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
def _open_other(ctx, store: str | None) -> Store | None:
|
||||
"""None for this project's store; else a Store on `store` (a store dir, a project
|
||||
file, or a directory containing pipewright.yaml)."""
|
||||
if not store:
|
||||
return None
|
||||
path = ctx.resolve_path(store)
|
||||
if path.is_file() or (path / "pipewright.yaml").exists():
|
||||
from ..project import Project
|
||||
|
||||
proj = Project.load(path if path.is_file() else path / "pipewright.yaml")
|
||||
path = proj.store_dir
|
||||
if path.resolve() == Path(ctx.store.root).resolve():
|
||||
return None
|
||||
if not (path / "index.sqlite").exists():
|
||||
raise ConfigError(f"no pipewright store at {path}")
|
||||
return Store(path)
|
||||
|
||||
|
||||
def query_and_copy(ctx, store: str | None, **q) -> list:
|
||||
other = _open_other(ctx, store)
|
||||
src = other or ctx.store
|
||||
try:
|
||||
items = src.query(exclude_run=ctx.run_id, **q)
|
||||
if other is not None:
|
||||
ctx.store.copy_from(other, [i.id for i in items]) # local lineage + blobs
|
||||
return items
|
||||
finally:
|
||||
if other is not None:
|
||||
other.close()
|
||||
|
||||
|
||||
class StoreQueryParams(P):
|
||||
graph: str | None = Field(None, description="graph name whose runs to read (default: this graph)")
|
||||
node: str | None = Field(None, description="node whose outputs to select (default: every item those runs "
|
||||
"stored)")
|
||||
port: str | None = Field(None, description="output port (default: all ports of the node)")
|
||||
run: str = Field("latest", description="latest | previous | all | <run id or prefix>; the current run is "
|
||||
"never read")
|
||||
store: str | None = Field(None, description="another project's store dir or project file (default: this one); "
|
||||
"selected items are copied here with their lineage")
|
||||
kind: str | None = Field(None, description="keep only items of this kind; also the declared output kind")
|
||||
provenance: Literal["real", "derived", "synthetic"] | None = None
|
||||
labels: dict[str, object] = Field(default_factory=dict, description="label equality filters")
|
||||
where: str | None = Field(None, description="expression over each item, e.g. labels.pass_rate >= 0.75")
|
||||
derived_from: str | None = Field(None, description="keep only descendants of this item (id, prefix or key)")
|
||||
limit: int | None = Field(None, ge=1)
|
||||
|
||||
|
||||
@register_node
|
||||
class StoreQuery(NodeType):
|
||||
"""Select earlier results as seeds for new work: items that flowed out of a node
|
||||
(and port) in a previous run of this or another graph (or another project's store),
|
||||
filtered by labels, provenance, an expression and lineage. Examples: validated tasks
|
||||
whose pass rate is at least 0.75; items routed to `too_easy` in run X; failures
|
||||
audited in the previous run, fed back to a generator (re-entrant loop without a
|
||||
live cycle). Items keep their ids, so downstream work on them stays memoized."""
|
||||
|
||||
name = "store.query"
|
||||
kind = "source"
|
||||
Params = StoreQueryParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
cacheable = False
|
||||
example = {"graph": "coding-tasks", "node": "bucket", "port": "too_easy", "run": "latest",
|
||||
"where": "labels.pass_rate >= 0.75", "kind": "task_result"}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
return {"out": Port(kind=(params.kind if params and params.kind else ANY))}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs([params.where]) if params.where else []
|
||||
|
||||
async def generate(self, ctx):
|
||||
p = self.params
|
||||
items = query_and_copy(ctx, p.store, graph=p.graph or ctx.engine.spec.name, node=p.node, port=p.port,
|
||||
run=p.run, kind=p.kind, provenance=p.provenance, labels=p.labels or None,
|
||||
where=p.where, derived_from=p.derived_from, limit=p.limit)
|
||||
for it in items:
|
||||
yield it
|
||||
|
||||
|
||||
class GraphImportParams(P):
|
||||
graph: str
|
||||
node: str
|
||||
ports: dict[str, str] = Field(description="port -> item kind")
|
||||
run: str = "latest"
|
||||
store: str | None = None
|
||||
where: str | None = None
|
||||
alias: str = ""
|
||||
source: str = ""
|
||||
|
||||
|
||||
@register_node
|
||||
class GraphImport(NodeType):
|
||||
"""Outputs of another graph's node (a cross-graph edge). Generated from a graph's
|
||||
`imports:` for every `alias:node.port` input; one output port per referenced port."""
|
||||
|
||||
name = "graph.import"
|
||||
kind = "source"
|
||||
Params = GraphImportParams
|
||||
outputs = {"out": Port(kind=ANY)}
|
||||
cacheable = False
|
||||
example = {"graph": "build", "node": "bucket", "ports": {"too_easy": "task_result"}}
|
||||
|
||||
@classmethod
|
||||
def output_ports(cls, params):
|
||||
if params is None:
|
||||
return dict(cls.outputs)
|
||||
return {p: Port(kind=k) for p, k in params.ports.items()}
|
||||
|
||||
@classmethod
|
||||
def validate_params(cls, params) -> list[str]:
|
||||
return _check_exprs([params.where]) if params.where else []
|
||||
|
||||
async def generate(self, ctx):
|
||||
p = self.params
|
||||
for port in sorted(p.ports):
|
||||
for it in query_and_copy(ctx, p.store, graph=p.graph, node=p.node, port=port, run=p.run,
|
||||
where=p.where):
|
||||
yield port, it
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Every CLI operation as a plain function returning JSON-able data.
|
||||
|
||||
The CLI (`pw ...`) and the MCP server are thin layers over these, so an agent gets
|
||||
the same results whichever way it drives pipewright.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from .check import check
|
||||
from .errors import ConfigError
|
||||
from .graph import GraphSpec, graph_to_data, load_graph, save_graph
|
||||
from .items import Item
|
||||
from .project import Project
|
||||
from .registry import registry
|
||||
from .store import Store
|
||||
|
||||
|
||||
def load(graph: str | Path, project: str | Path | None = None) -> tuple[GraphSpec, Project]:
|
||||
spec = load_graph(graph)
|
||||
proj = Project.discover(Path(graph).resolve().parent, project)
|
||||
registry.import_plugins(spec.plugins)
|
||||
return spec, proj
|
||||
|
||||
|
||||
def open_store(proj: Project) -> Store:
|
||||
return Store(proj.store_dir)
|
||||
|
||||
|
||||
def _run_or_latest(store: Store, spec: GraphSpec, run_id: str | None) -> dict:
|
||||
run = store.run(run_id) if run_id else store.latest_run(spec.name)
|
||||
if run is None:
|
||||
raise ConfigError(f"no runs of graph {spec.name!r} yet" if not run_id else f"no run {run_id!r}")
|
||||
return run
|
||||
|
||||
|
||||
def item_view(item: Item, max_str: int | None = 400) -> dict:
|
||||
def clip(v: Any) -> Any:
|
||||
if max_str is None:
|
||||
return v
|
||||
if isinstance(v, str) and len(v) > max_str:
|
||||
return v[:max_str] + f"... [{len(v) - max_str} more chars]"
|
||||
if isinstance(v, dict):
|
||||
return {k: clip(x) for k, x in v.items()}
|
||||
if isinstance(v, list):
|
||||
return [clip(x) for x in v[:50]] + ([f"... {len(v) - 50} more"] if len(v) > 50 else [])
|
||||
return v
|
||||
|
||||
return {"id": item.id, "key": item.key, "kind": item.kind, "provenance": item.provenance,
|
||||
"producer": item.producer, "op": item.op, "parents": list(item.parents),
|
||||
"payload": clip(item.payload), "labels": clip(item.labels),
|
||||
"artifacts": {k: v.model_dump() for k, v in item.artifacts.items()}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- node docs
|
||||
def nodes_list() -> list[dict]:
|
||||
out = []
|
||||
for name in registry.node_types.names():
|
||||
cls = registry.node_types[name]
|
||||
para = " ".join((cls.description or cls.__doc__ or "").strip().split("\n\n")[0].split())
|
||||
out.append({"type": name, "kind": cls.kind, "summary": para.split(". ")[0].rstrip(".") + "."})
|
||||
return out
|
||||
|
||||
|
||||
def nodes_describe(type_name: str) -> dict:
|
||||
cls = registry.node_types.get(type_name)
|
||||
if cls is None:
|
||||
import difflib
|
||||
|
||||
m = difflib.get_close_matches(type_name, registry.node_types.names(), n=3)
|
||||
raise ConfigError(f"unknown node type {type_name!r}" + (f"; did you mean {m}?" if m else ""))
|
||||
d = cls.describe()
|
||||
import yaml
|
||||
|
||||
d["example_yaml"] = yaml.safe_dump({"my_node": {"type": type_name, **({"inputs": {"in": "upstream"}}
|
||||
if cls.kind != "source" else {}),
|
||||
"params": cls.example}}, sort_keys=False)
|
||||
kw = ", ".join(f"{k}={v!r}" for k, v in cls.example.items())
|
||||
d["example_python"] = (f"g.add('my_node', {type_name!r}, "
|
||||
+ ("input=upstream, " if cls.kind != "source" else "") + kw + ")")
|
||||
return d
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- check / patch
|
||||
def check_graph(graph: str | Path, project: str | Path | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
diags = check(spec, proj)
|
||||
return {"ok": not any(d.level == "error" for d in diags), "graph": spec.name,
|
||||
"errors": sum(d.level == "error" for d in diags), "warnings": sum(d.level == "warning" for d in diags),
|
||||
"diagnostics": [d.to_dict() for d in diags]}
|
||||
|
||||
|
||||
def patch_graph(graph: str | Path, ops: list[dict], *, dry_run: bool = False, force: bool = False,
|
||||
project: str | Path | None = None, out: str | Path | None = None) -> dict:
|
||||
from .patch import apply_ops
|
||||
|
||||
spec, proj = load(graph, project)
|
||||
new = apply_ops(spec, ops)
|
||||
diags = check(new, proj)
|
||||
errors = [d for d in diags if d.level == "error"]
|
||||
target = Path(out or graph)
|
||||
written = False
|
||||
if not dry_run and (not errors or force):
|
||||
if target.suffix == ".py":
|
||||
raise ConfigError("cannot write a .py graph; give --out graph.yaml (or edit the Python builder)")
|
||||
save_graph(new, target)
|
||||
written = True
|
||||
return {"ok": not errors, "written": written, "path": str(target), "ops": len(ops),
|
||||
"diagnostics": [d.to_dict() for d in diags],
|
||||
**({"graph": graph_to_data(new)} if dry_run else {})}
|
||||
|
||||
|
||||
def export_graph(graph: str | Path, out: str | Path) -> dict:
|
||||
spec = load_graph(graph)
|
||||
save_graph(spec, out)
|
||||
return {"written": str(out), "nodes": len(spec.nodes)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- running
|
||||
def run_graph(graph: str | Path, *, project: str | Path | None = None, upto: str | None = None,
|
||||
limit: int | None = None, mode: str = "run", force: list[str] | None = None,
|
||||
retry_errors: bool = False, run_id: str | None = None,
|
||||
on_log: Callable[[str], None] | None = None, shard: tuple[int, int] | str | None = None,
|
||||
group: str | None = None) -> dict:
|
||||
return asyncio.run(run_graph_async(graph, project=project, upto=upto, limit=limit, mode=mode, force=force,
|
||||
retry_errors=retry_errors, run_id=run_id, on_log=on_log, shard=shard,
|
||||
group=group))
|
||||
|
||||
|
||||
def parse_shard(shard: tuple[int, int] | str | None) -> tuple[int, int] | None:
|
||||
if shard is None or isinstance(shard, tuple):
|
||||
return shard
|
||||
i, _, n = str(shard).partition("/")
|
||||
try:
|
||||
idx, cnt = int(i), int(n)
|
||||
except ValueError:
|
||||
raise ConfigError(f"--shard must look like I/N (e.g. 0/4), got {shard!r}") from None
|
||||
if not 0 <= idx < cnt:
|
||||
raise ConfigError(f"--shard {shard}: need 0 <= I < N")
|
||||
return idx, cnt
|
||||
|
||||
|
||||
async def run_graph_async(graph, *, project=None, upto=None, limit=None, mode="run", force=None,
|
||||
retry_errors=False, run_id=None, on_log=None, shard=None, group=None) -> dict:
|
||||
from .engine import Engine, RunOptions
|
||||
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
engine = Engine(spec, proj, store, on_log=on_log)
|
||||
return await engine.run(RunOptions(upto=upto, limit=limit, mode=mode, run_id=run_id,
|
||||
force=set(force or []), retry_errors=retry_errors,
|
||||
shard=parse_shard(shard), group=group))
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def preview(graph: str | Path, *, upto: str | None = None, n: int = 5, project: str | Path | None = None,
|
||||
on_log: Callable[[str], None] | None = None) -> dict:
|
||||
"""Run on the first n source items up to `upto` and show what came out of it."""
|
||||
spec, _ = load(graph, project)
|
||||
target = upto or spec.topo_order()[-1]
|
||||
summary = run_graph(graph, project=project, upto=target, limit=n, mode="preview", on_log=on_log)
|
||||
res = 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"]}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- inspection
|
||||
def expanded(spec: GraphSpec, proj: Project | None = None) -> GraphSpec:
|
||||
"""The spec with cross-graph imports as `graph.import` nodes (for funnels/reports)."""
|
||||
from .imports import expand_imports
|
||||
|
||||
try:
|
||||
return expand_imports(spec, proj or Project.discover(spec.base_dir), strict=False)
|
||||
except ConfigError:
|
||||
return spec
|
||||
|
||||
|
||||
def funnel_for_run(spec: GraphSpec, store: Store, run_id: str | list[str]) -> dict:
|
||||
"""Counts per node/port/edge for one run, or summed over several (e.g. the shards of a group)."""
|
||||
spec = expanded(spec)
|
||||
run_ids = [run_id] if isinstance(run_id, str) else list(run_id)
|
||||
counts: dict[tuple[str, str], int] = {}
|
||||
events: dict[str, dict[str, int]] = {}
|
||||
for rid in run_ids:
|
||||
for k, v in store.flow_counts(rid).items():
|
||||
counts[k] = counts.get(k, 0) + v
|
||||
for node, d in store.event_counts(rid).items():
|
||||
agg = events.setdefault(node, {})
|
||||
for k, v in d.items():
|
||||
agg[k] = agg.get(k, 0) + v
|
||||
node_results: dict[str, dict] = {}
|
||||
if len(run_ids) == 1:
|
||||
node_results = ((store.run(run_ids[0]) or {}).get("stats") or {}).get("nodes") or {}
|
||||
edges = []
|
||||
for src, sport, dst, dport in spec.edges():
|
||||
edges.append({"from": f"{src}.{sport}", "to": f"{dst}.{dport}", "items": counts.get((src, sport), 0)})
|
||||
nodes = {}
|
||||
for nid in spec.nodes:
|
||||
outs = {p: n for (node, p), n in counts.items() if node == nid and not p.startswith("__")}
|
||||
parked = counts.get((nid, "__parked__"), 0)
|
||||
ev = events.get(nid, {})
|
||||
nodes[nid] = {"type": spec.nodes[nid].type, "out": outs, "events": ev,
|
||||
**({"parked": parked} if parked else {})}
|
||||
res = node_results.get(nid, {}).get("result")
|
||||
if res is not None:
|
||||
nodes[nid]["result"] = res # e.g. a sink's {path, rows, appended, ...}
|
||||
if spec.nodes[nid].type == "graph.import":
|
||||
prm = spec.nodes[nid].params
|
||||
nodes[nid]["imported_from"] = {"graph": prm.get("graph"), "node": prm.get("node"),
|
||||
"run": prm.get("run"), "source": prm.get("source")}
|
||||
return {"run_id": run_id if isinstance(run_id, str) else ",".join(run_ids), "nodes": nodes, "edges": edges}
|
||||
|
||||
|
||||
def funnel(graph: str | Path, run_id: str | None = None, project: str | Path | None = None,
|
||||
group: str | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
if group:
|
||||
rids = store.group_runs(group, spec.name)
|
||||
if not rids:
|
||||
raise ConfigError(f"no runs in group {group!r}")
|
||||
return {**funnel_for_run(spec, store, rids), "group": group, "runs": rids}
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
return funnel_for_run(spec, store, run["run_id"])
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def status(graph: str | Path, run_id: str | None = None, project: str | Path | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
runs = store.runs(spec.name, limit=10)
|
||||
if not runs:
|
||||
return {"graph": spec.name, "runs": [], "message": "no runs yet; try `pw preview` or `pw run`"}
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
return {"graph": spec.name, "run": {k: v for k, v in run.items() if k != "spec"},
|
||||
"usage": store.usage_summary(run["run_id"]), "errors": store.errors(run["run_id"], limit=20),
|
||||
"recent_runs": [{k: r[k] for k in ("run_id", "mode", "status", "started", "finished")} for r in runs]}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def items(graph: str | Path, node: str, *, port: str | None = None, n: int = 10, sample: bool = False,
|
||||
run_id: str | None = None, errors: bool = False, full: bool = False,
|
||||
project: str | Path | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
if node not in spec.nodes:
|
||||
raise ConfigError(f"no node {node!r}; nodes: {sorted(spec.nodes)}")
|
||||
store = open_store(proj)
|
||||
try:
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
if errors:
|
||||
errs = store.errors(run["run_id"], node, limit=n)
|
||||
for e in errs:
|
||||
it = store.get_item(e["input"])
|
||||
if it is not None:
|
||||
e["item"] = item_view(it, None if full else 300)
|
||||
return {"run_id": run["run_id"], "node": node, "errors": errs}
|
||||
ids = store.flow_items(run["run_id"], node, port, limit=n, sample=sample)
|
||||
total = len(store.flow_items(run["run_id"], node, port))
|
||||
out = []
|
||||
for i in ids:
|
||||
it = store.get_item(i)
|
||||
if it is not None:
|
||||
v = item_view(it, None if full else 400)
|
||||
out.append(v)
|
||||
return {"run_id": run["run_id"], "node": node, "port": port, "total": total, "items": out}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def lineage(graph: str | Path, item_id: str, project: str | Path | None = None, *, descendants: bool = False,
|
||||
roots: bool = False, limit: int = 200) -> dict:
|
||||
"""An item (id, unique prefix or key) and its ancestors — across graphs that share the
|
||||
store (cross-graph imports keep item ids) — annotated with the graph/run that made each.
|
||||
`descendants`: every item derived from it (all variants); `roots`: only the root sources."""
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
full = store.resolve_item(item_id)
|
||||
if full is None:
|
||||
raise ConfigError(f"no item matching {item_id!r} (id, unique id prefix or key)")
|
||||
|
||||
def view(i: Item) -> dict:
|
||||
return {**item_view(i, 200), "origin": store.item_origin(i.id)}
|
||||
|
||||
out: dict[str, Any] = {"item": full}
|
||||
if roots:
|
||||
out["roots"] = [view(i) for i in store.roots(full)]
|
||||
else:
|
||||
out["lineage"] = [view(i) for i in store.lineage(full)][:limit]
|
||||
out["children"] = store.children(full)
|
||||
if descendants:
|
||||
ids = store.descendants(full, limit=limit)
|
||||
out["descendants"] = [view(i) for i in store.get_items(ids)]
|
||||
return out
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def query(graph: str | Path, *, 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, full: bool = False, project: str | Path | None = None) -> dict:
|
||||
"""Select stored results (the same selection a `store.query` node makes)."""
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
g = of_graph or spec.name
|
||||
runs_sel = store.select_runs(g, run)
|
||||
res = store.query(graph=g, node=node, port=port, run=run, where=where, labels=labels, kind=kind,
|
||||
provenance=provenance, derived_from=derived_from)
|
||||
return {"graph": g, "runs": runs_sel, "node": node, "port": port, "total": len(res),
|
||||
"items": [item_view(i, None if full else 300) for i in res[:n]],
|
||||
"as_node": {"type": "store.query", "params": {k: v for k, v in {
|
||||
"graph": g, "node": node, "port": port, "run": run, "where": where, "labels": labels,
|
||||
"kind": kind, "provenance": provenance, "derived_from": derived_from}.items() if v}}}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def export(graph: str | Path, node: str, out: str | Path, *, port: str | None = None, run_id: str | None = None,
|
||||
fields: list[str] | None = None, project: str | Path | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
ids = store.flow_items(run["run_id"], node, port)
|
||||
rows = []
|
||||
for it in store.get_items(ids):
|
||||
rows.append({f: it.get(f) for f in fields} if fields else item_view(it, None))
|
||||
out = Path(out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
if out.suffix == ".json":
|
||||
out.write_text(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
|
||||
else:
|
||||
out.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
|
||||
return {"run_id": run["run_id"], "node": node, "port": port, "rows": len(rows), "path": str(out)}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def report(graph: str | Path, out: str | Path | None = None, run_id: str | None = None,
|
||||
project: str | Path | None = None, refresh: int | None = None) -> dict:
|
||||
from .report import render_report
|
||||
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
html = render_report(spec, store, run, refresh=refresh)
|
||||
out = Path(out or proj.store_dir / "reports" / f"{spec.name}-{run['run_id']}.html")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(html)
|
||||
return {"run_id": run["run_id"], "path": str(out)}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def review_list(graph: str | Path, node: str, run_id: str | None = None, project: str | Path | None = None) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
run = _run_or_latest(store, spec, run_id)
|
||||
ids = store.flow_items(run["run_id"], node, "__parked__")
|
||||
params = spec.nodes[node].params
|
||||
return {"run_id": run["run_id"], "node": node, "instructions": params.get("instructions", ""),
|
||||
"parked": [item_view(i) for i in store.get_items(ids)]}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def review_decide(graph: str | Path, node: str, item_ids: list[str], decision: str, note: str = "",
|
||||
project: str | Path | None = None) -> dict:
|
||||
if decision not in ("approved", "rejected"):
|
||||
raise ConfigError("decision must be approved or rejected")
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
done = []
|
||||
for i in item_ids:
|
||||
full = i if store.get_item(i) else (store.find_items(i) or [None])[0]
|
||||
if full is None:
|
||||
raise ConfigError(f"no item {i!r}")
|
||||
store.set_review(node, full, decision, note)
|
||||
done.append(full)
|
||||
return {"node": node, "decision": decision, "items": done,
|
||||
"next": "re-run the graph (`pw run`) to move decided items on"}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def runs(graph: str | Path, project: str | Path | None = None, limit: int = 20) -> dict:
|
||||
spec, proj = load(graph, project)
|
||||
store = open_store(proj)
|
||||
try:
|
||||
return {"graph": spec.name, "runs": [{k: r[k] for k in ("run_id", "mode", "status", "started", "finished")}
|
||||
for r in store.runs(spec.name, limit)]}
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
async def serve_proxy(alias: str, *, project: str | Path | None = None, host: str = "127.0.0.1", port: int = 0,
|
||||
log_dir: str | Path | None = None, on_ready: Callable[[dict], None] | None = None) -> None:
|
||||
"""Standalone logging proxy for running an external agent by hand: it gets a base URL
|
||||
and a session token; calls go through the alias's provider (pacing, quirks, retries,
|
||||
request cache, accounting) and every turn is appended to <log_dir>/<conversation>.jsonl."""
|
||||
import time as _time
|
||||
|
||||
from .models.base import ModelClient
|
||||
from .models.proxy import LoggingProxy
|
||||
|
||||
proj = Project.discover(Path.cwd(), project)
|
||||
cfg = proj.config.models.get(alias)
|
||||
if cfg is None:
|
||||
raise ConfigError(f"unknown model alias {alias!r}; configured: {sorted(proj.config.models)}")
|
||||
store = open_store(proj)
|
||||
run_id = f"proxy-{_time.strftime('%Y%m%d-%H%M%S')}"
|
||||
store.begin_run(run_id, f"proxy:{alias}", "", "proxy", {})
|
||||
|
||||
def on_usage(a, prov, model, usage, cached):
|
||||
store.record_usage(run_id, "proxy", None, a, prov, model, usage.input_tokens, usage.output_tokens,
|
||||
usage.cost_usd, cached)
|
||||
|
||||
client = ModelClient(alias, cfg.model_copy(update={"cache": False}), proj.provider(cfg.provider), store=store,
|
||||
on_usage=on_usage)
|
||||
proxy = LoggingProxy()
|
||||
bound = await proxy.listen(host, port)
|
||||
session = proxy.open_session(client, Path(log_dir) if log_dir else None)
|
||||
info = {"base_url": f"http://{host}:{bound}/v1", "api_key": session.token, "model": cfg.model, "run_id": run_id,
|
||||
"log_dir": str(log_dir) if log_dir else None}
|
||||
if on_ready:
|
||||
on_ready(info)
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
await proxy.aclose()
|
||||
await proj.aclose()
|
||||
store.update_run(run_id, status="completed", finished=True)
|
||||
store.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- host pools
|
||||
def hosts(action: str, *, pool: str | None = None, count: int = 1, project: str | Path | None = None,
|
||||
start: str | Path = ".") -> dict:
|
||||
"""Host pools outside a run: `list` (recorded hosts + the provider's view), `up`
|
||||
(create hosts and keep them; later runs adopt them when the pool has `persist: true`),
|
||||
`down` (delete recorded hosts), `orphans` (delete provider hosts of this pool that no
|
||||
state file records, e.g. after a crash)."""
|
||||
proj = Project.discover(Path(start), project)
|
||||
names = [pool] if pool else sorted(proj.config.hosts)
|
||||
if pool and pool not in proj.config.hosts:
|
||||
raise ConfigError(f"unknown host pool {pool!r}; configured: {sorted(proj.config.hosts)}")
|
||||
return asyncio.run(_hosts(proj, action, names, count))
|
||||
|
||||
|
||||
async def _hosts(proj: Project, action: str, names: list[str], count: int) -> dict:
|
||||
from .hosts.base import Host
|
||||
|
||||
out: dict[str, Any] = {"action": action, "hosts": [], "remote": [], "created": [], "deleted": [], "errors": []}
|
||||
for name in names:
|
||||
hp = proj.host_pool(name)
|
||||
try:
|
||||
if action == "up":
|
||||
hp.persist = True
|
||||
out["errors"] += await hp.scale_to(count)
|
||||
out["created"] += [h.id for h in hp.hosts.values()]
|
||||
await hp.drain()
|
||||
recorded = {hid: Host.from_dict(d) for hid, d in hp._load().items()}
|
||||
if action == "down":
|
||||
for hid, h in recorded.items():
|
||||
try:
|
||||
await hp.provider.delete(h)
|
||||
out["deleted"].append(hid)
|
||||
except Exception as e:
|
||||
out["errors"].append(f"{hid}: {type(e).__name__}: {e}")
|
||||
hp.hosts = {}
|
||||
hp._save()
|
||||
recorded = {}
|
||||
remote = await hp.provider.list_remote()
|
||||
if action == "orphans":
|
||||
known = {h.meta.get("vm_id") for h in recorded.values()}
|
||||
for r in remote:
|
||||
if r.get("id") not in known:
|
||||
try:
|
||||
await hp.provider.delete_remote(r)
|
||||
out["deleted"].append(r.get("id"))
|
||||
except Exception as e:
|
||||
out["errors"].append(f"{r.get('id')}: {type(e).__name__}: {e}")
|
||||
remote = await hp.provider.list_remote()
|
||||
out["hosts"] += [h.view() for h in recorded.values()]
|
||||
out["remote"] += [{"pool": name, **r} for r in remote]
|
||||
finally:
|
||||
await hp.provider.aclose()
|
||||
return out
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Schema-validated graph patches (`pw patch <graph> <ops.json>`).
|
||||
|
||||
A patch is a JSON list of operations applied in order to an in-memory copy of the
|
||||
graph; the result is checked, and the file is only written if there are no errors
|
||||
(unless forced). `pw patch --schema` prints the JSON schema of the operations.
|
||||
|
||||
[
|
||||
{"op": "add_node", "id": "summary", "type": "llm.generate",
|
||||
"params": {"model": "labeler", "prompt": "Summarize: {{ payload.body }}", "output_field": "summary"},
|
||||
"inputs": {"in": "labels"}},
|
||||
{"op": "connect", "from": "summary", "to": "export.in"},
|
||||
{"op": "set_param", "node": "route", "path": "routes.urgent", "value": "labels.severity >= 2"},
|
||||
{"op": "remove_node", "id": "old_filter", "rewire": true}
|
||||
]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated, Any, Literal, Union
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
|
||||
|
||||
from .errors import ConfigError
|
||||
from .graph import GraphSpec, NodeSpec, RetryPolicy, split_ref
|
||||
|
||||
|
||||
class _Op(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
||||
|
||||
|
||||
class AddNode(_Op):
|
||||
op: Literal["add_node"]
|
||||
id: str
|
||||
type: str
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
inputs: dict[str, str | list[str]] = Field(default_factory=dict)
|
||||
timeout: float | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class RemoveNode(_Op):
|
||||
op: Literal["remove_node"]
|
||||
id: str
|
||||
rewire: bool = Field(False, description="connect the node's `in` sources to its consumers")
|
||||
|
||||
|
||||
class RenameNode(_Op):
|
||||
op: Literal["rename_node"]
|
||||
id: str
|
||||
new_id: str
|
||||
|
||||
|
||||
class Connect(_Op):
|
||||
op: Literal["connect"]
|
||||
from_: str = Field(alias="from", description="`node` or `node.port`")
|
||||
to: str = Field(description="`node.port` (default port `in`)")
|
||||
|
||||
|
||||
class Disconnect(_Op):
|
||||
op: Literal["disconnect"]
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
|
||||
|
||||
class SetParam(_Op):
|
||||
op: Literal["set_param"]
|
||||
node: str
|
||||
path: str = Field(description="dotted path inside params, e.g. `routes.urgent`")
|
||||
value: Any = None
|
||||
unset: bool = False
|
||||
|
||||
|
||||
class SetNode(_Op):
|
||||
op: Literal["set_node"]
|
||||
node: str
|
||||
type: str | None = None
|
||||
timeout: float | None = None
|
||||
retries: RetryPolicy | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
Op = Annotated[Union[AddNode, RemoveNode, RenameNode, Connect, Disconnect, SetParam, SetNode],
|
||||
Field(discriminator="op")]
|
||||
OPS = TypeAdapter(list[Op])
|
||||
|
||||
|
||||
class PatchError(ConfigError):
|
||||
pass
|
||||
|
||||
|
||||
def ops_schema() -> dict:
|
||||
return OPS.json_schema(by_alias=True)
|
||||
|
||||
|
||||
def _to_port(ref: str, default: str = "in") -> tuple[str, str]:
|
||||
node, _, port = ref.partition(".")
|
||||
return node, port or default
|
||||
|
||||
|
||||
def apply_ops(spec: GraphSpec, raw_ops: list[dict]) -> GraphSpec:
|
||||
try:
|
||||
ops = OPS.validate_python(raw_ops)
|
||||
except Exception as e:
|
||||
raise PatchError(f"invalid patch: {e}") from e
|
||||
g = spec.model_copy(deep=True)
|
||||
for i, op in enumerate(ops):
|
||||
where = f"op {i} ({op.op})"
|
||||
if isinstance(op, AddNode):
|
||||
if op.id in g.nodes:
|
||||
raise PatchError(f"{where}: node {op.id!r} already exists")
|
||||
g.nodes[op.id] = NodeSpec(type=op.type, params=op.params, inputs=op.inputs, timeout=op.timeout,
|
||||
description=op.description)
|
||||
elif isinstance(op, RemoveNode):
|
||||
if op.id not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {op.id!r}")
|
||||
removed = g.nodes.pop(op.id)
|
||||
feeds = removed.inputs.get("in", [])
|
||||
for n in g.nodes.values():
|
||||
for port, refs in list(n.inputs.items()):
|
||||
kept = [r for r in refs if split_ref(r)[0] != op.id]
|
||||
if op.rewire and len(kept) != len(refs):
|
||||
kept += [f for f in feeds if f not in kept]
|
||||
if kept:
|
||||
n.inputs[port] = kept
|
||||
else:
|
||||
del n.inputs[port]
|
||||
elif isinstance(op, RenameNode):
|
||||
if op.id not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {op.id!r}")
|
||||
if op.new_id in g.nodes:
|
||||
raise PatchError(f"{where}: node {op.new_id!r} already exists")
|
||||
g.nodes = {(op.new_id if k == op.id else k): v for k, v in g.nodes.items()}
|
||||
for n in g.nodes.values():
|
||||
for port, refs in n.inputs.items():
|
||||
n.inputs[port] = [f"{op.new_id}.{split_ref(r)[1]}" if split_ref(r)[0] == op.id else r
|
||||
for r in refs]
|
||||
elif isinstance(op, (Connect, Disconnect)):
|
||||
src, sport = split_ref(op.from_)
|
||||
dst, dport = _to_port(op.to)
|
||||
if dst not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {dst!r}")
|
||||
ref = f"{src}.{sport}"
|
||||
refs = [f"{split_ref(r)[0]}.{split_ref(r)[1]}" for r in g.nodes[dst].inputs.get(dport, [])]
|
||||
if isinstance(op, Connect):
|
||||
if src not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {src!r}")
|
||||
if ref not in refs:
|
||||
refs.append(ref)
|
||||
else:
|
||||
if ref not in refs:
|
||||
raise PatchError(f"{where}: {ref} is not connected to {dst}.{dport}")
|
||||
refs.remove(ref)
|
||||
if refs:
|
||||
g.nodes[dst].inputs[dport] = refs
|
||||
else:
|
||||
g.nodes[dst].inputs.pop(dport, None)
|
||||
elif isinstance(op, SetParam):
|
||||
if op.node not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {op.node!r}")
|
||||
cur: Any = g.nodes[op.node].params
|
||||
parts = op.path.split(".")
|
||||
for part in parts[:-1]:
|
||||
if isinstance(cur, list) and part.isdigit():
|
||||
cur = cur[int(part)]
|
||||
else:
|
||||
cur = cur.setdefault(part, {})
|
||||
last = parts[-1]
|
||||
if isinstance(cur, list) and last.isdigit():
|
||||
if op.unset:
|
||||
cur.pop(int(last))
|
||||
else:
|
||||
cur[int(last)] = op.value
|
||||
elif op.unset:
|
||||
cur.pop(last, None)
|
||||
else:
|
||||
cur[last] = op.value
|
||||
elif isinstance(op, SetNode):
|
||||
if op.node not in g.nodes:
|
||||
raise PatchError(f"{where}: no node {op.node!r}")
|
||||
n = g.nodes[op.node]
|
||||
for f in ("type", "timeout", "retries", "description"):
|
||||
v = getattr(op, f)
|
||||
if v is not None:
|
||||
setattr(n, f, v)
|
||||
return GraphSpec.model_validate(g.model_dump())
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Project configuration: providers, model aliases, sandboxes, harnesses, budgets.
|
||||
|
||||
Graphs refer to resources by NAME (model alias `labeler`, sandbox pool `docker`,
|
||||
harness `mini`); the project file binds names to concrete things. The same graph runs
|
||||
against the fake provider in tests and a real one in production by swapping the
|
||||
project file (or `--project`).
|
||||
|
||||
# pipewright.yaml
|
||||
store: .pipewright
|
||||
providers:
|
||||
morph:
|
||||
type: openai
|
||||
base_url: https://api.morphllm.com/v1
|
||||
api_key: {file: ~/.tmp, var: MORPH_SK} # or {env: MORPH_SK}; never logged
|
||||
rate: {requests_per_minute: 1000, input_tokens_per_minute: 2000000, output_tokens_per_minute: 76000}
|
||||
quirks: [stream_error_event]
|
||||
models:
|
||||
labeler: {provider: morph, model: morph-dsv41flash-1017, params: {temperature: 0}}
|
||||
sandboxes:
|
||||
docker: {type: docker, image: python:3.12-slim, cpus: 1, memory: 1g, network: none}
|
||||
harnesses:
|
||||
mini: {type: builtin, model: labeler, max_turns: 20}
|
||||
budgets: {usd: 5}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .errors import ConfigError
|
||||
from .registry import registry
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .harness.base import Harness
|
||||
from .models.base import ModelProvider
|
||||
from .nodes.base import ResourceRef
|
||||
from .hosts.pool import HostPool
|
||||
from .sandbox.base import SandboxProvider
|
||||
|
||||
# provider settings that do not change what a model answers (excluded from memo keys)
|
||||
NON_SEMANTIC_PROVIDER_KEYS = {"api_key", "rate", "timeout", "headers", "quirks", "stream", "pricing", "latency",
|
||||
"fail", "_transport"}
|
||||
|
||||
PROJECT_FILES = ("pipewright.yaml", "pipewright.yml", "pipewright.json")
|
||||
|
||||
|
||||
class SecretRef(BaseModel):
|
||||
"""Where a secret lives. Values are read at use time and never stored or logged."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
env: str | None = None
|
||||
file: str | None = None
|
||||
var: str | None = Field(None, description="for KEY=VALUE files: the key to read")
|
||||
|
||||
def resolve(self) -> str:
|
||||
if self.env:
|
||||
v = os.environ.get(self.env)
|
||||
if v:
|
||||
return v.strip()
|
||||
if not self.file:
|
||||
raise ConfigError(f"secret: environment variable {self.env} is not set")
|
||||
if self.file:
|
||||
path = Path(self.file).expanduser()
|
||||
if not path.exists():
|
||||
raise ConfigError(f"secret: file {path} does not exist")
|
||||
text = path.read_text()
|
||||
if not self.var:
|
||||
return text.strip()
|
||||
for line in text.splitlines():
|
||||
k, sep, v = line.partition("=")
|
||||
if sep and k.strip().removeprefix("export ").strip() == self.var:
|
||||
return v.strip().strip("'\"")
|
||||
raise ConfigError(f"secret: {self.var} not found in {path}")
|
||||
raise ConfigError("secret: give `env` or `file`")
|
||||
|
||||
def describe(self) -> str:
|
||||
parts = [f"env:{self.env}" if self.env else "", f"file:{self.file}" if self.file else "",
|
||||
f"var:{self.var}" if self.var else ""]
|
||||
return " ".join(p for p in parts if p)
|
||||
|
||||
def available(self) -> bool:
|
||||
try:
|
||||
self.resolve()
|
||||
return True
|
||||
except ConfigError:
|
||||
return False
|
||||
|
||||
|
||||
class ModelAlias(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
provider: str
|
||||
model: str
|
||||
params: dict[str, Any] = Field(default_factory=dict, description="default request params (temperature, ...)")
|
||||
max_retries: int = Field(12, description="per-call retries for 429/5xx/transport inside the client")
|
||||
cache: bool = Field(True, description="use the request cache (identical payload -> stored response)")
|
||||
|
||||
|
||||
class Budgets(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
usd: float | None = None
|
||||
input_tokens: int | None = None
|
||||
output_tokens: int | None = None
|
||||
vm_hours: float | None = None
|
||||
counters: dict[str, float] = Field(default_factory=dict, description="named counter budgets, spent by nodes "
|
||||
"with ctx.count(name), e.g. rollouts.terra: 60")
|
||||
|
||||
|
||||
class ProjectConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
store: str = ".pipewright"
|
||||
plugins: list[str] = Field(default_factory=list)
|
||||
providers: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
||||
models: dict[str, ModelAlias] = Field(default_factory=dict)
|
||||
sandboxes: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
||||
hosts: dict[str, dict[str, Any]] = Field(default_factory=dict,
|
||||
description="host pools (machines that run sandboxes)")
|
||||
harnesses: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
||||
budgets: Budgets = Field(default_factory=Budgets)
|
||||
|
||||
|
||||
class Project:
|
||||
def __init__(self, config: ProjectConfig, base_dir: str | Path, path: Path | None = None):
|
||||
self.config = config
|
||||
self.base_dir = Path(base_dir).resolve()
|
||||
self.path = path
|
||||
self._providers: dict[str, ModelProvider] = {}
|
||||
self._sandboxes: dict[str, SandboxProvider] = {}
|
||||
self._harnesses: dict[str, Harness] = {}
|
||||
self._host_pools: dict[str, HostPool] = {}
|
||||
# project-local modules (plugin packs, fake scripts) import relative to the project dir
|
||||
if str(self.base_dir) not in sys.path:
|
||||
sys.path.append(str(self.base_dir))
|
||||
if config.plugins:
|
||||
registry.import_plugins(config.plugins)
|
||||
|
||||
# ------------------------------------------------------------------ loading
|
||||
@classmethod
|
||||
def load(cls, path: str | Path) -> "Project":
|
||||
path = Path(path)
|
||||
if not path.exists():
|
||||
raise ConfigError(f"project file not found: {path}")
|
||||
data = yaml.safe_load(path.read_text()) or {}
|
||||
try:
|
||||
cfg = ProjectConfig.model_validate(data)
|
||||
except Exception as e:
|
||||
raise ConfigError(f"{path}: invalid project file: {e}") from e
|
||||
return cls(cfg, path.parent, path)
|
||||
|
||||
@classmethod
|
||||
def discover(cls, start: str | Path, explicit: str | Path | None = None) -> "Project":
|
||||
"""`explicit`, else the nearest pipewright.yaml at or above `start`, else defaults."""
|
||||
if explicit:
|
||||
return cls.load(explicit)
|
||||
here = Path(start).resolve()
|
||||
if here.is_file():
|
||||
here = here.parent
|
||||
for d in [here, *here.parents]:
|
||||
for name in PROJECT_FILES:
|
||||
if (d / name).exists():
|
||||
return cls.load(d / name)
|
||||
return cls(ProjectConfig(), here)
|
||||
|
||||
@property
|
||||
def store_dir(self) -> Path:
|
||||
p = Path(self.config.store).expanduser()
|
||||
return p if p.is_absolute() else self.base_dir / p
|
||||
|
||||
def resolve_path(self, p: str | Path) -> Path:
|
||||
p = Path(p).expanduser()
|
||||
return p if p.is_absolute() else self.base_dir / p
|
||||
|
||||
# ------------------------------------------------------------------ resources
|
||||
def has(self, ref: "ResourceRef") -> bool:
|
||||
if ref.type == "model":
|
||||
return ref.name in self.config.models
|
||||
if ref.type == "sandbox":
|
||||
return ref.name in self.config.sandboxes
|
||||
return ref.name in self.config.harnesses
|
||||
|
||||
def names(self, type: str) -> list[str]:
|
||||
return sorted({"model": self.config.models, "sandbox": self.config.sandboxes,
|
||||
"harness": self.config.harnesses}[type])
|
||||
|
||||
def resource_identity(self, ref: "ResourceRef") -> dict:
|
||||
"""What a node's results depend on: the concrete model, image, harness setup.
|
||||
Excludes things that do not change results (secrets, rate limits, slots)."""
|
||||
if ref.type == "model":
|
||||
alias = self.config.models.get(ref.name)
|
||||
if alias is None:
|
||||
return {"missing": ref.name}
|
||||
prov = {k: v for k, v in self.config.providers.get(alias.provider, {}).items()
|
||||
if k not in NON_SEMANTIC_PROVIDER_KEYS}
|
||||
return {"provider": prov, "model": alias.model, "params": alias.params}
|
||||
if ref.type == "sandbox":
|
||||
cfg = dict(self.config.sandboxes.get(ref.name, {}))
|
||||
for k in ("slots", "host", "ssh_options", "ttl_seconds", "hosts", "requires", "prefer", "image_source",
|
||||
"docker", "create_timeout", "cost_per_hour"):
|
||||
cfg.pop(k, None)
|
||||
return cfg
|
||||
cfg = dict(self.config.harnesses.get(ref.name, {}))
|
||||
if "model" in cfg:
|
||||
from .nodes.base import ResourceRef as RR
|
||||
|
||||
cfg["model"] = self.resource_identity(RR(type="model", name=cfg["model"]))
|
||||
return cfg
|
||||
|
||||
def provider(self, name: str) -> "ModelProvider":
|
||||
if name not in self._providers:
|
||||
cfg = self.config.providers.get(name)
|
||||
if cfg is None:
|
||||
raise ConfigError(f"unknown provider {name!r}; configured: {sorted(self.config.providers)}")
|
||||
factory = registry.providers.get(cfg.get("type", ""))
|
||||
if factory is None:
|
||||
raise ConfigError(f"provider {name!r}: unknown type {cfg.get('type')!r}; "
|
||||
f"available: {registry.providers.names()}")
|
||||
self._providers[name] = factory(name, cfg, self)
|
||||
return self._providers[name]
|
||||
|
||||
def sandbox_provider(self, name: str) -> "SandboxProvider":
|
||||
if name not in self._sandboxes:
|
||||
cfg = self.config.sandboxes.get(name)
|
||||
if cfg is None:
|
||||
raise ConfigError(f"unknown sandbox pool {name!r}; configured: {sorted(self.config.sandboxes)}")
|
||||
factory = registry.sandboxes.get(cfg.get("type", ""))
|
||||
if factory is None:
|
||||
raise ConfigError(f"sandbox {name!r}: unknown type {cfg.get('type')!r}; "
|
||||
f"available: {registry.sandboxes.names()}")
|
||||
self._sandboxes[name] = factory(name, cfg, self)
|
||||
return self._sandboxes[name]
|
||||
|
||||
def host_pool(self, name: str) -> "HostPool":
|
||||
"""The host pool `name` (one per project object; shared by every sandbox pool using it)."""
|
||||
if name not in self._host_pools:
|
||||
from .hosts.pool import HostPool
|
||||
|
||||
cfg = self.config.hosts.get(name)
|
||||
if cfg is None:
|
||||
raise ConfigError(f"unknown host pool {name!r}; configured: {sorted(self.config.hosts)}")
|
||||
factory = registry.hosts.get(cfg.get("type", ""))
|
||||
if factory is None:
|
||||
raise ConfigError(f"host pool {name!r}: unknown type {cfg.get('type')!r}; "
|
||||
f"available: {registry.hosts.names()}")
|
||||
self._host_pools[name] = HostPool(name, cfg, factory(name, cfg, self), self)
|
||||
return self._host_pools[name]
|
||||
|
||||
def harness(self, name: str) -> "Harness":
|
||||
if name not in self._harnesses:
|
||||
cfg = self.config.harnesses.get(name)
|
||||
if cfg is None:
|
||||
raise ConfigError(f"unknown harness {name!r}; configured: {sorted(self.config.harnesses)}")
|
||||
factory = registry.harnesses.get(cfg.get("type", ""))
|
||||
if factory is None:
|
||||
raise ConfigError(f"harness {name!r}: unknown type {cfg.get('type')!r}; "
|
||||
f"available: {registry.harnesses.names()}")
|
||||
self._harnesses[name] = factory(name, cfg, self)
|
||||
return self._harnesses[name]
|
||||
|
||||
def config_problems(self) -> list[tuple[str, str]]:
|
||||
"""(where, message) for broken provider/alias/sandbox/harness definitions."""
|
||||
out = []
|
||||
for name, alias in self.config.models.items():
|
||||
if alias.provider not in self.config.providers:
|
||||
out.append((f"models.{name}", f"provider {alias.provider!r} is not defined "
|
||||
f"(providers: {sorted(self.config.providers)})"))
|
||||
for name, cfg in self.config.sandboxes.items():
|
||||
hp = cfg.get("hosts")
|
||||
if hp and hp not in self.config.hosts:
|
||||
out.append((f"sandboxes.{name}.hosts", f"host pool {hp!r} is not defined "
|
||||
f"(hosts: {sorted(self.config.hosts)})"))
|
||||
for name, cfg in self.config.hosts.items():
|
||||
key = cfg.get("api_key")
|
||||
if isinstance(key, dict):
|
||||
try:
|
||||
if not SecretRef.model_validate(key).available():
|
||||
out.append((f"hosts.{name}.api_key", f"secret not available "
|
||||
f"({SecretRef.model_validate(key).describe()})"))
|
||||
except Exception as e:
|
||||
out.append((f"hosts.{name}.api_key", f"invalid secret reference: {e}"))
|
||||
for kind, section, reg in (("provider", self.config.providers, registry.providers),
|
||||
("sandbox", self.config.sandboxes, registry.sandboxes),
|
||||
("host", self.config.hosts, registry.hosts),
|
||||
("harness", self.config.harnesses, registry.harnesses)):
|
||||
for name, cfg in section.items():
|
||||
if cfg.get("type") not in reg:
|
||||
out.append((f"{kind}s.{name}" if kind != "harness" else f"harnesses.{name}",
|
||||
f"unknown type {cfg.get('type')!r}; available: {reg.names()}"))
|
||||
for name, cfg in self.config.harnesses.items():
|
||||
m = cfg.get("model")
|
||||
if m and m not in self.config.models:
|
||||
out.append((f"harnesses.{name}", f"model alias {m!r} is not defined"))
|
||||
for name, cfg in self.config.providers.items():
|
||||
key = cfg.get("api_key")
|
||||
if isinstance(key, dict):
|
||||
try:
|
||||
ref = SecretRef.model_validate(key)
|
||||
except Exception as e:
|
||||
out.append((f"providers.{name}.api_key", f"invalid secret reference: {e}"))
|
||||
continue
|
||||
if not ref.available():
|
||||
out.append((f"providers.{name}.api_key", f"secret not available ({ref.describe()})"))
|
||||
return out
|
||||
|
||||
async def aclose(self) -> None:
|
||||
for p in self._providers.values():
|
||||
await p.aclose()
|
||||
for s in self._sandboxes.values():
|
||||
await s.drain()
|
||||
for hp in self._host_pools.values():
|
||||
await hp.drain()
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Plugin registries.
|
||||
|
||||
Five registries (node types, model providers, harnesses, sandbox providers, host
|
||||
providers), each filled two ways:
|
||||
|
||||
- in-process: `@register_node`, `register_provider("name", factory)`,
|
||||
`register_harness(...)`, `register_sandbox(...)`;
|
||||
- entry points: a distribution declares e.g.
|
||||
|
||||
[project.entry-points."pipewright.nodes"]
|
||||
mypack = "mypack.nodes" # a module whose import registers node types
|
||||
|
||||
(groups: pipewright.nodes, pipewright.providers, pipewright.harnesses,
|
||||
pipewright.sandboxes, pipewright.hosts). An entry point may name a module (imported for its
|
||||
side effects) or an object: a NodeType subclass, or a factory callable for the other
|
||||
registries (registered under the entry point's name).
|
||||
|
||||
Graphs and project files can also list `plugins: [module, ...]` to import local packs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
from importlib.metadata import entry_points
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
GROUPS = {
|
||||
"node_types": "pipewright.nodes",
|
||||
"providers": "pipewright.providers",
|
||||
"harnesses": "pipewright.harnesses",
|
||||
"sandboxes": "pipewright.sandboxes",
|
||||
"hosts": "pipewright.hosts",
|
||||
}
|
||||
|
||||
BUILTIN_MODULES = [
|
||||
"pipewright.nodes.builtin",
|
||||
"pipewright.nodes.agentic",
|
||||
"pipewright.nodes.query",
|
||||
"pipewright.models.openai_compat",
|
||||
"pipewright.models.fake",
|
||||
"pipewright.harness.builtin_agent",
|
||||
"pipewright.harness.cli",
|
||||
"pipewright.harness.verifiers_adapter",
|
||||
"pipewright.sandbox.local",
|
||||
"pipewright.sandbox.docker",
|
||||
"pipewright.sandbox.fake",
|
||||
"pipewright.hosts.static",
|
||||
]
|
||||
|
||||
|
||||
class _Registry(dict):
|
||||
def __init__(self, owner: "Registries", group: str):
|
||||
super().__init__()
|
||||
self._owner, self.group = owner, group
|
||||
|
||||
def _ensure(self) -> None:
|
||||
self._owner.load()
|
||||
|
||||
def get(self, key, default=None): # type: ignore[override]
|
||||
self._ensure()
|
||||
return super().get(key, default)
|
||||
|
||||
def __getitem__(self, key):
|
||||
self._ensure()
|
||||
return super().__getitem__(key)
|
||||
|
||||
def __contains__(self, key) -> bool:
|
||||
self._ensure()
|
||||
return super().__contains__(key)
|
||||
|
||||
def names(self) -> list[str]:
|
||||
self._ensure()
|
||||
return sorted(super().keys())
|
||||
|
||||
|
||||
class Registries:
|
||||
def __init__(self) -> None:
|
||||
self.node_types = _Registry(self, "pipewright.nodes")
|
||||
self.providers = _Registry(self, "pipewright.providers")
|
||||
self.harnesses = _Registry(self, "pipewright.harnesses")
|
||||
self.sandboxes = _Registry(self, "pipewright.sandboxes")
|
||||
self.hosts = _Registry(self, "pipewright.hosts")
|
||||
self._loaded = False
|
||||
self._loading = False
|
||||
self.load_errors: dict[str, str] = {}
|
||||
|
||||
def load(self) -> None:
|
||||
if self._loaded or self._loading:
|
||||
return
|
||||
self._loading = True
|
||||
try:
|
||||
for mod in BUILTIN_MODULES:
|
||||
importlib.import_module(mod)
|
||||
for attr, group in GROUPS.items():
|
||||
for ep in entry_points(group=group):
|
||||
if ep.value in BUILTIN_MODULES:
|
||||
continue
|
||||
try:
|
||||
obj = ep.load()
|
||||
except Exception as e: # a broken plugin must not break the CLI
|
||||
self.load_errors[f"{group}:{ep.name}"] = f"{type(e).__name__}: {e}"
|
||||
log.warning("plugin %s failed to load: %s", ep.name, e)
|
||||
continue
|
||||
if isinstance(obj, ModuleType):
|
||||
continue # registered on import
|
||||
if attr == "node_types":
|
||||
register_node(obj)
|
||||
else:
|
||||
dict.__setitem__(getattr(self, attr), ep.name, obj)
|
||||
self._loaded = True
|
||||
finally:
|
||||
self._loading = False
|
||||
|
||||
def import_plugins(self, modules: list[str]) -> None:
|
||||
self.load()
|
||||
for m in modules:
|
||||
try:
|
||||
importlib.import_module(m)
|
||||
except Exception as e:
|
||||
from .errors import ConfigError
|
||||
|
||||
raise ConfigError(f"cannot import plugin module {m!r}: {type(e).__name__}: {e}") from e
|
||||
|
||||
|
||||
registry = Registries()
|
||||
|
||||
|
||||
def register_node(cls: Any) -> Any:
|
||||
"""Class decorator registering a NodeType subclass under `cls.name`."""
|
||||
from .nodes.base import KINDS
|
||||
|
||||
if getattr(cls, "kind", None) not in KINDS:
|
||||
raise ValueError(f"{cls.__name__}.kind must be one of {KINDS}")
|
||||
if not getattr(cls, "name", None):
|
||||
raise ValueError(f"{cls.__name__} needs a `name`")
|
||||
try:
|
||||
cls.Params.__node_type__ = cls.name
|
||||
except (AttributeError, TypeError): # pragma: no cover
|
||||
pass
|
||||
dict.__setitem__(registry.node_types, cls.name, cls)
|
||||
return cls
|
||||
|
||||
|
||||
def _register(reg: _Registry, name: str, factory: Callable | None):
|
||||
if factory is None:
|
||||
def deco(f):
|
||||
dict.__setitem__(reg, name, f)
|
||||
return f
|
||||
return deco
|
||||
dict.__setitem__(reg, name, factory)
|
||||
return factory
|
||||
|
||||
|
||||
def register_provider(name: str, factory: Callable | None = None):
|
||||
"""Register a model provider type: factory(name, config: dict, project) -> ModelProvider."""
|
||||
return _register(registry.providers, name, factory)
|
||||
|
||||
|
||||
def register_harness(name: str, factory: Callable | None = None):
|
||||
"""Register an agent harness type: factory(name, config: dict, project) -> Harness."""
|
||||
return _register(registry.harnesses, name, factory)
|
||||
|
||||
|
||||
def register_host_provider(name: str, factory: Callable | None = None):
|
||||
"""Register a host provider type: factory(name, config: dict, project) -> HostProvider
|
||||
(machines for host pools, see pipewright.hosts)."""
|
||||
return _register(registry.hosts, name, factory)
|
||||
|
||||
|
||||
def register_sandbox(name: str, factory: Callable | None = None):
|
||||
"""Register a sandbox provider type: factory(name, config: dict, project) -> SandboxProvider."""
|
||||
return _register(registry.sandboxes, name, factory)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Static HTML report: the graph with per-edge item counts, per-node status, usage,
|
||||
errors, and drill-down samples. Generated from the index; `--refresh N` adds an
|
||||
auto-reload so a report regenerated during a run (`pw report --watch`) stays live."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import time
|
||||
|
||||
from .graph import GraphSpec
|
||||
from .ops import funnel_for_run, item_view
|
||||
from .store import Store
|
||||
|
||||
CSS = """
|
||||
body{font:14px/1.45 system-ui,sans-serif;margin:24px;color:#1d2433;background:#fafbfc}
|
||||
h1{font-size:20px;margin:0 0 4px} h2{font-size:16px;margin:28px 0 8px} h3{font-size:14px;margin:16px 0 6px}
|
||||
.meta{color:#5b6475} .ok{color:#18794e} .err{color:#c62828} .warn{color:#a15c00}
|
||||
table{border-collapse:collapse;margin:6px 0} td,th{border-bottom:1px solid #e3e6ea;padding:4px 10px;text-align:left}
|
||||
th{font-weight:600;color:#5b6475} svg{background:#fff;border:1px solid #e3e6ea;border-radius:6px}
|
||||
.node rect{fill:#fff;stroke:#7a8599;stroke-width:1.2} .node:hover rect{stroke:#2f6fde;stroke-width:2}
|
||||
.node text{font-size:12px} .node .t{fill:#5b6475;font-size:11px} .edge{fill:none;stroke:#9aa3b2;stroke-width:1.3}
|
||||
.cnt{font-size:11px;fill:#2f6fde;font-weight:600} details{margin:4px 0} summary{cursor:pointer}
|
||||
pre{background:#f3f5f8;padding:8px;border-radius:4px;overflow:auto;max-height:420px;font-size:12px}
|
||||
.node.ext rect{stroke-dasharray:5 3;fill:#f6f8fc;stroke:#2f6fde} .edge.ext{stroke:#2f6fde;stroke-dasharray:5 3}
|
||||
.section{background:#fff;border:1px solid #e3e6ea;border-radius:6px;padding:10px 16px;margin:12px 0}
|
||||
"""
|
||||
|
||||
|
||||
def _layout(spec: GraphSpec) -> dict[str, tuple[int, int]]:
|
||||
order = spec.topo_order()
|
||||
depth: dict[str, int] = {}
|
||||
for n in order:
|
||||
ups = [depth[u] for u in spec.upstream(n) if u in depth]
|
||||
depth[n] = 1 + max(ups, default=-1)
|
||||
rows: dict[int, int] = {}
|
||||
pos = {}
|
||||
for n in order:
|
||||
d = depth[n]
|
||||
pos[n] = (d, rows.get(d, 0))
|
||||
rows[d] = rows.get(d, 0) + 1
|
||||
return pos
|
||||
|
||||
|
||||
def _svg(spec: GraphSpec, fun: dict) -> str:
|
||||
pos = _layout(spec)
|
||||
W, H, GX, GY = 190, 58, 80, 34
|
||||
coords = {n: (20 + c * (W + GX), 20 + r * (H + GY)) for n, (c, r) in pos.items()}
|
||||
width = max((x for x, _ in coords.values()), default=0) + W + 40
|
||||
height = max((y for _, y in coords.values()), default=0) + H + 40
|
||||
parts = [f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">']
|
||||
for e in fun["edges"]:
|
||||
src, sport = e["from"].split(".", 1)
|
||||
dst, _ = e["to"].split(".", 1)
|
||||
if src not in coords or dst not in coords:
|
||||
continue
|
||||
x1, y1 = coords[src][0] + W, coords[src][1] + H / 2
|
||||
x2, y2 = coords[dst][0], coords[dst][1] + H / 2
|
||||
mx = (x1 + x2) / 2
|
||||
ext = " ext" if fun["nodes"].get(src, {}).get("imported_from") else ""
|
||||
parts.append(f'<path class="edge{ext}" d="M{x1},{y1} C{mx},{y1} {mx},{y2} {x2},{y2}"/>')
|
||||
label = f'{sport}: {e["items"]}' if sport != "out" else str(e["items"])
|
||||
parts.append(f'<text class="cnt" x="{mx - 4}" y="{(y1 + y2) / 2 - 4}" text-anchor="middle">'
|
||||
f'{html.escape(label)}</text>')
|
||||
for n, (x, y) in coords.items():
|
||||
info = fun["nodes"][n]
|
||||
ev = info["events"]
|
||||
errs = sum(v for k, v in ev.items() if k.startswith("error"))
|
||||
line = f"ok {ev.get('ok', 0)}" + (f" · cached {ev['cached']}" if ev.get("cached") else "") + \
|
||||
(f" · err {errs}" if errs else "") + (f" · parked {info.get('parked')}" if info.get("parked") else "")
|
||||
err_fill = ' fill="#c62828"' if errs else ""
|
||||
imp = info.get("imported_from")
|
||||
cls = "node ext" if imp else "node"
|
||||
type_text = f"from graph {imp['graph']}:{imp['node']}" if imp else info["type"]
|
||||
parts.append(f'<a href="#node-{html.escape(n)}"><g class="{cls}"><title>'
|
||||
f'{html.escape(str(imp) if imp else info["type"])}</title><rect x="{x}" y="{y}" width="{W}" '
|
||||
f'height="{H}" rx="6"/><text x="{x + 10}" y="{y + 18}" font-weight="600">{html.escape(n)}</text>'
|
||||
f'<text class="t" x="{x + 10}" y="{y + 34}">{html.escape(type_text)}</text>'
|
||||
f'<text class="t" x="{x + 10}" y="{y + 49}"{err_fill}>'
|
||||
f'{html.escape(line)}</text></g></a>')
|
||||
parts.append("</svg>")
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def render_report(spec: GraphSpec, store: Store, run: dict, refresh: int | None = None, samples: int = 5) -> str:
|
||||
from .ops import expanded
|
||||
|
||||
spec = expanded(spec)
|
||||
fun = funnel_for_run(spec, store, run["run_id"])
|
||||
usage = store.usage_summary(run["run_id"])
|
||||
errors = store.errors(run["run_id"], limit=200)
|
||||
st = run.get("stats") or {}
|
||||
h = ['<!doctype html><html><head><meta charset="utf-8">',
|
||||
f'<title>{html.escape(spec.name)} — {run["run_id"]}</title>',
|
||||
f'<meta http-equiv="refresh" content="{refresh}">' if refresh else "",
|
||||
f"<style>{CSS}</style></head><body>",
|
||||
f'<h1>{html.escape(spec.name)}</h1><div class="meta">run {run["run_id"]} · mode {run["mode"]} · '
|
||||
f'status <b class="{"ok" if run["status"] == "completed" else "warn"}">{run["status"]}</b> · started '
|
||||
f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(run["started"]))}'
|
||||
+ (f' · {st.get("duration_s")}s' if st.get("duration_s") else "") + "</div>",
|
||||
'<h2>Graph</h2><div style="overflow-x:auto">', _svg(spec, fun), "</div>"]
|
||||
if usage:
|
||||
h.append("<h2>Model usage</h2><table><tr><th>node</th><th>alias</th><th>model</th><th>calls</th>"
|
||||
"<th>cached</th><th>input tok</th><th>output tok</th><th>$</th></tr>")
|
||||
for u in usage:
|
||||
h.append(f"<tr><td>{html.escape(u['node'])}</td><td>{html.escape(u['alias'])}</td>"
|
||||
f"<td>{html.escape(u['model'])}</td><td>{u['calls']}</td><td>{u['cached_calls']}</td>"
|
||||
f"<td>{u['input_tokens']}</td><td>{u['output_tokens']}</td>"
|
||||
f"<td>{'' if u['cost_usd'] is None else round(u['cost_usd'], 4)}</td></tr>")
|
||||
h.append("</table>")
|
||||
if st.get("budget"):
|
||||
h.append(f'<div class="meta">budget: {html.escape(json.dumps(st["budget"]))}</div>')
|
||||
if errors:
|
||||
h.append(f'<h2 class="err">Errors ({len(errors)})</h2><table><tr><th>node</th><th>category</th>'
|
||||
"<th>input</th><th>message</th></tr>")
|
||||
for e in errors[:100]:
|
||||
h.append(f"<tr><td>{html.escape(e['node'])}</td><td>{html.escape(str(e['category']))}</td>"
|
||||
f"<td><code>{html.escape(e['input'][:12])}</code></td>"
|
||||
f"<td>{html.escape((e['message'] or '')[:300])}</td></tr>")
|
||||
h.append("</table>")
|
||||
h.append("<h2>Nodes</h2>")
|
||||
for nid in spec.topo_order():
|
||||
info = fun["nodes"][nid]
|
||||
node = spec.nodes[nid]
|
||||
h.append(f'<div class="section" id="node-{html.escape(nid)}"><h3>{html.escape(nid)} '
|
||||
f'<span class="meta">({html.escape(node.type)})</span></h3>')
|
||||
h.append(f'<div class="meta">events {html.escape(json.dumps(info["events"]))} · out '
|
||||
f'{html.escape(json.dumps(info["out"]))}</div>')
|
||||
h.append(f"<details><summary>params</summary><pre>{html.escape(json.dumps(node.params, indent=2))}"
|
||||
"</pre></details>")
|
||||
ports = list(info["out"]) + (["__parked__"] if info.get("parked") else [])
|
||||
for port in ports:
|
||||
ids = store.flow_items(run["run_id"], nid, port, limit=samples, sample=True)
|
||||
h.append(f"<details><summary>{html.escape(port)}: {info['out'].get(port, info.get('parked'))} items "
|
||||
f"(sample {len(ids)})</summary>")
|
||||
for it in store.get_items(ids):
|
||||
h.append(f"<details><summary><code>{html.escape(it.key)}</code> "
|
||||
f"<span class='meta'>{it.id[:12]}</span></summary><pre>"
|
||||
f"{html.escape(json.dumps(item_view(it, 1500), indent=2, ensure_ascii=False))}</pre></details>")
|
||||
h.append("</details>")
|
||||
h.append("</div>")
|
||||
h.append("</body></html>")
|
||||
return "\n".join(h)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Sandbox/host providers: base interface, local subprocess, Docker (local or over SSH), fake."""
|
||||
|
||||
from .base import Capabilities, ExecResult, Sandbox, SandboxProvider
|
||||
|
||||
__all__ = ["Capabilities", "ExecResult", "Sandbox", "SandboxProvider"]
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Sandbox/host providers.
|
||||
|
||||
A SandboxProvider creates isolated places to run commands; a Sandbox is one of them.
|
||||
The interface is deliberately small so remote providers (VM APIs, Modal, E2B,
|
||||
Docker on a remote host, verifiers runtimes) are short plugins:
|
||||
|
||||
Sandbox: exec, read, write, expose, host_address, health
|
||||
SandboxProvider: create, setup (hook), destroy, extend, capabilities
|
||||
|
||||
Lifecycle and capacity are handled here, once, by `SandboxProvider.lease()`:
|
||||
slot acquisition (priority-ordered; slots derived from capacity), create, the
|
||||
`setup` commands from the pool config, a health check, optional reuse of healthy
|
||||
sandboxes (`reuse: true`, for expensive VMs), destroy on release, VM-hour/$
|
||||
accounting (`cost_per_hour`), and `drain()` at the end of a run.
|
||||
|
||||
Pool config keys every provider understands:
|
||||
|
||||
slots: 8 # max live sandboxes (default: from capacity, see provider)
|
||||
setup: ["pip install pytest"] # commands run once after create
|
||||
reuse: false # keep healthy sandboxes for the next lease
|
||||
cost_per_hour: 0.0 # USD, for budgets
|
||||
workdir: /workspace
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, AsyncIterator, Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..errors import InfraError
|
||||
from ..scheduler import BudgetTracker, SlotPool
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..project import Project
|
||||
|
||||
|
||||
LEASE_CONTEXT: contextvars.ContextVar[tuple[int, "BudgetTracker | None"]] = contextvars.ContextVar(
|
||||
"pipewright_lease_context", default=(0, None))
|
||||
"""(priority, run budget) of the lease being created — lets `create()` of providers that
|
||||
place sandboxes on host pools pass them on without changing the `create()` signature."""
|
||||
|
||||
|
||||
class Capabilities(BaseModel):
|
||||
cpus: float | None = None
|
||||
memory: str | None = None
|
||||
kvm: bool = False
|
||||
gpu: bool = False
|
||||
network: Literal["none", "full", "allowlist"] = "full"
|
||||
isolated: bool = True
|
||||
"""False for the local provider: commands run on the host."""
|
||||
remote: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecResult:
|
||||
exit_code: int
|
||||
stdout: str
|
||||
stderr: str
|
||||
timed_out: bool = False
|
||||
duration: float = 0.0
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return self.exit_code == 0 and not self.timed_out
|
||||
|
||||
def summary(self, limit: int = 4000) -> str:
|
||||
out = self.stdout[-limit:] + ("\n[stderr]\n" + self.stderr[-limit:] if self.stderr.strip() else "")
|
||||
return f"exit={self.exit_code}{' (timeout)' if self.timed_out else ''}\n{out}"
|
||||
|
||||
|
||||
class Sandbox(ABC):
|
||||
def __init__(self, id: str, workdir: str):
|
||||
self.id, self.workdir = id, workdir
|
||||
self.created = time.time()
|
||||
|
||||
@abstractmethod
|
||||
async def exec(self, cmd: str | list[str], *, timeout: float | None = None, env: dict[str, str] | None = None,
|
||||
cwd: str | None = None, stdin: bytes | None = None) -> ExecResult:
|
||||
"""Run a command (a string runs under `sh -c`). Raises InfraError only when the
|
||||
sandbox itself failed; a failing command is a non-zero ExecResult."""
|
||||
|
||||
@abstractmethod
|
||||
async def read(self, path: str) -> bytes: ...
|
||||
|
||||
@abstractmethod
|
||||
async def write(self, path: str, data: bytes | str) -> None: ...
|
||||
|
||||
async def expose(self, port: int) -> str:
|
||||
"""A URL on the host side for a port inside the sandbox."""
|
||||
raise InfraError(f"{type(self).__name__} cannot expose ports")
|
||||
|
||||
def host_address(self) -> tuple[str, str]:
|
||||
"""(hostname the sandbox uses to reach the host, host IP to bind listeners on)."""
|
||||
return "127.0.0.1", "127.0.0.1"
|
||||
|
||||
async def reverse(self, port: int) -> str | None:
|
||||
"""`host:port` that connects, from inside the sandbox, to 127.0.0.1:`port` on the
|
||||
orchestrating machine (a reverse tunnel), or None if this sandbox reaches the
|
||||
orchestrator directly (then use `host_address`)."""
|
||||
return None
|
||||
|
||||
async def health(self) -> bool:
|
||||
try:
|
||||
return (await self.exec("true", timeout=30)).exit_code == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def path(self, p: str) -> str:
|
||||
return p if p.startswith("/") else f"{self.workdir.rstrip('/')}/{p}"
|
||||
|
||||
|
||||
class SandboxProvider(ABC):
|
||||
type: str = "abstract"
|
||||
|
||||
def __init__(self, name: str, config: dict, project: "Project | None" = None):
|
||||
self.name, self.config, self.project = name, config, project
|
||||
self.slots = SlotPool(self.default_slots())
|
||||
self.idle: list[Sandbox] = []
|
||||
self.live: dict[str, Sandbox] = {}
|
||||
self.stats = {"created": 0, "destroyed": 0, "reused": 0, "failed_create": 0, "seconds": 0.0}
|
||||
|
||||
def default_slots(self) -> int | None:
|
||||
return self.config.get("slots")
|
||||
|
||||
@property
|
||||
def capabilities(self) -> Capabilities:
|
||||
return Capabilities()
|
||||
|
||||
@abstractmethod
|
||||
async def create(self) -> Sandbox: ...
|
||||
|
||||
@abstractmethod
|
||||
async def destroy(self, sandbox: Sandbox) -> None: ...
|
||||
|
||||
async def setup(self, sandbox: Sandbox) -> None:
|
||||
for cmd in self.config.get("setup") or []:
|
||||
r = await sandbox.exec(cmd, timeout=self.config.get("setup_timeout", 900))
|
||||
if not r.ok:
|
||||
raise InfraError(f"sandbox setup command failed: {cmd!r}: {r.summary(800)}")
|
||||
|
||||
async def extend(self, sandbox: Sandbox, seconds: float) -> None:
|
||||
"""Extend a sandbox's time to live (VM providers with TTLs)."""
|
||||
|
||||
def accounts_vm_hours(self) -> bool:
|
||||
"""Whether lease time counts as VM-hours in run budgets. Providers that place
|
||||
sandboxes on host pools return False: the pool accounts host time itself."""
|
||||
return self.capabilities.remote
|
||||
|
||||
@asynccontextmanager
|
||||
async def lease(self, priority: int = 0, budget: BudgetTracker | None = None) -> AsyncIterator[Sandbox]:
|
||||
await self.slots.acquire(priority)
|
||||
sb: Sandbox | None = None
|
||||
start = time.time()
|
||||
healthy = False
|
||||
try:
|
||||
if budget is not None:
|
||||
budget.check()
|
||||
while self.idle:
|
||||
cand = self.idle.pop()
|
||||
if await cand.health():
|
||||
sb = cand
|
||||
self.stats["reused"] += 1
|
||||
break
|
||||
await self._destroy(cand)
|
||||
if sb is None:
|
||||
token = LEASE_CONTEXT.set((priority, budget))
|
||||
try:
|
||||
sb = await self.create()
|
||||
except InfraError:
|
||||
self.stats["failed_create"] += 1
|
||||
raise
|
||||
except Exception as e:
|
||||
self.stats["failed_create"] += 1
|
||||
raise InfraError(f"{self.name}: create failed: {type(e).__name__}: {e}") from e
|
||||
finally:
|
||||
LEASE_CONTEXT.reset(token)
|
||||
self.stats["created"] += 1
|
||||
self.live[sb.id] = sb
|
||||
await self.setup(sb)
|
||||
yield sb
|
||||
healthy = True
|
||||
finally:
|
||||
elapsed = time.time() - start
|
||||
self.stats["seconds"] += elapsed
|
||||
if budget is not None:
|
||||
rate = float(self.config.get("cost_per_hour", 0) or 0)
|
||||
budget.add(vm_hours=elapsed / 3600 if self.accounts_vm_hours() else 0.0, usd=rate * elapsed / 3600)
|
||||
try:
|
||||
if sb is not None:
|
||||
if healthy and self.config.get("reuse") and await sb.health():
|
||||
self.idle.append(sb)
|
||||
else:
|
||||
await asyncio.shield(self._destroy(sb))
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
async def _destroy(self, sb: Sandbox) -> None:
|
||||
self.live.pop(sb.id, None)
|
||||
try:
|
||||
await self.destroy(sb)
|
||||
finally:
|
||||
self.stats["destroyed"] += 1
|
||||
|
||||
async def drain(self) -> None:
|
||||
"""Destroy every sandbox this provider still holds."""
|
||||
idle, self.idle = self.idle, []
|
||||
for sb in idle + [s for s in self.live.values() if s not in idle]:
|
||||
try:
|
||||
await asyncio.shield(self._destroy(sb))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,421 @@
|
||||
"""Docker sandboxes via the docker CLI — locally or on a remote host over SSH.
|
||||
|
||||
sandboxes:
|
||||
docker:
|
||||
type: docker
|
||||
image: python:3.12-slim
|
||||
cpus: 1 # per sandbox; default slots = host CPUs // cpus
|
||||
memory: 2g
|
||||
network: none # none | bridge | allowlist
|
||||
allow: [pypi.org, "*.pythonhosted.org"] # for network: allowlist
|
||||
kvm: false # pass /dev/kvm (nested VMs, e.g. NixOS tests)
|
||||
gpu: false # --gpus all
|
||||
setup: ["pip install -q pytest"]
|
||||
remote:
|
||||
type: ssh_docker # same provider, Docker daemon on another machine
|
||||
host: ssh://user@build-box
|
||||
image: python:3.12-slim
|
||||
vmtest:
|
||||
type: docker
|
||||
hosts: vms # place containers on a host pool (see pipewright.hosts)
|
||||
image: nix-base:dev
|
||||
image_source: {build: ./image} # or {load: img.tar} / {pull: ref}; default: pull on demand
|
||||
cpus: 4 # per sandbox: reserved on the host and passed to docker
|
||||
memory: 7g
|
||||
requires: {kvm: true, labels: [], disk: 20g}
|
||||
prefer: [volume:nix-store] # locality; the image is always preferred
|
||||
volumes: {nix-store: /nix-cache} # named volumes (warm caches); hosts get label volume:<name>
|
||||
|
||||
`network: allowlist` puts the container on an `--internal` Docker network (no route
|
||||
out) and runs an allowlisting HTTP(S) CONNECT proxy on that network's gateway; the
|
||||
container gets HTTP(S)_PROXY pointing at it. Anything not going through the proxy, or
|
||||
to a host not on the list, fails. (Local Docker only.)
|
||||
|
||||
Containers are labelled `pipewright.pool=<name>`; `drain()` removes leftovers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import fnmatch
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from ..errors import ConfigError, InfraError
|
||||
from ..registry import register_sandbox
|
||||
from .base import Capabilities, ExecResult, Sandbox, SandboxProvider
|
||||
from .local import run_process
|
||||
|
||||
|
||||
class DockerSandbox(Sandbox):
|
||||
def __init__(self, id: str, name: str, provider: "DockerProvider", workdir: str, *,
|
||||
docker_host: str | None = None, env: dict[str, str] | None = None, host_lease=None):
|
||||
super().__init__(id, workdir)
|
||||
self.name, self.provider = name, provider
|
||||
self.docker_host = docker_host
|
||||
"""`docker -H` target when the container runs on a pool host (else the provider's)."""
|
||||
self.proc_env = env
|
||||
"""Environment for the local docker CLI process (e.g. the per-host ssh wrapper)."""
|
||||
self.host_lease = host_lease
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
"""The pool Host this container runs on (None unless placed via `hosts:`)."""
|
||||
return self.host_lease.host if self.host_lease is not None else None
|
||||
|
||||
def _docker(self, *args: str) -> list[str]:
|
||||
return self.provider.docker_argv(*args, host=self.docker_host)
|
||||
|
||||
async def reverse(self, port: int) -> str | None:
|
||||
if self.host_lease is None:
|
||||
return None
|
||||
if self.provider.network == "none":
|
||||
raise InfraError(f"sandbox {self.provider.name}: network: none — a container on a pool host cannot "
|
||||
"reach the orchestrator; use network: bridge")
|
||||
if self.provider.network == "host":
|
||||
return f"127.0.0.1:{await self.provider.host_pool.reverse(self.host_lease.host, port, loopback=True)}"
|
||||
relay_port = await self.provider.host_pool.reverse(self.host_lease.host, port)
|
||||
return f"host.docker.internal:{relay_port}"
|
||||
|
||||
async def exec(self, cmd, *, timeout=None, env=None, cwd=None, stdin=None) -> ExecResult:
|
||||
argv = self._docker("exec", "-i")
|
||||
for k, v in {**self.provider.env, **(env or {})}.items():
|
||||
argv += ["-e", f"{k}={v}"]
|
||||
argv += ["-w", self.path(cwd) if cwd else self.workdir, self.name]
|
||||
inner = ["sh", "-c", cmd] if isinstance(cmd, str) else list(cmd)
|
||||
if timeout:
|
||||
inner = ["timeout", "-s", "KILL", str(max(1, int(math.ceil(timeout))))] + inner
|
||||
start = time.time()
|
||||
r = await run_process(argv + inner, timeout=(timeout + 30) if timeout else None, env=self.proc_env, cwd=None,
|
||||
stdin=stdin)
|
||||
if timeout and (r.exit_code in (124, 137) and time.time() - start >= timeout - 0.5):
|
||||
r.timed_out = True
|
||||
if r.exit_code in (125, 126, 127) and ("No such container" in r.stderr or "is not running" in r.stderr):
|
||||
raise InfraError(f"container {self.name} is gone: {r.stderr[:300]}")
|
||||
return r
|
||||
|
||||
async def read(self, path: str) -> bytes:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*self._docker("exec", self.name, "cat", self.path(path)),
|
||||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=self.proc_env)
|
||||
out, err = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
if b"No such container" in err:
|
||||
raise InfraError(f"container {self.name} is gone")
|
||||
raise FileNotFoundError(f"{path}: {err.decode(errors='replace').strip()}")
|
||||
return out
|
||||
|
||||
async def write(self, path: str, data) -> None:
|
||||
p = self.path(path)
|
||||
script = 'mkdir -p "$(dirname "$1")" && cat > "$1"'
|
||||
r = await run_process(self._docker("exec", "-i", self.name, "sh", "-c", script, "sh", p), timeout=120,
|
||||
env=self.proc_env, cwd=None, stdin=data.encode() if isinstance(data, str) else data)
|
||||
if r.exit_code != 0:
|
||||
raise InfraError(f"write {path} failed: {r.stderr[:300]}")
|
||||
|
||||
def host_address(self) -> tuple[str, str]:
|
||||
return self.provider.host_address()
|
||||
|
||||
|
||||
class DockerProvider(SandboxProvider):
|
||||
type = "docker"
|
||||
|
||||
def __init__(self, name: str, config: dict, project=None):
|
||||
if not config.get("image"):
|
||||
raise ConfigError(f"sandbox {name}: `image` is required")
|
||||
self.host = config.get("host")
|
||||
self.host_pool_name: str | None = config.get("hosts")
|
||||
if self.host and self.host_pool_name:
|
||||
raise ConfigError(f"sandbox {name}: give either `host` (one remote daemon) or `hosts` (a host pool)")
|
||||
self.network = config.get("network", "none")
|
||||
if self.network not in ("none", "bridge", "allowlist", "host"):
|
||||
raise ConfigError(f"sandbox {name}: network must be none, bridge, allowlist or host")
|
||||
if self.network == "host" and not config.get("hosts"):
|
||||
raise ConfigError(f"sandbox {name}: network: host is only allowed for containers on a host pool")
|
||||
if self.network == "allowlist" and (self.host or self.host_pool_name):
|
||||
raise ConfigError(f"sandbox {name}: network: allowlist is only supported for local Docker")
|
||||
self.env: dict[str, str] = dict(config.get("env") or {})
|
||||
self._egress: EgressProxy | None = None
|
||||
self._net_name: str | None = None
|
||||
self._gateway: str | None = None
|
||||
self._prepared = asyncio.Lock()
|
||||
self._ready = False
|
||||
super().__init__(name, config, project)
|
||||
|
||||
def docker_argv(self, *args: str, host: str | None = None) -> list[str]:
|
||||
base = [self.config.get("docker", "docker")]
|
||||
if host or self.host:
|
||||
base += ["-H", host or self.host]
|
||||
return base + list(args)
|
||||
|
||||
# ------------------------------------------------------------------ host pools
|
||||
@property
|
||||
def host_pool(self):
|
||||
if not self.host_pool_name:
|
||||
return None
|
||||
if self.project is None:
|
||||
raise ConfigError(f"sandbox {self.name}: `hosts` needs a project")
|
||||
return self.project.host_pool(self.host_pool_name)
|
||||
|
||||
def host_requirements(self):
|
||||
from ..hosts.base import Resources
|
||||
|
||||
req = dict(self.config.get("requires") or {})
|
||||
res = Resources(float(self.config.get("cpus", 1)), 0.0, 0.0)
|
||||
res.memory = Resources.parse({"memory": self.config.get("memory") or req.get("memory")}).memory
|
||||
res.disk = Resources.parse({"disk": req.get("disk")}).disk
|
||||
prefer = set(self.config.get("prefer") or []) | {f"image:{self.config['image']}"}
|
||||
prefer |= {f"volume:{v}" for v in (self.config.get("volumes") or {})}
|
||||
return self.host_pool.requirements(res, kvm=bool(req.get("kvm") or self.config.get("kvm")),
|
||||
gpu=bool(req.get("gpu") or self.config.get("gpu")),
|
||||
labels=set(req.get("labels") or []), prefer=prefer)
|
||||
|
||||
def accounts_vm_hours(self) -> bool:
|
||||
return bool(self.host) # host pools account their own host time
|
||||
|
||||
def default_slots(self) -> int | None:
|
||||
if "slots" in self.config:
|
||||
return self.config["slots"]
|
||||
if self.host_pool_name:
|
||||
return None # the host pool's free resources are the limit
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
out = subprocess.run(self.docker_argv("info", "--format", "{{.NCPU}}"), capture_output=True, text=True,
|
||||
timeout=30)
|
||||
ncpu = int(out.stdout.strip())
|
||||
except Exception:
|
||||
ncpu = os.cpu_count() or 4
|
||||
return max(1, int(ncpu // max(float(self.config.get("cpus", 1)), 0.25)))
|
||||
|
||||
@property
|
||||
def capabilities(self) -> Capabilities:
|
||||
return Capabilities(cpus=self.config.get("cpus", 1), memory=self.config.get("memory"),
|
||||
kvm=bool(self.config.get("kvm")), gpu=bool(self.config.get("gpu")),
|
||||
network={"none": "none", "bridge": "full", "allowlist": "allowlist",
|
||||
"host": "full"}[self.network],
|
||||
remote=bool(self.host or self.host_pool_name))
|
||||
|
||||
async def _prepare(self) -> None:
|
||||
async with self._prepared:
|
||||
if self._ready:
|
||||
return
|
||||
if self.network == "allowlist":
|
||||
self._net_name = f"pw-egress-{self.name}"
|
||||
r = await run_process(self.docker_argv("network", "inspect", self._net_name), timeout=60, env=None,
|
||||
cwd=None, stdin=None)
|
||||
if r.exit_code != 0:
|
||||
r = await run_process(self.docker_argv("network", "create", "--internal", self._net_name),
|
||||
timeout=60, env=None, cwd=None, stdin=None)
|
||||
if r.exit_code != 0:
|
||||
raise InfraError(f"cannot create network {self._net_name}: {r.stderr[:300]}")
|
||||
r = await run_process(self.docker_argv("network", "inspect", self._net_name), timeout=60,
|
||||
env=None, cwd=None, stdin=None)
|
||||
self._gateway = json.loads(r.stdout)[0]["IPAM"]["Config"][0]["Gateway"]
|
||||
self._egress = EgressProxy(self.config.get("allow") or [])
|
||||
port = await self._egress.start(self._gateway)
|
||||
proxy = f"http://{self._gateway}:{port}"
|
||||
self.env.update({"HTTP_PROXY": proxy, "HTTPS_PROXY": proxy, "http_proxy": proxy,
|
||||
"https_proxy": proxy, "NO_PROXY": "host.docker.internal,localhost,127.0.0.1",
|
||||
"no_proxy": "host.docker.internal,localhost,127.0.0.1"})
|
||||
elif self.network == "bridge" and not self.host:
|
||||
r = await run_process(self.docker_argv("network", "inspect", "bridge"), timeout=60, env=None,
|
||||
cwd=None, stdin=None)
|
||||
try:
|
||||
self._gateway = json.loads(r.stdout)[0]["IPAM"]["Config"][0]["Gateway"]
|
||||
except Exception:
|
||||
self._gateway = "172.17.0.1"
|
||||
self._ready = True
|
||||
|
||||
def host_address(self) -> tuple[str, str]:
|
||||
if self.host or self.host_pool_name:
|
||||
raise InfraError(f"sandbox {self.name}: reaching the host from a remote Docker host is not supported "
|
||||
"in v0 (needs a reverse tunnel)")
|
||||
if self.network == "none" or not self._gateway:
|
||||
raise InfraError(f"sandbox {self.name}: network: none — the sandbox cannot reach the host; use "
|
||||
"network: bridge or allowlist for harnesses that call models through the proxy")
|
||||
return "host.docker.internal", self._gateway
|
||||
|
||||
async def create(self) -> Sandbox:
|
||||
if self.host_pool_name:
|
||||
return await self._create_on_pool()
|
||||
await self._prepare()
|
||||
sid = uuid.uuid4().hex[:10]
|
||||
name = f"pw-{self.name}-{sid}"
|
||||
workdir = self.config.get("workdir", "/workspace")
|
||||
argv = self.docker_argv("run", "-d", "--name", name, "--label", f"pipewright.pool={self.name}",
|
||||
"--cpus", str(self.config.get("cpus", 1)), "-w", workdir, "--init")
|
||||
if self.config.get("memory"):
|
||||
argv += ["--memory", str(self.config["memory"])]
|
||||
if self.config.get("pids_limit", 4096):
|
||||
argv += ["--pids-limit", str(self.config.get("pids_limit", 4096))]
|
||||
net = {"none": "none", "bridge": "bridge", "allowlist": self._net_name}[self.network]
|
||||
argv += ["--network", net]
|
||||
if self.network in ("bridge", "allowlist") and self._gateway:
|
||||
argv += ["--add-host", f"host.docker.internal:{self._gateway}"]
|
||||
if self.config.get("kvm"):
|
||||
argv += ["--device", "/dev/kvm"]
|
||||
if self.config.get("gpu"):
|
||||
argv += ["--gpus", "all"]
|
||||
if self.config.get("user"):
|
||||
argv += ["--user", str(self.config["user"])]
|
||||
argv += [str(a) for a in self.config.get("run_args") or []]
|
||||
argv += [self.config["image"], "sleep", "infinity"]
|
||||
r = await run_process(argv, timeout=self.config.get("create_timeout", 600), env=None, cwd=None, stdin=None)
|
||||
if r.exit_code != 0:
|
||||
raise InfraError(f"docker run failed ({r.exit_code}): {r.stderr.strip()[:500]}")
|
||||
return DockerSandbox(sid, name, self, workdir)
|
||||
|
||||
async def _create_on_pool(self) -> Sandbox:
|
||||
from .base import LEASE_CONTEXT
|
||||
|
||||
pool = self.host_pool
|
||||
priority, budget = LEASE_CONTEXT.get()
|
||||
lease = await pool.acquire(self.host_requirements(), priority, budget)
|
||||
host = lease.host
|
||||
try:
|
||||
image = self.config["image"]
|
||||
await pool.ensure_image(host, image, self.config.get("image_source"))
|
||||
sid = uuid.uuid4().hex[:10]
|
||||
name = f"pw-{self.name}-{sid}"
|
||||
workdir = self.config.get("workdir", "/workspace")
|
||||
argv = self.docker_argv("run", "-d", "--name", name, "--label", f"pipewright.pool={self.name}",
|
||||
"--label", f"pipewright.host={host.id}", "--cpus", str(self.config.get("cpus", 1)),
|
||||
"-w", workdir, "--init", host=host.docker_host)
|
||||
if self.config.get("memory"):
|
||||
argv += ["--memory", str(self.config["memory"])]
|
||||
if self.config.get("pids_limit", 4096):
|
||||
argv += ["--pids-limit", str(self.config.get("pids_limit", 4096))]
|
||||
argv += ["--network", self.network if self.network in ("none", "host") else "bridge"]
|
||||
if self.network == "bridge":
|
||||
argv += ["--add-host", "host.docker.internal:host-gateway"] # reverse tunnels (see reverse())
|
||||
req = self.config.get("requires") or {}
|
||||
if (req.get("kvm") or self.config.get("kvm")) and not pool.kvm_runtime:
|
||||
argv += ["--device", "/dev/kvm"]
|
||||
if req.get("gpu") or self.config.get("gpu"):
|
||||
argv += ["--gpus", "all"]
|
||||
if self.config.get("user"):
|
||||
argv += ["--user", str(self.config["user"])]
|
||||
for vol, mount in (self.config.get("volumes") or {}).items():
|
||||
argv += ["-v", f"{vol}:{mount}"]
|
||||
argv += [str(a) for a in self.config.get("run_args") or []]
|
||||
argv += [image, "sleep", "infinity"]
|
||||
env = host.docker_env()
|
||||
r = await run_process(argv, timeout=self.config.get("create_timeout", 600), env=env, cwd=None, stdin=None)
|
||||
if r.exit_code != 0:
|
||||
raise InfraError(f"docker run on host {host.id} failed ({r.exit_code}): {r.stderr.strip()[:500]}")
|
||||
for vol in self.config.get("volumes") or {}:
|
||||
pool.add_label(host, f"volume:{vol}")
|
||||
return DockerSandbox(sid, name, self, workdir, docker_host=host.docker_host, env=env, host_lease=lease)
|
||||
except BaseException:
|
||||
lease.release()
|
||||
raise
|
||||
|
||||
async def destroy(self, sandbox: Sandbox) -> None:
|
||||
assert isinstance(sandbox, DockerSandbox)
|
||||
try:
|
||||
await run_process(sandbox._docker("rm", "-f", sandbox.name), timeout=120, env=sandbox.proc_env, cwd=None,
|
||||
stdin=None)
|
||||
finally:
|
||||
if sandbox.host_lease is not None:
|
||||
sandbox.host_lease.release()
|
||||
|
||||
async def drain(self) -> None:
|
||||
await super().drain()
|
||||
if self._egress is not None:
|
||||
await self._egress.stop()
|
||||
self._egress = None
|
||||
self._ready = False
|
||||
if self._net_name:
|
||||
await run_process(self.docker_argv("network", "rm", self._net_name), timeout=60, env=None, cwd=None,
|
||||
stdin=None)
|
||||
self._net_name = None
|
||||
|
||||
|
||||
class EgressProxy:
|
||||
"""Allowlisting HTTP proxy: CONNECT for HTTPS, absolute-URI forwarding for HTTP."""
|
||||
|
||||
def __init__(self, allow: list[str]):
|
||||
self.allow = [a.lower() for a in allow]
|
||||
self.server: asyncio.AbstractServer | None = None
|
||||
self.denied: list[str] = []
|
||||
|
||||
def allowed(self, host: str) -> bool:
|
||||
host = host.lower().strip("[]")
|
||||
return any(fnmatch.fnmatch(host, pat) or host == pat for pat in self.allow)
|
||||
|
||||
async def start(self, bind: str) -> int:
|
||||
self.server = await asyncio.start_server(self._handle, bind, 0)
|
||||
return self.server.sockets[0].getsockname()[1]
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self.server:
|
||||
self.server.close()
|
||||
await self.server.wait_closed()
|
||||
|
||||
async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
try:
|
||||
head = await reader.readuntil(b"\r\n\r\n")
|
||||
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError):
|
||||
writer.close()
|
||||
return
|
||||
line = head.split(b"\r\n", 1)[0].decode("latin-1")
|
||||
try:
|
||||
method, target, version = line.split(" ", 2)
|
||||
except ValueError:
|
||||
writer.close()
|
||||
return
|
||||
if method.upper() == "CONNECT":
|
||||
host, _, port = target.rpartition(":")
|
||||
rest = b""
|
||||
else:
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
u = urlsplit(target)
|
||||
host, port = u.hostname or "", str(u.port or 80)
|
||||
path = (u.path or "/") + (f"?{u.query}" if u.query else "")
|
||||
rest = head.replace(line.encode("latin-1"), f"{method} {path} {version}".encode("latin-1"), 1)
|
||||
if not self.allowed(host):
|
||||
self.denied.append(host)
|
||||
writer.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 27\r\n\r\negress denied by pipewright")
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
return
|
||||
try:
|
||||
up_r, up_w = await asyncio.wait_for(asyncio.open_connection(host, int(port)), 30)
|
||||
except Exception:
|
||||
writer.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
|
||||
await writer.drain()
|
||||
writer.close()
|
||||
return
|
||||
if method.upper() == "CONNECT":
|
||||
writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
await writer.drain()
|
||||
else:
|
||||
up_w.write(rest)
|
||||
await asyncio.gather(_pipe(reader, up_w), _pipe(up_r, writer), return_exceptions=True)
|
||||
|
||||
|
||||
async def _pipe(r: asyncio.StreamReader, w: asyncio.StreamWriter) -> None:
|
||||
try:
|
||||
while data := await r.read(65536):
|
||||
w.write(data)
|
||||
await w.drain()
|
||||
finally:
|
||||
try:
|
||||
w.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _ssh_docker(name: str, config: dict, project=None) -> DockerProvider:
|
||||
if not config.get("host"):
|
||||
raise ConfigError(f"sandbox {name}: ssh_docker needs `host: ssh://user@host`")
|
||||
return DockerProvider(name, config, project)
|
||||
|
||||
|
||||
register_sandbox("docker", DockerProvider)
|
||||
register_sandbox("ssh_docker", _ssh_docker)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""In-memory fake sandbox for unit tests: files live in a dict, commands are matched
|
||||
against rules.
|
||||
|
||||
sandboxes:
|
||||
fake:
|
||||
type: fake
|
||||
rules: # first regex match on the command wins
|
||||
- {match: "pytest", exit_code: 1, stdout: "1 failed"}
|
||||
default_exit: 0
|
||||
fail_create: 0 # inject N create failures (InfraError)
|
||||
|
||||
`cat <path>` and `echo ... > path` style commands are not interpreted; use read/write.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from ..errors import InfraError
|
||||
from ..registry import register_sandbox
|
||||
from .base import Capabilities, ExecResult, Sandbox, SandboxProvider
|
||||
|
||||
|
||||
class FakeSandbox(Sandbox):
|
||||
def __init__(self, id: str, provider: "FakeProvider"):
|
||||
super().__init__(id, "/workspace")
|
||||
self.provider = provider
|
||||
self.files: dict[str, bytes] = {}
|
||||
self.commands: list[str] = []
|
||||
|
||||
async def exec(self, cmd, *, timeout=None, env=None, cwd=None, stdin=None) -> ExecResult:
|
||||
text = cmd if isinstance(cmd, str) else " ".join(cmd)
|
||||
self.commands.append(text)
|
||||
handler = self.provider.handler
|
||||
if handler is not None:
|
||||
return handler(self, text)
|
||||
for rx, rule in self.provider.rules:
|
||||
if rx.search(text):
|
||||
return ExecResult(int(rule.get("exit_code", 0)), rule.get("stdout", ""), rule.get("stderr", ""))
|
||||
return ExecResult(int(self.provider.config.get("default_exit", 0)), "", "")
|
||||
|
||||
async def read(self, path: str) -> bytes:
|
||||
p = self.path(path)
|
||||
if p not in self.files:
|
||||
raise FileNotFoundError(path)
|
||||
return self.files[p]
|
||||
|
||||
async def write(self, path: str, data) -> None:
|
||||
self.files[self.path(path)] = data.encode() if isinstance(data, str) else data
|
||||
|
||||
|
||||
class FakeProvider(SandboxProvider):
|
||||
type = "fake"
|
||||
|
||||
def __init__(self, name, config, project=None):
|
||||
super().__init__(name, config, project)
|
||||
self.rules = [(re.compile(r.get("match", ""), re.S), r) for r in config.get("rules", [])]
|
||||
self.handler = config.get("_handler")
|
||||
self.fail_create = int(config.get("fail_create", 0))
|
||||
self.destroyed: list[str] = []
|
||||
|
||||
@property
|
||||
def capabilities(self) -> Capabilities:
|
||||
return Capabilities(network="none")
|
||||
|
||||
async def create(self) -> Sandbox:
|
||||
if self.fail_create > 0:
|
||||
self.fail_create -= 1
|
||||
raise InfraError("injected create failure")
|
||||
return FakeSandbox(f"fake-{uuid.uuid4().hex[:8]}", self)
|
||||
|
||||
async def destroy(self, sandbox: Sandbox) -> None:
|
||||
self.destroyed.append(sandbox.id)
|
||||
|
||||
|
||||
register_sandbox("fake", FakeProvider)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Local subprocess sandbox: a fresh temp directory on the host per sandbox.
|
||||
|
||||
No isolation (commands run as you, with your network) — use it for trusted commands,
|
||||
fast tests and development; use `docker` for anything an agent or a generated task
|
||||
controls.
|
||||
|
||||
sandboxes:
|
||||
local: {type: local, setup: ["python -m venv .venv"]}
|
||||
|
||||
Relative paths are relative to the sandbox's temp workdir; the `slots` default is the
|
||||
host CPU count.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from ..errors import InfraError
|
||||
from ..registry import register_sandbox
|
||||
from .base import Capabilities, ExecResult, Sandbox, SandboxProvider
|
||||
|
||||
|
||||
async def run_process(argv: list[str], *, timeout: float | None, env: dict | None, cwd: str | None,
|
||||
stdin: bytes | None, limit: int = 2_000_000) -> ExecResult:
|
||||
start = time.time()
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*argv, cwd=cwd, env=env, stdin=asyncio.subprocess.PIPE if stdin is not None else asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, start_new_session=True)
|
||||
except OSError as e:
|
||||
raise InfraError(f"cannot start {argv[0]}: {e}") from e
|
||||
timed_out = False
|
||||
try:
|
||||
out, err = await asyncio.wait_for(proc.communicate(stdin), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
timed_out = True
|
||||
try:
|
||||
os.killpg(proc.pid, 9)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
out, err = await proc.communicate()
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
os.killpg(proc.pid, 9)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
raise
|
||||
return ExecResult(proc.returncode if proc.returncode is not None else -1,
|
||||
out[-limit:].decode(errors="replace"), err[-limit:].decode(errors="replace"),
|
||||
timed_out, time.time() - start)
|
||||
|
||||
|
||||
class LocalSandbox(Sandbox):
|
||||
async def exec(self, cmd, *, timeout=None, env=None, cwd=None, stdin=None) -> ExecResult:
|
||||
argv = ["bash", "-c", cmd] if isinstance(cmd, str) else list(cmd)
|
||||
full_env = {**os.environ, "HOME": os.environ.get("HOME", self.workdir), **(env or {})}
|
||||
return await run_process(argv, timeout=timeout, env=full_env, cwd=self.path(cwd) if cwd else self.workdir,
|
||||
stdin=stdin)
|
||||
|
||||
async def read(self, path: str) -> bytes:
|
||||
try:
|
||||
return Path(self.path(path)).read_bytes()
|
||||
except OSError as e:
|
||||
raise FileNotFoundError(f"{path}: {e.strerror}") from None
|
||||
|
||||
async def write(self, path: str, data) -> None:
|
||||
p = Path(self.path(path))
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_bytes(data.encode() if isinstance(data, str) else data)
|
||||
|
||||
|
||||
class LocalProvider(SandboxProvider):
|
||||
type = "local"
|
||||
|
||||
def default_slots(self) -> int | None:
|
||||
return self.config.get("slots", os.cpu_count() or 4)
|
||||
|
||||
@property
|
||||
def capabilities(self) -> Capabilities:
|
||||
return Capabilities(network="full", isolated=False)
|
||||
|
||||
async def create(self) -> Sandbox:
|
||||
root = tempfile.mkdtemp(prefix=f"pw-{self.name}-", dir=self.config.get("root"))
|
||||
return LocalSandbox(f"local-{uuid.uuid4().hex[:8]}", root)
|
||||
|
||||
async def destroy(self, sandbox: Sandbox) -> None:
|
||||
if not self.config.get("keep"):
|
||||
await asyncio.to_thread(shutil.rmtree, sandbox.workdir, True)
|
||||
|
||||
|
||||
register_sandbox("local", LocalProvider)
|
||||
@@ -0,0 +1,423 @@
|
||||
"""Resource leases: concurrency emerges from limits, not from worker counts.
|
||||
|
||||
- RateLimiter: rolling-window request/token budgets per provider. A request is
|
||||
recorded in the window when it is ADMITTED, so requests the provider rejects (429)
|
||||
still count against the window — exactly how providers that count rejected requests
|
||||
behave — and a 429 additionally closes a shared gate for Retry-After (or an
|
||||
exponential backoff), so retries do not keep the window full and starve themselves.
|
||||
Waiters are served in priority order (deeper graph nodes first), so items flow to
|
||||
the end of the pipeline instead of every stage being half done.
|
||||
With `shared=SharedLedger(...)` the window and the 429 gate live in a small SQLite
|
||||
ledger file instead, so several processes/runs sharing one provider key pace jointly
|
||||
(admission = check + insert in one `BEGIN IMMEDIATE` transaction). The local
|
||||
priority queue still orders this process's waiters; when the ledger says "wait",
|
||||
the pump re-polls (capped at `SharedLedger.max_poll`).
|
||||
- SlotPool: N slots (sandbox pools, hosts) with the same priority ordering; N comes
|
||||
from capacity (host CPUs / sandbox CPUs, a provider's concurrent-sandbox limit).
|
||||
- BudgetTracker: USD / token / VM-hour budgets per run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import heapq
|
||||
import itertools
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import BudgetExceeded, backoff_scale
|
||||
|
||||
_seq = itertools.count()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Entry:
|
||||
at: float
|
||||
input_tokens: int
|
||||
output_tokens: float
|
||||
id: int | None = None # ledger row id when the limiter is shared
|
||||
|
||||
|
||||
@dataclass(order=True)
|
||||
class _Waiter:
|
||||
priority: int
|
||||
seq: int
|
||||
input_tokens: int = field(compare=False)
|
||||
future: asyncio.Future = field(compare=False)
|
||||
|
||||
|
||||
class Lease:
|
||||
def __init__(self, limiter: "RateLimiter", entry: _Entry):
|
||||
self.limiter, self.entry = limiter, entry
|
||||
|
||||
def settle(self, output_tokens: int | None) -> None:
|
||||
"""Record the actual output tokens once known."""
|
||||
if output_tokens is None:
|
||||
return
|
||||
self.entry.output_tokens = output_tokens
|
||||
if self.limiter.shared is not None and self.entry.id is not None:
|
||||
self.limiter.shared.settle(self.entry.id, output_tokens)
|
||||
self.limiter.observe(output_tokens)
|
||||
|
||||
|
||||
DEFAULT_SHARED_DIR = "~/.cache/pipewright/rate"
|
||||
|
||||
|
||||
def _ok(r: int, i: float, o: float, need_in: int, need_out: float,
|
||||
rpm: int | None, ipm: int | None, opm: int | None) -> bool:
|
||||
# an over-sized single request is admitted into an empty window
|
||||
if r == 0:
|
||||
return True
|
||||
return ((rpm is None or r + 1 <= rpm)
|
||||
and (ipm is None or i + need_in <= ipm)
|
||||
and (opm is None or o + need_out <= opm))
|
||||
|
||||
|
||||
class SharedLedger:
|
||||
"""A cross-process rate window: one SQLite file per provider key.
|
||||
|
||||
Rows are admitted requests (wall-clock `at`, input tokens, output tokens — the
|
||||
estimate until settled); `meta.gate_until` is the shared 429 gate (wall clock).
|
||||
Every operation is one short transaction; admission checks and inserts under
|
||||
`BEGIN IMMEDIATE`, so concurrent processes cannot both take the last slot.
|
||||
All processes sharing a key should use the same window/limits.
|
||||
"""
|
||||
|
||||
def __init__(self, path: str | Path, clock=time.time, max_poll: float = 0.5, busy_timeout_ms: int = 10000):
|
||||
self.path = Path(path).expanduser()
|
||||
self.clock = clock
|
||||
self.max_poll = max_poll
|
||||
self.busy_timeout_ms = busy_timeout_ms
|
||||
self._conn: sqlite3.Connection | None = None
|
||||
self._pid: int | None = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@classmethod
|
||||
def for_key(cls, key: str, directory: str | Path | None = None, **kw) -> "SharedLedger":
|
||||
safe = re.sub(r"[^A-Za-z0-9._-]", "_", key) or "default"
|
||||
return cls(Path(directory or DEFAULT_SHARED_DIR).expanduser() / f"{safe}.sqlite", **kw)
|
||||
|
||||
def _db(self) -> sqlite3.Connection:
|
||||
if self._conn is None or self._pid != os.getpid(): # never reuse a connection across fork
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
c = sqlite3.connect(str(self.path), timeout=self.busy_timeout_ms / 1000, isolation_level=None,
|
||||
check_same_thread=False)
|
||||
c.execute(f"PRAGMA busy_timeout={int(self.busy_timeout_ms)}")
|
||||
deadline = time.monotonic() + self.busy_timeout_ms / 1000
|
||||
while True: # switching to WAL on a fresh file can report "locked" without the busy handler
|
||||
try:
|
||||
c.execute("PRAGMA journal_mode=WAL")
|
||||
c.execute("PRAGMA synchronous=NORMAL")
|
||||
c.execute("CREATE TABLE IF NOT EXISTS entries (id INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"at REAL NOT NULL, input_tokens INTEGER NOT NULL, output_tokens REAL NOT NULL, "
|
||||
"settled INTEGER NOT NULL DEFAULT 0)")
|
||||
c.execute("CREATE INDEX IF NOT EXISTS entries_at ON entries(at)")
|
||||
c.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v REAL NOT NULL)")
|
||||
break
|
||||
except sqlite3.OperationalError as e:
|
||||
if "locked" not in str(e) or time.monotonic() > deadline:
|
||||
c.close()
|
||||
raise
|
||||
time.sleep(0.01 + random.random() * 0.02)
|
||||
self._conn, self._pid = c, os.getpid()
|
||||
return self._conn
|
||||
|
||||
def _tx(self, fn):
|
||||
with self._lock:
|
||||
c = self._db()
|
||||
c.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
out = fn(c)
|
||||
except BaseException:
|
||||
c.execute("ROLLBACK")
|
||||
raise
|
||||
c.execute("COMMIT")
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _gate(c: sqlite3.Connection) -> float:
|
||||
row = c.execute("SELECT v FROM meta WHERE k='gate_until'").fetchone()
|
||||
return row[0] if row else 0.0
|
||||
|
||||
def try_admit(self, need_in: int, need_out: float, rpm: int | None, ipm: int | None, opm: int | None,
|
||||
window: float, record: bool = True) -> tuple[float, int | None]:
|
||||
"""Atomically check the shared window and, if the request fits, record it.
|
||||
Returns (0, row id) when admitted, else (seconds to wait, None)."""
|
||||
|
||||
def fn(c):
|
||||
now = self.clock()
|
||||
gate = self._gate(c)
|
||||
if now < gate:
|
||||
return gate - now, None
|
||||
cutoff = now - window
|
||||
c.execute("DELETE FROM entries WHERE at <= ?", (cutoff,))
|
||||
if record and not (rpm is None and ipm is None and opm is None):
|
||||
r, tin, tout = c.execute("SELECT COUNT(*), COALESCE(SUM(input_tokens), 0), "
|
||||
"COALESCE(SUM(output_tokens), 0) FROM entries").fetchone()
|
||||
if not _ok(r, tin, tout, need_in, need_out, rpm, ipm, opm):
|
||||
for at, ei, eo in c.execute("SELECT at, input_tokens, output_tokens FROM entries ORDER BY at, id"):
|
||||
r, tin, tout = r - 1, tin - ei, tout - eo
|
||||
if _ok(r, tin, tout, need_in, need_out, rpm, ipm, opm):
|
||||
return max(0.01, at + window - now), None
|
||||
return window, None
|
||||
cur = c.execute("INSERT INTO entries (at, input_tokens, output_tokens) VALUES (?, ?, ?)",
|
||||
(now, need_in, need_out))
|
||||
return 0.0, cur.lastrowid
|
||||
return 0.0, None
|
||||
|
||||
return self._tx(fn)
|
||||
|
||||
def settle(self, entry_id: int, output_tokens: float) -> None:
|
||||
self._tx(lambda c: c.execute("UPDATE entries SET output_tokens=?, settled=1 WHERE id=?",
|
||||
(output_tokens, entry_id)))
|
||||
|
||||
def extend_gate(self, delay: float) -> float:
|
||||
"""Close the shared gate for at least `delay` seconds from now; returns gate_until."""
|
||||
|
||||
def fn(c):
|
||||
until = max(self._gate(c), self.clock() + delay)
|
||||
c.execute("INSERT INTO meta (k, v) VALUES ('gate_until', ?) "
|
||||
"ON CONFLICT(k) DO UPDATE SET v=excluded.v", (until,))
|
||||
return until
|
||||
|
||||
return self._tx(fn)
|
||||
|
||||
def gate_remaining(self) -> float:
|
||||
return self._tx(lambda c: max(0.0, self._gate(c) - self.clock()))
|
||||
|
||||
def totals(self, window: float) -> dict:
|
||||
def fn(c):
|
||||
r, tin, tout = c.execute("SELECT COUNT(*), COALESCE(SUM(input_tokens), 0), COALESCE(SUM(output_tokens), 0) "
|
||||
"FROM entries WHERE at > ?", (self.clock() - window,)).fetchone()
|
||||
return {"requests": r, "input_tokens": tin, "output_tokens": tout}
|
||||
|
||||
return self._tx(fn)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._conn is not None:
|
||||
self._conn.close()
|
||||
self._conn = None
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
def __init__(self, requests_per_minute: int | None = None, input_tokens_per_minute: int | None = None,
|
||||
output_tokens_per_minute: int | None = None, window: float = 60.0,
|
||||
initial_output_estimate: float = 800.0, clock=time.monotonic,
|
||||
shared: SharedLedger | None = None):
|
||||
self.rpm, self.ipm, self.opm = requests_per_minute, input_tokens_per_minute, output_tokens_per_minute
|
||||
self.window = window
|
||||
self.entries: list[_Entry] = []
|
||||
self.waiters: list[_Waiter] = []
|
||||
self.out_estimate = initial_output_estimate
|
||||
self.gate_until = 0.0
|
||||
self.consecutive_rejects = 0
|
||||
self.clock = clock
|
||||
self.shared = shared
|
||||
self._timer: asyncio.TimerHandle | None = None
|
||||
self.stats = {"admitted": 0, "rejected": 0, "waited_s": 0.0}
|
||||
|
||||
@property
|
||||
def unlimited(self) -> bool:
|
||||
return self.rpm is None and self.ipm is None and self.opm is None
|
||||
|
||||
def observe(self, output_tokens: int) -> None:
|
||||
self.out_estimate = 0.9 * self.out_estimate + 0.1 * output_tokens
|
||||
|
||||
def reject(self, retry_after: float | None = None) -> float:
|
||||
"""The provider rejected a request (429): close the gate. Returns the delay."""
|
||||
self.consecutive_rejects += 1
|
||||
self.stats["rejected"] += 1
|
||||
if retry_after is None:
|
||||
retry_after = min(60.0, 2.0 * (1.6 ** min(self.consecutive_rejects, 10))) * backoff_scale()
|
||||
delay = retry_after + random.random() * min(5.0, retry_after * 0.2 + 0.5) * backoff_scale()
|
||||
self.gate_until = max(self.gate_until, self.clock() + delay)
|
||||
if self.shared is not None:
|
||||
self.shared.extend_gate(delay)
|
||||
self._schedule(delay)
|
||||
return delay
|
||||
|
||||
def accepted(self) -> None:
|
||||
self.consecutive_rejects = 0
|
||||
|
||||
async def acquire(self, input_tokens: int = 0, priority: int = 0) -> Lease:
|
||||
loop = asyncio.get_running_loop()
|
||||
start = self.clock()
|
||||
w = _Waiter(priority, next(_seq), input_tokens, loop.create_future())
|
||||
heapq.heappush(self.waiters, w)
|
||||
self._pump()
|
||||
try:
|
||||
entry = await w.future
|
||||
except asyncio.CancelledError:
|
||||
if not w.future.done():
|
||||
w.future.cancel()
|
||||
self.waiters = [x for x in self.waiters if x is not w]
|
||||
heapq.heapify(self.waiters)
|
||||
raise
|
||||
self.stats["waited_s"] += self.clock() - start
|
||||
return Lease(self, entry)
|
||||
|
||||
def _expire(self, now: float) -> None:
|
||||
cutoff = now - self.window
|
||||
if self.entries and self.entries[0].at <= cutoff:
|
||||
self.entries = [e for e in self.entries if e.at > cutoff]
|
||||
|
||||
def _fits(self, need_in: int) -> float:
|
||||
"""0 if a request with `need_in` input tokens fits now, else seconds to wait."""
|
||||
now = self.clock()
|
||||
if now < self.gate_until:
|
||||
return self.gate_until - now
|
||||
self._expire(now)
|
||||
req = len(self.entries)
|
||||
tin = sum(e.input_tokens for e in self.entries)
|
||||
tout = sum(e.output_tokens for e in self.entries)
|
||||
need_out = self.out_estimate
|
||||
|
||||
def ok(r: int, i: float, o: float) -> bool:
|
||||
# an over-sized single request is admitted into an empty window
|
||||
if r == 0:
|
||||
return True
|
||||
return ((self.rpm is None or r + 1 <= self.rpm)
|
||||
and (self.ipm is None or i + need_in <= self.ipm)
|
||||
and (self.opm is None or o + need_out <= self.opm))
|
||||
|
||||
if ok(req, tin, tout):
|
||||
return 0.0
|
||||
for e in self.entries: # oldest first: when would enough expire?
|
||||
req, tin, tout = req - 1, tin - e.input_tokens, tout - e.output_tokens
|
||||
if ok(req, tin, tout):
|
||||
return max(0.01, e.at + self.window - now)
|
||||
return self.window
|
||||
|
||||
def _schedule(self, delay: float) -> None:
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
return
|
||||
if self._timer is not None:
|
||||
self._timer.cancel()
|
||||
self._timer = loop.call_later(delay, self._pump)
|
||||
|
||||
def _pump(self) -> None:
|
||||
if self.shared is not None:
|
||||
return self._pump_shared()
|
||||
while self.waiters:
|
||||
w = self.waiters[0]
|
||||
if w.future.done():
|
||||
heapq.heappop(self.waiters)
|
||||
continue
|
||||
wait = 0.0 if self.unlimited and self.clock() >= self.gate_until else self._fits(w.input_tokens)
|
||||
if wait > 0:
|
||||
self._schedule(wait)
|
||||
return
|
||||
heapq.heappop(self.waiters)
|
||||
entry = _Entry(self.clock(), w.input_tokens, self.out_estimate)
|
||||
if not self.unlimited:
|
||||
self.entries.append(entry)
|
||||
self.stats["admitted"] += 1
|
||||
w.future.set_result(entry)
|
||||
|
||||
def _pump_shared(self) -> None:
|
||||
led = self.shared
|
||||
while self.waiters:
|
||||
w = self.waiters[0]
|
||||
if w.future.done():
|
||||
heapq.heappop(self.waiters)
|
||||
continue
|
||||
wait, row = led.try_admit(w.input_tokens, self.out_estimate, self.rpm, self.ipm, self.opm,
|
||||
self.window, record=not self.unlimited)
|
||||
if wait > 0:
|
||||
self._schedule(min(wait, led.max_poll)) # other processes may free room earlier
|
||||
return
|
||||
heapq.heappop(self.waiters)
|
||||
entry = _Entry(self.clock(), w.input_tokens, self.out_estimate, row)
|
||||
self.stats["admitted"] += 1
|
||||
w.future.set_result(entry)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
now = self.clock()
|
||||
if self.shared is not None:
|
||||
t = self.shared.totals(self.window)
|
||||
return {"in_window": t["requests"], "waiting": len(self.waiters),
|
||||
"gate_closed_s": round(self.shared.gate_remaining(), 1), "shared": str(self.shared.path),
|
||||
**self.stats}
|
||||
self._expire(now)
|
||||
return {"in_window": len(self.entries), "waiting": len(self.waiters),
|
||||
"gate_closed_s": max(0.0, round(self.gate_until - now, 1)), **self.stats}
|
||||
|
||||
|
||||
class SlotPool:
|
||||
"""A priority-ordered counting semaphore; `slots=None` means unlimited."""
|
||||
|
||||
def __init__(self, slots: int | None):
|
||||
self.slots = slots
|
||||
self.in_use = 0
|
||||
self.waiters: list[_Waiter] = []
|
||||
|
||||
async def acquire(self, priority: int = 0) -> None:
|
||||
if self.slots is None or (self.in_use < self.slots and not self.waiters):
|
||||
self.in_use += 1
|
||||
return
|
||||
w = _Waiter(priority, next(_seq), 0, asyncio.get_running_loop().create_future())
|
||||
heapq.heappush(self.waiters, w)
|
||||
try:
|
||||
await w.future
|
||||
except asyncio.CancelledError:
|
||||
if w.future.done() and not w.future.cancelled():
|
||||
self.release() # we were granted the slot while being cancelled
|
||||
else:
|
||||
self.waiters = [x for x in self.waiters if x is not w]
|
||||
heapq.heapify(self.waiters)
|
||||
raise
|
||||
|
||||
def release(self) -> None:
|
||||
while self.waiters:
|
||||
w = heapq.heappop(self.waiters)
|
||||
if not w.future.done():
|
||||
w.future.set_result(None) # hand the slot over directly
|
||||
return
|
||||
self.in_use -= 1
|
||||
|
||||
|
||||
class BudgetTracker:
|
||||
def __init__(self, usd: float | None = None, input_tokens: int | None = None,
|
||||
output_tokens: int | None = None, vm_hours: float | None = None,
|
||||
counters: dict[str, float] | None = None):
|
||||
self.limits = {"usd": usd, "input_tokens": input_tokens, "output_tokens": output_tokens, "vm_hours": vm_hours}
|
||||
self.used = {"usd": 0.0, "input_tokens": 0, "output_tokens": 0, "vm_hours": 0.0}
|
||||
self.exceeded: str | None = None
|
||||
self.counter_limits: dict[str, float] = dict(counters or {})
|
||||
self.counters: dict[str, float] = {}
|
||||
|
||||
def count(self, name: str, n: float = 1) -> None:
|
||||
"""Spend `n` units of a named counter budget (e.g. `rollouts.terra`). Raises
|
||||
BudgetExceeded — for this call only; other work continues — when it would go over
|
||||
the limit, so at most `limit` units are ever counted. Unlimited counters are tracked."""
|
||||
lim = self.counter_limits.get(name)
|
||||
cur = self.counters.get(name, 0)
|
||||
if lim is not None and cur + n > lim:
|
||||
raise BudgetExceeded(f"counter budget {name!r} exhausted ({cur:g} + {n:g} > {lim:g})")
|
||||
self.counters[name] = cur + n
|
||||
|
||||
def add(self, **amounts: float) -> None:
|
||||
for k, v in amounts.items():
|
||||
if v:
|
||||
self.used[k] += v
|
||||
for k, lim in self.limits.items():
|
||||
if lim is not None and self.used[k] >= lim and not self.exceeded:
|
||||
self.exceeded = f"{k} budget exhausted ({self.used[k]:.4g} >= {lim})"
|
||||
|
||||
def check(self) -> None:
|
||||
if self.exceeded:
|
||||
raise BudgetExceeded(self.exceeded)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {"used": {k: round(v, 6) for k, v in self.used.items()},
|
||||
"limits": {k: v for k, v in self.limits.items() if v is not None}, "exceeded": self.exceeded,
|
||||
**({"counters": dict(self.counters), "counter_limits": dict(self.counter_limits)}
|
||||
if self.counters or self.counter_limits else {})}
|
||||
@@ -0,0 +1,616 @@
|
||||
"""Persistent store: content-addressed blobs + a SQLite index.
|
||||
|
||||
Layout under the store root (default `.pipewright/` next to the project file):
|
||||
|
||||
blobs/ab/cdef... content-addressed artifacts (sha256)
|
||||
index.sqlite items, lineage, memo results, runs, flows, usage, request cache, reviews
|
||||
|
||||
The index is plain SQLite (stdlib) so it can be inspected with any SQLite tool; the
|
||||
funnel/lineage/sample queries the CLI needs live here as methods. WAL mode lets
|
||||
`pw status`/`pw report` read while a run writes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import random
|
||||
import sqlite3
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .items import ArtifactRef, Item
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY, key TEXT, kind TEXT, provenance TEXT, producer TEXT, op TEXT,
|
||||
created REAL, data TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS items_key ON items(key);
|
||||
CREATE TABLE IF NOT EXISTS lineage (child TEXT, parent TEXT, PRIMARY KEY (child, parent));
|
||||
CREATE INDEX IF NOT EXISTS lineage_parent ON lineage(parent);
|
||||
CREATE TABLE IF NOT EXISTS memo (
|
||||
sig TEXT, input_key TEXT, node TEXT, status TEXT, outputs TEXT, error TEXT,
|
||||
run_id TEXT, created REAL, duration REAL, PRIMARY KEY (sig, input_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runs (
|
||||
run_id TEXT PRIMARY KEY, graph TEXT, graph_hash TEXT, mode TEXT, status TEXT,
|
||||
started REAL, finished REAL, spec TEXT, stats TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS flows (
|
||||
run_id TEXT, node TEXT, port TEXT, item_id TEXT, PRIMARY KEY (run_id, node, port, item_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
run_id TEXT, node TEXT, input_key TEXT, status TEXT, cached INTEGER, category TEXT,
|
||||
message TEXT, at REAL, PRIMARY KEY (run_id, node, input_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS usage (
|
||||
run_id TEXT, node TEXT, item_id TEXT, alias TEXT, provider TEXT, model TEXT,
|
||||
input_tokens INTEGER, output_tokens INTEGER, cost REAL, cached INTEGER, at REAL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS request_cache (key TEXT PRIMARY KEY, response TEXT, created REAL);
|
||||
CREATE INDEX IF NOT EXISTS items_producer ON items(producer);
|
||||
CREATE TABLE IF NOT EXISTS reviews (
|
||||
node TEXT, item_id TEXT, decision TEXT, note TEXT, at REAL, PRIMARY KEY (node, item_id)
|
||||
);
|
||||
"""
|
||||
|
||||
MIGRATIONS: list[str] = [
|
||||
"ALTER TABLE items ADD COLUMN run_id TEXT", # run that first stored the item (-> graph)
|
||||
]
|
||||
|
||||
DONE_STATUSES = ("completed", "completed_with_errors", "budget_exceeded")
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemoEntry:
|
||||
status: str # ok | error
|
||||
outputs: dict[str, list[str]]
|
||||
error: dict | None
|
||||
run_id: str | None
|
||||
duration: float | None
|
||||
|
||||
|
||||
class _BatchedDB:
|
||||
"""A sqlite3 connection whose bulk writes are buffered and committed in batches.
|
||||
|
||||
Hot-path writes (items, lineage, flows, events, memo, usage, request cache) go to
|
||||
`write()`, which only appends to an in-memory buffer. `commit()` (after `max_ops`
|
||||
buffered rows, `max_age` seconds, any immediate write, or explicitly) takes the
|
||||
write lock with `BEGIN IMMEDIATE`, runs one `executemany` per statement and
|
||||
commits — so the lock is held for milliseconds, not while Python works, and many
|
||||
worker processes can share one store. Readers that need buffered rows either
|
||||
commit first (funnels, queries) or consult the overlays (memo, request cache);
|
||||
items are served from each Store's item cache.
|
||||
"""
|
||||
|
||||
def __init__(self, conn: sqlite3.Connection, max_ops: int = 5000, max_age: float = 0.5):
|
||||
self.conn, self.max_ops, self.max_age = conn, max_ops, max_age
|
||||
self.pending: dict[str, list[tuple]] = {}
|
||||
self.n_pending = 0
|
||||
self.first_pending = 0.0
|
||||
self.memo_overlay: dict[tuple[str, str], tuple] = {}
|
||||
self.cache_overlay: dict[str, str] = {}
|
||||
self.stats = {"commits": 0, "rows": 0, "lock_wait_s": 0.0, "commit_s": 0.0}
|
||||
|
||||
def write(self, sql: str, args: tuple) -> None:
|
||||
if not self.n_pending:
|
||||
self.first_pending = time.monotonic()
|
||||
self.pending.setdefault(sql, []).append(args)
|
||||
self.n_pending += 1
|
||||
if self.n_pending >= self.max_ops or time.monotonic() - self.first_pending >= self.max_age:
|
||||
self.commit()
|
||||
|
||||
def write_many(self, sql: str, rows: list[tuple]) -> None:
|
||||
for r in rows:
|
||||
self.write(sql, r)
|
||||
|
||||
def execute(self, sql: str, args: Any = ()):
|
||||
"""Reads pass through; writes run immediately (after flushing the buffer)."""
|
||||
if sql.lstrip()[:7].upper().startswith(("INSERT", "UPDATE", "DELETE", "REPLACE")):
|
||||
self.commit()
|
||||
return self.conn.execute(sql, args)
|
||||
|
||||
def executescript(self, sql: str):
|
||||
self.commit()
|
||||
return self.conn.executescript(sql)
|
||||
|
||||
def commit(self) -> None:
|
||||
if not self.n_pending:
|
||||
return
|
||||
t0 = time.perf_counter()
|
||||
self.conn.execute("BEGIN IMMEDIATE")
|
||||
t1 = time.perf_counter()
|
||||
try:
|
||||
for sql, rows in self.pending.items():
|
||||
self.conn.executemany(sql, rows)
|
||||
self.conn.execute("COMMIT")
|
||||
except BaseException:
|
||||
self.conn.execute("ROLLBACK")
|
||||
raise
|
||||
self.stats["lock_wait_s"] += t1 - t0
|
||||
self.stats["commit_s"] += time.perf_counter() - t1
|
||||
self.stats["commits"] += 1
|
||||
self.stats["rows"] += self.n_pending
|
||||
self.pending, self.n_pending = {}, 0
|
||||
self.memo_overlay.clear()
|
||||
self.cache_overlay.clear()
|
||||
|
||||
def close(self) -> None:
|
||||
self.commit()
|
||||
self.conn.close()
|
||||
|
||||
|
||||
_OPEN: dict[str, list] = {} # resolved root -> [_BatchedDB, refcount]
|
||||
|
||||
|
||||
def _shared_db(root: Path) -> _BatchedDB:
|
||||
"""One connection per store per process: every Store object on the same root shares
|
||||
it, so buffered writes are visible to all of them and two connections in one thread
|
||||
can never wait on each other's write lock."""
|
||||
key = str(root.resolve()) if root.exists() else str(root.absolute())
|
||||
entry = _OPEN.get(key)
|
||||
if entry is None:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / "blobs").mkdir(exist_ok=True)
|
||||
key = str(root.resolve())
|
||||
conn = sqlite3.connect(root / "index.sqlite", isolation_level=None, check_same_thread=False)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
conn.execute("PRAGMA busy_timeout=30000")
|
||||
conn.executescript(SCHEMA)
|
||||
for stmt in MIGRATIONS:
|
||||
try:
|
||||
conn.execute(stmt)
|
||||
except sqlite3.OperationalError:
|
||||
pass # already applied
|
||||
entry = _OPEN[key] = [_BatchedDB(conn), 0]
|
||||
entry[1] += 1
|
||||
return entry[0]
|
||||
|
||||
|
||||
def _release_db(root: Path) -> None:
|
||||
key = str(root.resolve())
|
||||
entry = _OPEN.get(key)
|
||||
if entry is None:
|
||||
return
|
||||
entry[0].commit()
|
||||
entry[1] -= 1
|
||||
if entry[1] <= 0:
|
||||
_OPEN.pop(key, None)
|
||||
entry[0].close()
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, root: str | Path, *, readonly: bool = False):
|
||||
self.root = Path(root)
|
||||
self.readonly = readonly
|
||||
if readonly:
|
||||
if not (self.root / "index.sqlite").exists():
|
||||
from .errors import ConfigError
|
||||
|
||||
raise ConfigError(f"no pipewright store at {self.root}")
|
||||
conn = sqlite3.connect(f"file:{self.root / 'index.sqlite'}?mode=ro", uri=True, isolation_level=None,
|
||||
check_same_thread=False)
|
||||
conn.execute("PRAGMA busy_timeout=10000")
|
||||
self.db = _BatchedDB(conn)
|
||||
else:
|
||||
self.db = _shared_db(self.root)
|
||||
self._item_cache: dict[str, Item] = {}
|
||||
self._memo_pre: dict[str, dict[str, tuple]] = {}
|
||||
self.current_run: str | None = None
|
||||
"""Set by the engine: items stored while it is set record the run (-> graph) that made them."""
|
||||
|
||||
def commit(self) -> None:
|
||||
"""Make buffered writes visible to other processes now."""
|
||||
self.db.commit()
|
||||
|
||||
def close(self) -> None:
|
||||
if self.readonly:
|
||||
self.db.close()
|
||||
else:
|
||||
_release_db(self.root)
|
||||
|
||||
# ------------------------------------------------------------------ blobs
|
||||
def put_blob(self, data: bytes, media_type: str = "application/octet-stream", name: str | None = None) -> ArtifactRef:
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
path = self.root / "blobs" / sha[:2] / sha[2:]
|
||||
if not path.exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(f".tmp{random.randrange(1 << 30)}")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
return ArtifactRef(sha256=sha, size=len(data), media_type=media_type, name=name)
|
||||
|
||||
def get_blob(self, ref: ArtifactRef | str) -> bytes:
|
||||
sha = ref.sha256 if isinstance(ref, ArtifactRef) else ref
|
||||
return (self.root / "blobs" / sha[:2] / sha[2:]).read_bytes()
|
||||
|
||||
# ------------------------------------------------------------------ items
|
||||
def put_item(self, item: Item) -> None:
|
||||
if item.id in self._item_cache:
|
||||
return
|
||||
self.db.write(
|
||||
"INSERT OR IGNORE INTO items (id, key, kind, provenance, producer, op, created, data, run_id) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
(item.id, item.key, item.kind, item.provenance, item.producer, item.op, time.time(),
|
||||
item.model_dump_json(), self.current_run),
|
||||
)
|
||||
if item.parents:
|
||||
self.db.write_many("INSERT OR IGNORE INTO lineage VALUES (?,?)", [(item.id, p) for p in item.parents])
|
||||
self._item_cache[item.id] = item
|
||||
|
||||
def get_item(self, item_id: str) -> Item | None:
|
||||
if item_id in self._item_cache:
|
||||
return self._item_cache[item_id]
|
||||
row = self.db.execute("SELECT data FROM items WHERE id=?", (item_id,)).fetchone()
|
||||
if not row and self.db.n_pending:
|
||||
self.db.commit() # stored by another Store object on this connection, not yet flushed
|
||||
row = self.db.execute("SELECT data FROM items WHERE id=?", (item_id,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
item = Item.model_validate_json(row[0])
|
||||
self._item_cache[item_id] = item
|
||||
return item
|
||||
|
||||
def get_items(self, ids: Iterable[str]) -> list[Item]:
|
||||
out = []
|
||||
for i in ids:
|
||||
item = self.get_item(i)
|
||||
if item is None:
|
||||
raise KeyError(f"item {i} missing from store")
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
def find_items(self, prefix: str, limit: int = 10) -> list[str]:
|
||||
self.db.commit()
|
||||
return [r[0] for r in self.db.execute("SELECT id FROM items WHERE id LIKE ? LIMIT ?", (prefix + "%", limit))]
|
||||
|
||||
def lineage(self, item_id: str, depth: int = 50) -> list[Item]:
|
||||
"""The item and all its ancestors, nearest first."""
|
||||
seen, order, frontier = set(), [], [item_id]
|
||||
while frontier and depth > 0:
|
||||
nxt = []
|
||||
for i in frontier:
|
||||
if i in seen:
|
||||
continue
|
||||
seen.add(i)
|
||||
item = self.get_item(i)
|
||||
if item is not None:
|
||||
order.append(item)
|
||||
nxt.extend(item.parents)
|
||||
frontier, depth = nxt, depth - 1
|
||||
return order
|
||||
|
||||
def children(self, item_id: str) -> list[str]:
|
||||
self.db.commit()
|
||||
return [r[0] for r in self.db.execute("SELECT child FROM lineage WHERE parent=?", (item_id,))]
|
||||
|
||||
def descendants(self, item_id: str, limit: int = 100_000) -> list[str]:
|
||||
"""Every item derived (transitively) from `item_id`, breadth first."""
|
||||
seen: set[str] = {item_id}
|
||||
order: list[str] = []
|
||||
frontier = [item_id]
|
||||
while frontier and len(order) < limit:
|
||||
nxt = []
|
||||
for i in frontier:
|
||||
for c in self.children(i):
|
||||
if c not in seen:
|
||||
seen.add(c)
|
||||
order.append(c)
|
||||
nxt.append(c)
|
||||
frontier = nxt
|
||||
return order
|
||||
|
||||
def roots(self, item_id: str) -> list[Item]:
|
||||
"""The root ancestors (items without parents) of `item_id`."""
|
||||
return [i for i in self.lineage(item_id, depth=1000) if not i.parents]
|
||||
|
||||
def item_origin(self, item_id: str) -> dict:
|
||||
"""Which run (and graph) first stored an item."""
|
||||
self.db.commit()
|
||||
row = self.db.execute("SELECT i.run_id, r.graph FROM items i LEFT JOIN runs r ON r.run_id = i.run_id "
|
||||
"WHERE i.id=?", (item_id,)).fetchone()
|
||||
return {"run_id": row[0], "graph": row[1]} if row else {}
|
||||
|
||||
def resolve_item(self, ref: str) -> str | None:
|
||||
"""An item id from an id, a unique id prefix, or a key (the first stored item with
|
||||
that key, i.e. the root of the chain that inherited it)."""
|
||||
self.db.commit()
|
||||
if self.get_item(ref) is not None:
|
||||
return ref
|
||||
m = self.find_items(ref, limit=2)
|
||||
if len(m) == 1:
|
||||
return m[0]
|
||||
row = self.db.execute("SELECT id FROM items WHERE key=? ORDER BY created, rowid LIMIT 1", (ref,)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
# ------------------------------------------------------------------ queries over results
|
||||
def select_runs(self, graph: str | None, run: str = "latest", exclude: str | None = None) -> list[str]:
|
||||
"""Run ids for a run selector: `latest` / `previous` (latest finished non-preview run,
|
||||
excluding `exclude`), `all` (every non-preview run but `exclude`), or a run id /
|
||||
unique prefix."""
|
||||
q = "SELECT run_id, status FROM runs WHERE mode != 'preview'"
|
||||
args: list[Any] = []
|
||||
if graph:
|
||||
q += " AND graph=?"
|
||||
args.append(graph)
|
||||
rows = [(r[0], r[1]) for r in self.db.execute(q + " ORDER BY started DESC", args) if r[0] != exclude]
|
||||
if run in ("latest", "previous"):
|
||||
return [r for r, st in rows if st in DONE_STATUSES][:1]
|
||||
if run.startswith("group:"):
|
||||
return self.group_runs(run.removeprefix("group:"), graph)
|
||||
if run == "all":
|
||||
return [r for r, _ in rows]
|
||||
exact = [r for r, _ in rows if r == run] or [r for r, _ in rows if r.startswith(run)]
|
||||
if not exact:
|
||||
row = self.db.execute("SELECT run_id FROM runs WHERE run_id=? OR run_id LIKE ?", (run, run + "%")).fetchone()
|
||||
exact = [row[0]] if row else []
|
||||
return exact[:1]
|
||||
|
||||
def group_runs(self, group: str, graph: str | None = None) -> list[str]:
|
||||
"""Runs labelled with run group `group` (e.g. the shards of one logical run)."""
|
||||
q = "SELECT run_id FROM runs WHERE json_extract(spec, '$.group') = ?"
|
||||
args: list[Any] = [group]
|
||||
if graph:
|
||||
q += " AND graph=?"
|
||||
args.append(graph)
|
||||
return [r[0] for r in self.db.execute(q + " ORDER BY started", args)]
|
||||
|
||||
def query(self, *, graph: str | None = None, node: str | None = None, port: str | None = None,
|
||||
run: str = "latest", exclude_run: str | None = None, kind: str | None = None,
|
||||
provenance: str | None = None, labels: dict | None = None, where: str | None = None,
|
||||
derived_from: str | None = None, limit: int | None = None) -> list[Item]:
|
||||
"""Select stored results: items that flowed out of `node[.port]` in the selected
|
||||
run(s) of `graph` (or, without `node`, every item those runs stored), filtered by
|
||||
kind, provenance, label equality, an expression and lineage (`derived_from`: an
|
||||
item id/prefix/key whose descendants to keep)."""
|
||||
self.db.commit()
|
||||
from .expr import eval_item
|
||||
|
||||
run_ids = self.select_runs(graph, run, exclude_run)
|
||||
if not run_ids:
|
||||
return []
|
||||
marks = ",".join("?" * len(run_ids))
|
||||
if node:
|
||||
q = f"SELECT item_id FROM flows WHERE run_id IN ({marks}) AND node=?"
|
||||
args: list[Any] = [*run_ids, node]
|
||||
if port:
|
||||
q += " AND port=?"
|
||||
args.append(port)
|
||||
else:
|
||||
q += " AND port NOT LIKE '\\_\\_%' ESCAPE '\\'"
|
||||
q += " ORDER BY rowid"
|
||||
else:
|
||||
q = f"SELECT id FROM items WHERE run_id IN ({marks}) ORDER BY created"
|
||||
args = list(run_ids)
|
||||
ids = list(dict.fromkeys(r[0] for r in self.db.execute(q, args)))
|
||||
keep: set[str] | None = None
|
||||
if derived_from:
|
||||
root = self.resolve_item(derived_from)
|
||||
keep = set(self.descendants(root)) | {root} if root else set()
|
||||
out: list[Item] = []
|
||||
for i in ids:
|
||||
if keep is not None and i not in keep:
|
||||
continue
|
||||
it = self.get_item(i)
|
||||
if it is None:
|
||||
continue
|
||||
if kind and it.kind != kind:
|
||||
continue
|
||||
if provenance and it.provenance != provenance:
|
||||
continue
|
||||
if labels and any(it.labels.get(k) != v for k, v in labels.items()):
|
||||
continue
|
||||
if where and not eval_item(where, it):
|
||||
continue
|
||||
out.append(it)
|
||||
if limit is not None and len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
def copy_from(self, other: "Store", item_ids: Iterable[str], depth: int = 1000) -> None:
|
||||
"""Copy items (with their ancestors and artifact blobs) from another store."""
|
||||
for item in [a for i in item_ids for a in other.lineage(i, depth)]:
|
||||
if self.get_item(item.id) is not None:
|
||||
continue
|
||||
for ref in item.artifacts.values():
|
||||
dst = self.root / "blobs" / ref.sha256[:2] / ref.sha256[2:]
|
||||
if not dst.exists():
|
||||
try:
|
||||
self.put_blob(other.get_blob(ref), ref.media_type, ref.name)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
self.put_item(item)
|
||||
|
||||
# ------------------------------------------------------------------ memo
|
||||
def memo_preload(self, sig: str) -> int:
|
||||
"""Load every memo entry of a node signature in one query (replays then cost no
|
||||
per-item lookups). Returns the number of entries."""
|
||||
self.db.commit()
|
||||
self._memo_pre[sig] = {r[0]: tuple(r[1:]) for r in self.db.execute(
|
||||
"SELECT input_key, status, outputs, error, run_id, duration FROM memo WHERE sig=?", (sig,))}
|
||||
return len(self._memo_pre[sig])
|
||||
|
||||
def memo_get(self, sig: str, input_key: str) -> MemoEntry | None:
|
||||
row = self.db.memo_overlay.get((sig, input_key))
|
||||
if row is None:
|
||||
pre = self._memo_pre.get(sig)
|
||||
if pre is not None:
|
||||
row = pre.get(input_key)
|
||||
else:
|
||||
row = self.db.execute("SELECT status, outputs, error, run_id, duration FROM memo "
|
||||
"WHERE sig=? AND input_key=?", (sig, input_key)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return MemoEntry(row[0], json.loads(row[1] or "{}"), json.loads(row[2]) if row[2] else None, row[3], row[4])
|
||||
|
||||
def memo_put(self, sig: str, input_key: str, node: str, status: str, outputs: dict[str, list[str]],
|
||||
error: dict | None, run_id: str, duration: float) -> None:
|
||||
out_j, err_j = json.dumps(outputs), json.dumps(error) if error else None
|
||||
self.db.write("INSERT OR REPLACE INTO memo VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
(sig, input_key, node, status, out_j, err_j, run_id, time.time(), duration))
|
||||
self.db.memo_overlay[(sig, input_key)] = (status, out_j, err_j, run_id, duration)
|
||||
if sig in self._memo_pre:
|
||||
self._memo_pre[sig][input_key] = (status, out_j, err_j, run_id, duration)
|
||||
|
||||
def memo_delete(self, sig: str, input_key: str | None = None) -> int:
|
||||
self.db.commit()
|
||||
self._memo_pre.pop(sig, None)
|
||||
if input_key is None:
|
||||
return self.db.execute("DELETE FROM memo WHERE sig=?", (sig,)).rowcount
|
||||
return self.db.execute("DELETE FROM memo WHERE sig=? AND input_key=?", (sig, input_key)).rowcount
|
||||
|
||||
# ------------------------------------------------------------------ runs
|
||||
def begin_run(self, run_id: str, graph: str, graph_hash: str, mode: str, spec: dict) -> None:
|
||||
self.db.execute(
|
||||
"INSERT OR REPLACE INTO runs VALUES (?,?,?,?,?,?,?,?,?)",
|
||||
(run_id, graph, graph_hash, mode, "running", time.time(), None, json.dumps(spec), "{}"),
|
||||
)
|
||||
self.commit()
|
||||
|
||||
def update_run(self, run_id: str, *, status: str | None = None, stats: dict | None = None,
|
||||
finished: bool = False) -> None:
|
||||
if stats is not None:
|
||||
self.db.execute("UPDATE runs SET stats=? WHERE run_id=?", (json.dumps(stats), run_id))
|
||||
if status is not None:
|
||||
self.db.execute("UPDATE runs SET status=? WHERE run_id=?", (status, run_id))
|
||||
if finished:
|
||||
self.db.execute("UPDATE runs SET finished=? WHERE run_id=?", (time.time(), run_id))
|
||||
self.commit()
|
||||
|
||||
def runs(self, graph: str | None = None, limit: int = 20) -> list[dict]:
|
||||
q = "SELECT run_id, graph, graph_hash, mode, status, started, finished, stats FROM runs"
|
||||
args: tuple = ()
|
||||
if graph:
|
||||
q += " WHERE graph=?"
|
||||
args = (graph,)
|
||||
q += " ORDER BY started DESC LIMIT ?"
|
||||
rows = self.db.execute(q, (*args, limit)).fetchall()
|
||||
return [
|
||||
{"run_id": r[0], "graph": r[1], "graph_hash": r[2], "mode": r[3], "status": r[4], "started": r[5],
|
||||
"finished": r[6], "stats": json.loads(r[7] or "{}")}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def run(self, run_id: str) -> dict | None:
|
||||
row = self.db.execute(
|
||||
"SELECT run_id, graph, graph_hash, mode, status, started, finished, stats, spec FROM runs WHERE run_id=?",
|
||||
(run_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {"run_id": row[0], "graph": row[1], "graph_hash": row[2], "mode": row[3], "status": row[4],
|
||||
"started": row[5], "finished": row[6], "stats": json.loads(row[7] or "{}"),
|
||||
"spec": json.loads(row[8] or "{}")}
|
||||
|
||||
def latest_run(self, graph: str | None = None, mode: str | None = None) -> dict | None:
|
||||
q = "SELECT run_id FROM runs WHERE 1=1"
|
||||
args: list[Any] = []
|
||||
if graph:
|
||||
q += " AND graph=?"
|
||||
args.append(graph)
|
||||
if mode:
|
||||
q += " AND mode=?"
|
||||
args.append(mode)
|
||||
row = self.db.execute(q + " ORDER BY started DESC LIMIT 1", args).fetchone()
|
||||
return self.run(row[0]) if row else None
|
||||
|
||||
# ------------------------------------------------------------------ flows & events
|
||||
def record_flow(self, run_id: str, node: str, port: str, item_id: str) -> None:
|
||||
self.db.write("INSERT OR IGNORE INTO flows VALUES (?,?,?,?)", (run_id, node, port, item_id))
|
||||
|
||||
def record_event(self, run_id: str, node: str, input_key: str, status: str, cached: bool,
|
||||
error: dict | None = None) -> None:
|
||||
self.db.write(
|
||||
"INSERT OR REPLACE INTO events VALUES (?,?,?,?,?,?,?,?)",
|
||||
(run_id, node, input_key, status, int(cached), (error or {}).get("category"),
|
||||
(error or {}).get("message"), time.time()),
|
||||
)
|
||||
|
||||
def flow_counts(self, run_id: str) -> dict[tuple[str, str], int]:
|
||||
self.db.commit()
|
||||
rows = self.db.execute(
|
||||
"SELECT node, port, COUNT(*) FROM flows WHERE run_id=? GROUP BY node, port", (run_id,)
|
||||
).fetchall()
|
||||
return {(r[0], r[1]): r[2] for r in rows}
|
||||
|
||||
def event_counts(self, run_id: str) -> dict[str, dict[str, int]]:
|
||||
self.db.commit()
|
||||
out: dict[str, dict[str, int]] = {}
|
||||
for node, status, cached, cat, n in self.db.execute(
|
||||
"SELECT node, status, cached, category, COUNT(*) FROM events WHERE run_id=? "
|
||||
"GROUP BY node, status, cached, category", (run_id,)
|
||||
):
|
||||
d = out.setdefault(node, {})
|
||||
key = status if status != "error" else f"error:{cat}"
|
||||
d[key] = d.get(key, 0) + n
|
||||
if cached:
|
||||
d["cached"] = d.get("cached", 0) + n
|
||||
return out
|
||||
|
||||
def errors(self, run_id: str, node: str | None = None, limit: int = 50) -> list[dict]:
|
||||
self.db.commit()
|
||||
q = "SELECT node, input_key, category, message FROM events WHERE run_id=? AND status='error'"
|
||||
args: list[Any] = [run_id]
|
||||
if node:
|
||||
q += " AND node=?"
|
||||
args.append(node)
|
||||
return [{"node": r[0], "input": r[1], "category": r[2], "message": r[3]}
|
||||
for r in self.db.execute(q + " LIMIT ?", (*args, limit))]
|
||||
|
||||
def flow_items(self, run_id: str, node: str, port: str | None = None, limit: int | None = None,
|
||||
sample: bool = False, seed: int = 0) -> list[str]:
|
||||
self.db.commit()
|
||||
q = "SELECT item_id FROM flows WHERE run_id=? AND node=?"
|
||||
args: list[Any] = [run_id, node]
|
||||
if port:
|
||||
q += " AND port=?"
|
||||
args.append(port)
|
||||
ids = [r[0] for r in self.db.execute(q + " ORDER BY rowid", args)]
|
||||
if sample and limit is not None and len(ids) > limit:
|
||||
ids = random.Random(seed).sample(ids, limit)
|
||||
elif limit is not None:
|
||||
ids = ids[:limit]
|
||||
return ids
|
||||
|
||||
# ------------------------------------------------------------------ usage
|
||||
def record_usage(self, run_id: str, node: str, item_id: str | None, alias: str, provider: str, model: str,
|
||||
input_tokens: int, output_tokens: int, cost: float | None, cached: bool) -> None:
|
||||
self.db.write(
|
||||
"INSERT INTO usage VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(run_id, node, item_id, alias, provider, model, input_tokens, output_tokens, cost, int(cached), time.time()),
|
||||
)
|
||||
|
||||
def usage_summary(self, run_id: str) -> list[dict]:
|
||||
self.db.commit()
|
||||
rows = self.db.execute(
|
||||
"SELECT node, alias, model, SUM(cached), COUNT(*), SUM(input_tokens), SUM(output_tokens), SUM(cost) "
|
||||
"FROM usage WHERE run_id=? GROUP BY node, alias, model", (run_id,)
|
||||
).fetchall()
|
||||
return [{"node": r[0], "alias": r[1], "model": r[2], "cached_calls": r[3], "calls": r[4],
|
||||
"input_tokens": r[5] or 0, "output_tokens": r[6] or 0, "cost_usd": r[7]} for r in rows]
|
||||
|
||||
# ------------------------------------------------------------------ request cache
|
||||
def cache_get(self, key: str) -> dict | None:
|
||||
hit = self.db.cache_overlay.get(key)
|
||||
if hit is not None:
|
||||
return json.loads(hit)
|
||||
row = self.db.execute("SELECT response FROM request_cache WHERE key=?", (key,)).fetchone()
|
||||
return json.loads(row[0]) if row else None
|
||||
|
||||
def cache_put(self, key: str, response: dict) -> None:
|
||||
j = json.dumps(response)
|
||||
self.db.write("INSERT OR REPLACE INTO request_cache VALUES (?,?,?)", (key, j, time.time()))
|
||||
self.db.cache_overlay[key] = j
|
||||
|
||||
# ------------------------------------------------------------------ reviews
|
||||
def set_review(self, node: str, item_id: str, decision: str, note: str = "") -> None:
|
||||
self.db.execute("INSERT OR REPLACE INTO reviews VALUES (?,?,?,?,?)", (node, item_id, decision, note, time.time()))
|
||||
self.commit()
|
||||
|
||||
def get_review(self, node: str, item_id: str) -> tuple[str, str] | None:
|
||||
row = self.db.execute("SELECT decision, note FROM reviews WHERE node=? AND item_id=?", (node, item_id)).fetchone()
|
||||
return (row[0], row[1]) if row else None
|
||||
@@ -0,0 +1,53 @@
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
os.environ.setdefault("PW_BACKOFF_SCALE", "0.01")
|
||||
|
||||
|
||||
def pytest_addoption(parser):
|
||||
parser.addoption("--live", action="store_true", help="run tests against the real provider (Morph)")
|
||||
parser.addoption("--docker", action="store_true", help="run tests that need a Docker daemon")
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
for item in items:
|
||||
if "live" in item.keywords and not config.getoption("--live"):
|
||||
item.add_marker(pytest.mark.skip(reason="needs --live"))
|
||||
if "docker" in item.keywords and not (config.getoption("--docker") or os.environ.get("PW_TEST_DOCKER")):
|
||||
item.add_marker(pytest.mark.skip(reason="needs --docker"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_project(tmp_path):
|
||||
"""Write a project file (dict) into tmp_path and return the Project."""
|
||||
from pipewright.project import Project
|
||||
|
||||
def make(cfg: dict | None = None, name: str = "pipewright.yaml"):
|
||||
cfg = {"store": ".pipewright", **(cfg or {})}
|
||||
(tmp_path / name).write_text(yaml.safe_dump(cfg))
|
||||
return Project.load(tmp_path / name)
|
||||
|
||||
return make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def example(tmp_path):
|
||||
"""Copy an example directory into tmp_path; returns its path."""
|
||||
|
||||
def copy(name: str) -> Path:
|
||||
dst = tmp_path / name
|
||||
shutil.copytree(ROOT / "examples" / name, dst,
|
||||
ignore=shutil.ignore_patterns(".pipewright*", "out", "__pycache__"))
|
||||
return dst
|
||||
|
||||
return copy
|
||||
|
||||
|
||||
FAKE = {"providers": {"fake": {"type": "fake"}}, "models": {"m": {"provider": "fake", "model": "fake-m"}}}
|
||||
Executable
+77
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
# ruff: noqa: E702
|
||||
"""A fake `docker` CLI for host-pool tests: containers are directories, `exec` runs
|
||||
locally. State lives under $FAKE_DOCKER_ROOT. Records every invocation (with -H)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(os.environ["FAKE_DOCKER_ROOT"])
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
args = sys.argv[1:]
|
||||
host = "local"
|
||||
if args[:1] == ["-H"]:
|
||||
host, args = args[1], args[2:]
|
||||
with open(root / "calls.jsonl", "a") as f:
|
||||
f.write(json.dumps({"host": host, "args": args}) + "\n")
|
||||
hdir = root / "hosts" / host.replace("/", "_").replace(":", "_")
|
||||
hdir.mkdir(parents=True, exist_ok=True)
|
||||
imgs_file = hdir / "images"
|
||||
images = set(imgs_file.read_text().split()) if imgs_file.exists() else set()
|
||||
|
||||
|
||||
def save_images():
|
||||
imgs_file.write_text("\n".join(sorted(images)))
|
||||
|
||||
|
||||
cmd = args[0]
|
||||
if cmd == "info":
|
||||
print(os.environ.get("FAKE_DOCKER_INFO", "4 8589934592"))
|
||||
elif cmd == "image" and args[1] == "inspect":
|
||||
sys.exit(0 if args[-1] in images else 1)
|
||||
elif cmd == "image" and args[1] == "ls":
|
||||
print("\n".join(sorted(images)))
|
||||
elif cmd == "pull":
|
||||
images.add(args[-1]); save_images()
|
||||
elif cmd == "build":
|
||||
images.add(args[args.index("-t") + 1]); save_images()
|
||||
elif cmd == "load":
|
||||
sys.stdin.buffer.read(); images.add("loaded:latest"); save_images()
|
||||
elif cmd == "tag":
|
||||
images.add(args[2]); save_images()
|
||||
elif cmd == "run":
|
||||
name = args[args.index("--name") + 1]
|
||||
if os.environ.get("FAKE_DOCKER_AUTO_PULL", "1") == "1":
|
||||
images.add(args[-3]); save_images()
|
||||
c = root / "containers" / name
|
||||
(c / "workspace").mkdir(parents=True)
|
||||
(c / "meta.json").write_text(json.dumps({"host": host, "args": args}))
|
||||
print(name)
|
||||
elif cmd == "exec":
|
||||
i, env = 1, dict(os.environ)
|
||||
workdir = "/workspace"
|
||||
while args[i].startswith("-"):
|
||||
if args[i] == "-e":
|
||||
k, _, v = args[i + 1].partition("="); env[k] = v; i += 2
|
||||
elif args[i] == "-w":
|
||||
workdir = args[i + 1]; i += 2
|
||||
else:
|
||||
i += 1
|
||||
name, rest = args[i], args[i + 1:]
|
||||
c = root / "containers" / name
|
||||
if not c.exists():
|
||||
print(f"Error: No such container: {name}", file=sys.stderr); sys.exit(125)
|
||||
rest = [a.replace("/workspace", str(c / "workspace")) for a in rest]
|
||||
cwd = str(c) + workdir
|
||||
os.makedirs(cwd, exist_ok=True)
|
||||
r = subprocess.run(rest, cwd=cwd, env=env, stdin=sys.stdin)
|
||||
sys.exit(r.returncode)
|
||||
elif cmd == "rm":
|
||||
shutil.rmtree(root / "containers" / args[-1], ignore_errors=True)
|
||||
else:
|
||||
print(f"fake docker: unsupported {args}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Scripted fake-model responses used by tests."""
|
||||
|
||||
STATE = {"calls": 0}
|
||||
|
||||
|
||||
def invalid_then_valid(payload):
|
||||
STATE["calls"] += 1
|
||||
if STATE["calls"] == 1:
|
||||
return {"content": "sorry, no JSON today"}
|
||||
return {"content": '{"c": "x"}'}
|
||||
@@ -0,0 +1,56 @@
|
||||
import json
|
||||
|
||||
from pipewright.cli import main
|
||||
|
||||
|
||||
def run_cli(capsys, *args):
|
||||
code = main(list(args))
|
||||
out = capsys.readouterr().out
|
||||
return code, json.loads(out) if "--json" in args else out
|
||||
|
||||
|
||||
def test_cli_end_to_end(example, capsys, tmp_path):
|
||||
d = example("issue_triage")
|
||||
g = str(d / "graph.yaml")
|
||||
assert main(["convert", str(d / "graph.py"), g]) == 0
|
||||
capsys.readouterr()
|
||||
code, nodes = run_cli(capsys, "nodes", "list", "--json")
|
||||
assert code == 0 and any(n["type"] == "llm.label" for n in nodes)
|
||||
code, desc = run_cli(capsys, "nodes", "describe", "route.expr", "--json")
|
||||
assert desc["kind"] == "route" and "routes" in desc["params_schema"]["properties"]
|
||||
code, chk = run_cli(capsys, "check", g, "--json")
|
||||
assert code == 0 and chk["ok"]
|
||||
|
||||
code, prev = run_cli(capsys, "preview", g, "--upto", "heuristics", "-n", "2", "--json", "--quiet")
|
||||
assert code == 0 and len(prev["items"]) == 2 and "has_traceback" in prev["items"][0]["labels"]
|
||||
|
||||
bad = json.dumps([{"op": "set_param", "node": "route", "path": "routes.urgent", "value": "labels.severty >"}])
|
||||
code, res = run_cli(capsys, "patch", g, bad, "--json")
|
||||
assert code == 1 and not res["written"]
|
||||
good = json.dumps([{"op": "add_node", "id": "short", "type": "sink.jsonl", "inputs": {"in": "substantive.rejected"},
|
||||
"params": {"path": "out/short.jsonl"}}])
|
||||
code, res = run_cli(capsys, "patch", g, good, "--json")
|
||||
assert code == 0 and res["written"]
|
||||
|
||||
code, run = run_cli(capsys, "run", g, "--json", "--quiet")
|
||||
assert code == 0 and run["status"] == "completed"
|
||||
code, fun = run_cli(capsys, "funnel", g, "--json")
|
||||
assert {"from": "substantive.rejected", "to": "short.in", "items": 2} in fun["edges"]
|
||||
code, st = run_cli(capsys, "status", g, "--json")
|
||||
assert st["run"]["status"] == "completed" and st["usage"][0]["calls"] == 10
|
||||
code, its = run_cli(capsys, "items", g, "route", "--port", "urgent", "-n", "2", "--json")
|
||||
assert its["total"] == 5 and len(its["items"]) == 2
|
||||
code, lin = run_cli(capsys, "lineage", g, its["items"][0]["id"][:10], "--json")
|
||||
assert [x["producer"] for x in lin["lineage"]][:3] == ["classify", "heuristics", "issues"]
|
||||
out = tmp_path / "x.jsonl"
|
||||
code, ex = run_cli(capsys, "export", g, "classify", "-o", str(out), "--fields", "key,labels.category", "--json")
|
||||
assert ex["rows"] == 10 and out.read_text().count("\n") == 10
|
||||
code, rep = run_cli(capsys, "report", g, "--json")
|
||||
assert rep["path"].endswith(".html")
|
||||
code, err = run_cli(capsys, "check", str(tmp_path / "missing.yaml"), "--json")
|
||||
assert code == 2 and "not found" in err["error"]
|
||||
|
||||
|
||||
def test_patch_schema(capsys):
|
||||
assert main(["patch", "--schema"]) == 0
|
||||
assert "add_node" in capsys.readouterr().out
|
||||
@@ -0,0 +1,225 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright import Graph, NodeType, register_node
|
||||
from pipewright.engine import Engine, RunOptions
|
||||
from pipewright.errors import InfraError
|
||||
from pipewright.store import Store
|
||||
|
||||
from conftest import FAKE
|
||||
|
||||
CALLS: dict[str, int] = {}
|
||||
|
||||
|
||||
@register_node
|
||||
class Flaky(NodeType):
|
||||
"""Fails with InfraError the first `fail` times per key, then passes."""
|
||||
|
||||
name = "test.flaky"
|
||||
kind = "map"
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Params(BaseModel):
|
||||
fail: int = 1
|
||||
mode: str = "infra"
|
||||
|
||||
async def process(self, item, ctx):
|
||||
n = CALLS[item.key] = CALLS.get(item.key, 0) + 1
|
||||
if n <= self.params.fail:
|
||||
if self.params.mode == "infra":
|
||||
raise InfraError("box died")
|
||||
raise ValueError("bad item")
|
||||
return item.derive(update_labels={"calls": n})
|
||||
|
||||
|
||||
def records(n):
|
||||
return [{"id": f"r{i}", "body": "word " * (i + 1)} for i in range(n)]
|
||||
|
||||
|
||||
def graph(recs, expr="labels.words > 2", model="m"):
|
||||
g = Graph("eng")
|
||||
src = g.add("src", "source.inline", kind="doc", records=recs)
|
||||
lab = g.add("words", "label.expr", input=src, labels={"words": "words(payload.body)"})
|
||||
keep = g.add("keep", "filter.expr", input=lab, expr=expr)
|
||||
llm = g.add("llm", "llm.generate", input=keep, model=model, prompt="Summarize {{ payload.body }}",
|
||||
output_field="summary")
|
||||
g.add("sink", "sink.jsonl", input=llm, path="out/x.jsonl", mode="rewrite")
|
||||
return g.to_spec()
|
||||
|
||||
|
||||
def run(spec, proj, **opts):
|
||||
store = Store(proj.store_dir)
|
||||
try:
|
||||
return asyncio.run(Engine(spec, proj, store).run(RunOptions(**opts)))
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
def ev(summary, node):
|
||||
return summary["funnel"]["nodes"][node]["events"]
|
||||
|
||||
|
||||
def test_memoization_and_incremental(make_project):
|
||||
proj = make_project(FAKE)
|
||||
s1 = run(graph(records(4)), proj)
|
||||
assert s1["status"] == "completed"
|
||||
assert ev(s1, "llm") == {"ok": 2} # r2, r3 have >2 words
|
||||
s2 = run(graph(records(4)), proj)
|
||||
assert ev(s2, "llm") == {"ok": 2, "cached": 2} and ev(s2, "words")["cached"] == 4
|
||||
# new inputs: only they are processed
|
||||
s3 = run(graph(records(6)), proj)
|
||||
assert ev(s3, "words") == {"ok": 6, "cached": 4} and ev(s3, "llm") == {"ok": 4, "cached": 2}
|
||||
# changing a node's params invalidates it and (where outputs change) downstream
|
||||
s4 = run(graph(records(6), expr="labels.words > 4"), proj)
|
||||
assert ev(s4, "words")["cached"] == 6 and "cached" not in ev(s4, "keep")
|
||||
assert ev(s4, "llm") == {"ok": 2, "cached": 2} # same items reach llm -> still memoized
|
||||
assert (proj.base_dir / "out/x.jsonl").read_text().count("\n") == 2
|
||||
usage = {u["node"]: u for u in s1["usage"]}
|
||||
assert usage["llm"]["calls"] == 2
|
||||
|
||||
|
||||
def test_model_alias_change_invalidates(make_project, tmp_path):
|
||||
proj = make_project({**FAKE, "models": {"m": {"provider": "fake", "model": "fake-m"},
|
||||
"m2": {"provider": "fake", "model": "fake-m2"}}})
|
||||
run(graph(records(4)), proj)
|
||||
s = run(graph(records(4), model="m2"), proj)
|
||||
assert ev(s, "llm") == {"ok": 2}
|
||||
|
||||
|
||||
def test_upto_and_limit(make_project):
|
||||
proj = make_project(FAKE)
|
||||
s = run(graph(records(10)), proj, upto="keep", limit=3, mode="preview")
|
||||
assert set(s["funnel"]["nodes"]["src"]["out"].values()) == {3}
|
||||
assert ev(s, "llm") == {} and not (proj.base_dir / "out/x.jsonl").exists()
|
||||
|
||||
|
||||
def test_transient_errors_retried_and_not_memoized(make_project):
|
||||
CALLS.clear()
|
||||
proj = make_project(FAKE)
|
||||
g = Graph("flaky")
|
||||
src = g.add("src", "source.inline", kind="doc", records=records(2))
|
||||
g.add("f", "test.flaky", input=src, fail=1, retries={"infra": 0, "provider": 0, "node": 0})
|
||||
s1 = run(g.to_spec(), proj)
|
||||
assert s1["status"] == "completed_with_errors" and ev(s1, "f") == {"error:infra": 2}
|
||||
s2 = run(g.to_spec(), proj) # infra errors are not memoized: retried on the next run
|
||||
assert ev(s2, "f") == {"ok": 2}
|
||||
CALLS.clear()
|
||||
g2 = Graph("flaky2")
|
||||
src = g2.add("src", "source.inline", kind="doc", records=[{"id": "fresh1"}, {"id": "fresh2"}])
|
||||
g2.add("f", "test.flaky", input=src, fail=1, retries={"infra": 2})
|
||||
assert ev(run(g2.to_spec(), proj), "f") == {"ok": 2} # retried within the run
|
||||
|
||||
|
||||
def test_node_errors_memoized_unless_retry_errors(make_project):
|
||||
CALLS.clear()
|
||||
proj = make_project(FAKE)
|
||||
g = Graph("nodeerr")
|
||||
src = g.add("src", "source.inline", kind="doc", records=records(1))
|
||||
g.add("f", "test.flaky", input=src, fail=1, mode="node")
|
||||
assert ev(run(g.to_spec(), proj), "f") == {"error:node": 1}
|
||||
assert ev(run(g.to_spec(), proj), "f") == {"error:node": 1, "cached": 1}
|
||||
assert ev(run(g.to_spec(), proj, retry_errors=True), "f") == {"ok": 1}
|
||||
|
||||
|
||||
def test_provider_errors_inside_llm_node(make_project):
|
||||
proj = make_project({"providers": {"fake": {"type": "fake", "fail": {"first": 3, "status": 503}}},
|
||||
"models": {"m": {"provider": "fake", "model": "x", "max_retries": 0}}})
|
||||
spec = graph(records(4))
|
||||
spec.nodes["llm"].retries = None
|
||||
s = run(spec, proj)
|
||||
# 3 failing calls: each item gets its first call + 3 provider retries at node level -> both succeed
|
||||
assert ev(s, "llm") == {"ok": 2}
|
||||
|
||||
|
||||
def test_budget_stops_run(make_project):
|
||||
proj = make_project({**FAKE, "budgets": {"input_tokens": 1}})
|
||||
s = run(graph(records(6)), proj)
|
||||
assert s["status"] == "budget_exceeded"
|
||||
assert ev(s, "llm").get("pending", 0) >= 1
|
||||
|
||||
|
||||
def test_review_flow(make_project):
|
||||
from pipewright import ops
|
||||
|
||||
proj = make_project(FAKE)
|
||||
g = Graph("rev")
|
||||
src = g.add("src", "source.inline", kind="doc", records=records(3))
|
||||
rv = g.add("review", "review.manual", input=src, instructions="ok?", auto_reject="payload.id == 'r2'")
|
||||
g.add("sink", "sink.jsonl", input=rv.port("approved"), path="out/approved.jsonl")
|
||||
path = proj.base_dir / "rev.yaml"
|
||||
g.save(path)
|
||||
s1 = run(g.to_spec(), proj)
|
||||
assert s1["funnel"]["nodes"]["review"]["parked"] == 2
|
||||
parked = ops.review_list(path, "review")["parked"]
|
||||
ops.review_decide(path, "review", [parked[0]["id"][:10]], "approved")
|
||||
s2 = run(g.to_spec(), proj)
|
||||
assert s2["funnel"]["nodes"]["review"]["out"] == {"approved": 1, "rejected": 1}
|
||||
|
||||
|
||||
def test_retry_loop_and_join(make_project):
|
||||
from pipewright.registry import register_node as reg
|
||||
|
||||
@reg
|
||||
class Fix(NodeType):
|
||||
name = "test.fix"
|
||||
kind = "map"
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return item.derive(update_payload={"v": item.payload["v"] + 1})
|
||||
|
||||
proj = make_project(FAKE)
|
||||
g = Graph("loop")
|
||||
src = g.add("src", "source.inline", kind="n", records=[{"id": "a", "v": 0}, {"id": "b", "v": 5}, {"id": "c", "v": -9}])
|
||||
loop = g.add("loop", "retry.loop", input=src, max_rounds=3,
|
||||
check={"type": "filter.expr", "params": {"expr": "payload.v >= 2"}},
|
||||
fix={"type": "test.fix", "params": {}})
|
||||
grp = g.add("all", "join.group", inputs={"in": [loop.port("out"), loop.port("exhausted")]}, by="'all'",
|
||||
aggregates={"n": ["count", "1"], "rounds": ["list", "labels.rounds"]})
|
||||
g.add("sink", "sink.jsonl", input=grp, path="out/g.jsonl")
|
||||
s = run(g.to_spec(), proj)
|
||||
assert s["funnel"]["nodes"]["loop"]["out"] == {"out": 2, "exhausted": 1}
|
||||
from pipewright import ops
|
||||
|
||||
path = proj.base_dir / "loop.yaml"
|
||||
g.save(path)
|
||||
out = ops.items(path, "all")["items"][0]
|
||||
assert out["labels"]["n"] == 3 and sorted(out["labels"]["rounds"]) == [1, 3, 3]
|
||||
s2 = run(g.to_spec(), proj)
|
||||
assert ev(s2, "loop")["cached"] == 3
|
||||
|
||||
|
||||
def test_cancellation_marks_run(make_project):
|
||||
proj = make_project({"providers": {"fake": {"type": "fake", "latency": 5}},
|
||||
"models": {"m": {"provider": "fake", "model": "x"}}})
|
||||
store = Store(proj.store_dir)
|
||||
|
||||
async def main():
|
||||
eng = Engine(graph(records(5)), proj, store)
|
||||
t = asyncio.create_task(eng.run())
|
||||
await asyncio.sleep(0.5)
|
||||
t.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await t
|
||||
return eng.run_id
|
||||
|
||||
rid = asyncio.run(main())
|
||||
assert store.run(rid)["status"] == "cancelled"
|
||||
store.close()
|
||||
|
||||
|
||||
def test_llm_label_errors_and_fresh_sample_on_retry(make_project):
|
||||
import fake_scripts
|
||||
|
||||
fake_scripts.STATE["calls"] = 0
|
||||
proj = make_project({"providers": {"fake": {"type": "fake", "script": "fake_scripts:invalid_then_valid"}},
|
||||
"models": {"m": {"provider": "fake", "model": "x"}}})
|
||||
g = Graph("lab")
|
||||
src = g.add("src", "source.inline", kind="doc", records=[{"id": "a", "body": "hello"}])
|
||||
g.add("lab", "llm.label", input=src, model="m", prompt="{{ payload.body }}", repair_attempts=0,
|
||||
labels={"c": {"type": "string", "enum": ["x", "y"]}})
|
||||
spec = g.to_spec()
|
||||
assert ev(run(spec, proj), "lab") == {"error:node": 1}
|
||||
assert ev(run(spec, proj), "lab") == {"error:node": 1, "cached": 1}
|
||||
s = run(spec, proj, retry_errors=True) # must not replay the cached bad answer
|
||||
assert ev(s, "lab") == {"ok": 1} and fake_scripts.STATE["calls"] == 2
|
||||
@@ -0,0 +1,64 @@
|
||||
"""The example pipelines double as integration tests (fake model, local/Docker sandboxes)."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright import ops
|
||||
|
||||
|
||||
def read_jsonl(path):
|
||||
return [json.loads(line) for line in path.read_text().splitlines()]
|
||||
|
||||
|
||||
def test_issue_triage(example):
|
||||
d = example("issue_triage")
|
||||
s = ops.run_graph(d / "graph.py")
|
||||
assert s["status"] == "completed"
|
||||
nodes = s["funnel"]["nodes"]
|
||||
assert nodes["issues"]["out"] == {"out": 12}
|
||||
assert nodes["substantive"]["out"] == {"out": 10, "rejected": 2}
|
||||
assert nodes["route"]["out"] == {"urgent": 5, "features": 3, "other": 2}
|
||||
urgent = read_jsonl(d / "out/urgent.jsonl")
|
||||
assert {r["key"] for r in urgent} == {"gh-101", "gh-104", "gh-107", "gh-109", "gh-112"}
|
||||
assert all(r["labels.category"] == "bug" for r in urgent)
|
||||
# second run is fully memoized
|
||||
s2 = ops.run_graph(d / "graph.py")
|
||||
assert s2["funnel"]["nodes"]["classify"]["events"] == {"ok": 10, "cached": 10}
|
||||
# the yaml form of the graph is equivalent
|
||||
ops.export_graph(d / "graph.py", d / "graph.yaml")
|
||||
s3 = ops.run_graph(d / "graph.yaml")
|
||||
assert s3["funnel"]["nodes"]["classify"]["events"]["cached"] == 10
|
||||
rep = ops.report(d / "graph.yaml")
|
||||
html = open(rep["path"]).read()
|
||||
assert "issue-triage" in html and "<svg" in html and "node-classify" in html
|
||||
|
||||
|
||||
def _check_coding(s, d):
|
||||
assert s["status"] == "completed", s["errors"]
|
||||
nodes = s["funnel"]["nodes"]
|
||||
assert nodes["synth"]["out"] == {"out": 4}
|
||||
assert nodes["valid"]["out"] == {"out": 3, "rejected": 1}
|
||||
assert nodes["probe"]["out"] == {"out": 6}
|
||||
assert nodes["bucket"]["out"] == {"too_easy": 1, "learnable": 1, "too_hard": 1}
|
||||
assert read_jsonl(d / "out/too_easy.jsonl")[0]["key"] == "add"
|
||||
assert read_jsonl(d / "out/learnable.jsonl")[0] == {"key": "classify", "labels.pass_rate": 0.5,
|
||||
"labels.rollouts": 2}
|
||||
assert read_jsonl(d / "out/invalid.jsonl")[0]["key"] == "broken_max"
|
||||
|
||||
|
||||
def test_coding_tasks_local(example):
|
||||
d = example("coding_tasks")
|
||||
s = ops.run_graph(d / "graph.py")
|
||||
_check_coding(s, d)
|
||||
s2 = ops.run_graph(d / "graph.py")
|
||||
assert s2["funnel"]["nodes"]["probe"]["events"] == {"ok": 6, "cached": 6}
|
||||
tr = ops.items(d / "graph.py", "probe", n=1)["items"][0]
|
||||
assert "trajectory" in tr["artifacts"] and tr["labels"]["agent_status"] == "completed"
|
||||
|
||||
|
||||
@pytest.mark.docker
|
||||
def test_coding_tasks_docker(example):
|
||||
d = example("coding_tasks")
|
||||
s = ops.run_graph(d / "graph.py", project=d / "pipewright.docker.yaml")
|
||||
_check_coding(s, d)
|
||||
@@ -0,0 +1,45 @@
|
||||
import pytest
|
||||
|
||||
from pipewright.expr import ExprError, check_expr, eval_item, render_item
|
||||
from pipewright.items import Item
|
||||
|
||||
IT = Item(key="gh-1", kind="issue", payload={"title": "Crash", "body": "Traceback: boom", "n": 3,
|
||||
"members": [{"labels": {"passed": True}}, {"labels": {"passed": False}}]},
|
||||
labels={"score": 0.5})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("src,expected", [
|
||||
("payload.n * 2", 6),
|
||||
("labels.score > 0.4 and kind == 'issue'", True),
|
||||
("re(r'traceback', payload.body)", True),
|
||||
("re_find(r'(\\w+)$', payload.body)", "boom"),
|
||||
("labels.missing or 7", 7),
|
||||
("mean([m.labels.passed for m in payload.members])", 0.5),
|
||||
("sum(1 for m in payload.members if m.labels.passed)", 1),
|
||||
("payload.title.lower().startswith('cr')", True),
|
||||
("{'a': payload.n}", {"a": 3}),
|
||||
("words(payload.body)", 2),
|
||||
("key.split('-')[1]", "1"),
|
||||
])
|
||||
def test_eval(src, expected):
|
||||
assert eval_item(src, IT) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("src", [
|
||||
"__import__('os')", "payload.__class__", "().__class__.__bases__", "open('/etc/passwd')",
|
||||
"'{0.__class__}'.format(1)", "lambda: 1", "[x for x in ().__class__.__mro__]",
|
||||
])
|
||||
def test_unsafe_rejected(src):
|
||||
with pytest.raises(ExprError):
|
||||
eval_item(src, IT)
|
||||
|
||||
|
||||
def test_check_expr_names():
|
||||
assert check_expr("labels.x > 1", {"labels"}) is None
|
||||
assert "unknown name" in check_expr("lables.x > 1", {"labels", "payload"})
|
||||
assert "syntax error" in check_expr("labels.x >", {"labels"})
|
||||
|
||||
|
||||
def test_render():
|
||||
assert render_item("T: {{ payload.title }} ({{ labels.score }})", IT) == "T: Crash (0.5)"
|
||||
assert render_item("{{ payload.missing }}|", IT) == "|"
|
||||
@@ -0,0 +1,129 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright import Graph, load_graph
|
||||
from pipewright.check import check
|
||||
from pipewright.errors import ConfigError
|
||||
from pipewright.nodes.builtin import FilterExpr
|
||||
from pipewright.patch import apply_ops, ops_schema
|
||||
from pipewright.registry import registry
|
||||
|
||||
from conftest import FAKE
|
||||
|
||||
|
||||
def small_graph() -> Graph:
|
||||
g = Graph("t")
|
||||
src = g.add("src", "source.inline", kind="issue", records=[{"id": "a", "body": "x" * 50}, {"id": "b", "body": "y"}])
|
||||
f = g.add("long", FilterExpr.Params(expr="len(payload.body) > 10"), input=src)
|
||||
g.add("lab", "llm.label", input=f, model="m", prompt="{{ payload.body }}",
|
||||
labels={"c": {"type": "string", "enum": ["x", "y"]}})
|
||||
g.add("out", "sink.jsonl", input="lab", path="out.jsonl")
|
||||
return g
|
||||
|
||||
|
||||
def codes(diags, level=None):
|
||||
return [d.code for d in diags if level is None or d.level == level]
|
||||
|
||||
|
||||
def test_builder_roundtrip(tmp_path):
|
||||
g = small_graph()
|
||||
g.save(tmp_path / "g.yaml")
|
||||
g.save(tmp_path / "g.json")
|
||||
a, b = load_graph(tmp_path / "g.yaml"), load_graph(tmp_path / "g.json")
|
||||
assert a == b == g.to_spec()
|
||||
assert a.nodes["lab"].inputs == {"in": ["long.out"]} or a.nodes["lab"].inputs == {"in": ["long"]}
|
||||
|
||||
|
||||
def test_builder_validates_params_early():
|
||||
g = Graph("t")
|
||||
from pydantic import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
g.add("x", "filter.expr", exprr="1")
|
||||
|
||||
|
||||
def test_clean_graph_checks_ok(make_project):
|
||||
proj = make_project(FAKE)
|
||||
diags = check(small_graph().to_spec(), proj)
|
||||
assert not codes(diags, "error"), [d.format() for d in diags]
|
||||
assert "PW014" in codes(diags) # budget estimate
|
||||
|
||||
|
||||
def test_check_finds_problems(make_project):
|
||||
proj = make_project(FAKE)
|
||||
spec = small_graph().to_spec()
|
||||
spec.nodes["lab"].type = "llm.lable"
|
||||
spec.nodes["out"].inputs = {"in": ["lab.outt"]}
|
||||
spec.nodes["long"].params["expr"] = "len(payload.body) >"
|
||||
diags = check(spec, proj)
|
||||
msgs = {d.code: d for d in diags if d.level == "error"}
|
||||
assert "llm.label" in msgs["PW001"].hint
|
||||
assert msgs["PW002"].node == "long"
|
||||
spec2 = small_graph().to_spec()
|
||||
spec2.nodes["lab"].params["model"] = "mm"
|
||||
spec2.nodes["out"].inputs = {"in": ["long.nope"]}
|
||||
d2 = {d.code: d for d in check(spec2, proj) if d.level == "error"}
|
||||
assert "PW011" in d2 and "'m'" in d2["PW011"].hint
|
||||
assert "PW004" in d2 and "out" in d2["PW004"].hint
|
||||
|
||||
|
||||
def test_check_kind_mismatch_cycle_and_required_input(make_project):
|
||||
from pipewright.nodes.base import NodeType, Port
|
||||
from pipewright.registry import register_node
|
||||
|
||||
@register_node
|
||||
class OnlyTasks(NodeType):
|
||||
name = "test.only_tasks"
|
||||
kind = "map"
|
||||
inputs = {"in": Port(kind="task")}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return item
|
||||
|
||||
proj = make_project(FAKE)
|
||||
spec = small_graph().to_spec()
|
||||
spec.nodes["lab"].type = "test.only_tasks"
|
||||
spec.nodes["lab"].params = {}
|
||||
assert "PW007" in codes(check(spec, proj), "error")
|
||||
spec = small_graph().to_spec()
|
||||
spec.nodes["long"].inputs = {"in": ["lab"]}
|
||||
assert "PW008" in codes(check(spec, proj), "error")
|
||||
spec = small_graph().to_spec()
|
||||
spec.nodes["long"].inputs = {}
|
||||
assert "PW006" in codes(check(spec, proj), "error")
|
||||
|
||||
|
||||
def test_patch_ops(make_project):
|
||||
proj = make_project(FAKE)
|
||||
spec = small_graph().to_spec()
|
||||
new = apply_ops(spec, [
|
||||
{"op": "add_node", "id": "sum", "type": "llm.generate", "inputs": {"in": "lab"},
|
||||
"params": {"model": "m", "prompt": "{{ payload.body }}", "output_field": "s"}},
|
||||
{"op": "disconnect", "from": "lab", "to": "out.in"},
|
||||
{"op": "connect", "from": "sum", "to": "out"},
|
||||
{"op": "set_param", "node": "long", "path": "expr", "value": "len(payload.body) > 5"},
|
||||
{"op": "rename_node", "id": "long", "new_id": "longish"},
|
||||
])
|
||||
assert new.nodes["out"].inputs == {"in": ["sum.out"]}
|
||||
assert new.nodes["lab"].inputs == {"in": ["longish.out"]}
|
||||
assert not codes(check(new, proj), "error")
|
||||
removed = apply_ops(new, [{"op": "remove_node", "id": "sum", "rewire": True}])
|
||||
assert removed.nodes["out"].inputs == {"in": ["lab.out"]}
|
||||
with pytest.raises(ConfigError):
|
||||
apply_ops(spec, [{"op": "connect", "from": "ghost", "to": "out"}])
|
||||
with pytest.raises(ConfigError):
|
||||
apply_ops(spec, [{"op": "explode"}])
|
||||
assert "oneOf" in json.dumps(ops_schema()) or "discriminator" in json.dumps(ops_schema())
|
||||
|
||||
|
||||
def test_every_node_type_example_validates():
|
||||
from pipewright.ops import nodes_describe
|
||||
|
||||
for name in registry.node_types.names():
|
||||
cls = registry.node_types[name]
|
||||
if name.startswith("test."):
|
||||
continue
|
||||
cls.Params.model_validate(cls.example)
|
||||
d = nodes_describe(name)
|
||||
assert d["params_schema"] and d["example_yaml"] and d["description"]
|
||||
@@ -0,0 +1,105 @@
|
||||
import asyncio
|
||||
import json
|
||||
import textwrap
|
||||
|
||||
from pipewright import Graph
|
||||
from pipewright.engine import Engine, RunOptions
|
||||
from pipewright.harness.base import AgentTask, HarnessContext
|
||||
from pipewright.harness.builtin_agent import BuiltinAgent
|
||||
from pipewright.models.base import ModelClient
|
||||
from pipewright.models.fake import FakeProvider
|
||||
from pipewright.project import ModelAlias
|
||||
from pipewright.sandbox.fake import FakeProvider as FakeSandboxes
|
||||
from pipewright.store import Store
|
||||
|
||||
|
||||
def tool_call(name, args, i=0):
|
||||
return {"id": f"c{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}
|
||||
|
||||
|
||||
def test_builtin_agent_uses_tools():
|
||||
def script(payload):
|
||||
msgs = payload["messages"]
|
||||
tools = [m for m in msgs if m["role"] == "tool"]
|
||||
if not tools:
|
||||
return {"content": "", "tool_calls": [tool_call("write_file", {"path": "a.py", "content": "x=1"})]}
|
||||
if len(tools) == 1:
|
||||
return {"content": "", "tool_calls": [tool_call("bash", {"command": "ls"}, 1),
|
||||
tool_call("bash", {"command": "{bad json"}, 2)]}
|
||||
return {"content": "", "tool_calls": [tool_call("finish", {"summary": "wrote a.py"}, 3)]}
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
mod = types.ModuleType("_pw_test_script")
|
||||
mod.script = script
|
||||
sys.modules["_pw_test_script"] = mod
|
||||
|
||||
async def main():
|
||||
prov = FakeProvider("f", {"script": "_pw_test_script:script"})
|
||||
client = ModelClient("solver", ModelAlias(provider="f", model="m", cache=False), prov)
|
||||
ctx = HarnessContext(lambda alias, salt: client, None)
|
||||
sbp = FakeSandboxes("fs", {"rules": [{"match": "ls", "stdout": "a.py\n"}]})
|
||||
async with sbp.lease() as sb:
|
||||
traj = await BuiltinAgent("mini", {"model": "solver"}).run(AgentTask(prompt="do it"), sb, ctx)
|
||||
return traj, sb.files
|
||||
|
||||
traj, files = asyncio.run(main())
|
||||
assert traj.status == "completed" and traj.final == "wrote a.py" and traj.turns == 3
|
||||
assert files == {"/workspace/a.py": b"x=1"}
|
||||
assert "a.py" in traj.messages[5]["content"] # bash output fed back
|
||||
|
||||
|
||||
AGENT = textwrap.dedent("""
|
||||
import json, os, urllib.request, urllib.error
|
||||
req = urllib.request.Request(os.environ["OPENAI_BASE_URL"] + "/chat/completions",
|
||||
data=json.dumps({"model": os.environ["PW_MODEL"], "messages": [{"role": "user", "content": open(".pw/prompt.md").read()}]}).encode(),
|
||||
headers={"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"], "Content-Type": "application/json"})
|
||||
try:
|
||||
answer = json.load(urllib.request.urlopen(req))["choices"][0]["message"]["content"]
|
||||
except urllib.error.HTTPError as e:
|
||||
print("model call failed", e.code) # a sloppy agent: exits 0 anyway
|
||||
raise SystemExit(0)
|
||||
open("answer.txt", "w").write(answer)
|
||||
""")
|
||||
|
||||
|
||||
def cli_graph():
|
||||
g = Graph("cli")
|
||||
src = g.add("src", "source.inline", kind="q", records=[{"id": "q1", "q": "say the magic word"}])
|
||||
g.add("agent", "agent.run", input=src, harness="ext", pool="local", prompt="{{ payload.q }}",
|
||||
files={"agent.py": AGENT}, grade={"command": "grep -q abracadabra answer.txt"},
|
||||
retries={"provider": 0})
|
||||
return g.to_spec()
|
||||
|
||||
|
||||
def test_cli_harness_through_proxy(make_project):
|
||||
proj = make_project({
|
||||
"providers": {"fake": {"type": "fake", "rules": [{"match": "magic", "content": "abracadabra"}]}},
|
||||
"models": {"m": {"provider": "fake", "model": "fake-m"}},
|
||||
"sandboxes": {"local": {"type": "local"}},
|
||||
"harnesses": {"ext": {"type": "cli", "model": "m", "command": "python3 agent.py"}},
|
||||
})
|
||||
store = Store(proj.store_dir)
|
||||
s = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
|
||||
assert s["funnel"]["nodes"]["agent"]["events"] == {"ok": 1}, s["errors"]
|
||||
item = store.get_items(store.flow_items(s["run_id"], "agent"))[0]
|
||||
assert item.labels["passed"] is True and item.labels["agent_status"] == "completed"
|
||||
traj = json.loads(store.get_blob(item.artifacts["trajectory"]))
|
||||
assert traj["messages"][-1]["content"] == "abracadabra" and traj["turns"] == 1
|
||||
|
||||
|
||||
def test_cli_harness_last_call_failed_is_provider_error(make_project):
|
||||
proj = make_project({
|
||||
"providers": {"fake": {"type": "fake", "fail": {"first": 99, "status": 503}}},
|
||||
"models": {"m": {"provider": "fake", "model": "fake-m", "max_retries": 0}},
|
||||
"sandboxes": {"local": {"type": "local"}},
|
||||
"harnesses": {"ext": {"type": "cli", "model": "m", "command": "python3 agent.py"}},
|
||||
})
|
||||
store = Store(proj.store_dir)
|
||||
s = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
|
||||
assert s["funnel"]["nodes"]["agent"]["events"] == {"error:provider": 1}
|
||||
assert "last model call failed" in s["errors"][0]["message"]
|
||||
# not memoized: the next run executes it again instead of replaying the error
|
||||
s2 = asyncio.run(Engine(cli_graph(), proj, store).run(RunOptions()))
|
||||
assert s2["funnel"]["nodes"]["agent"]["events"] == {"error:provider": 1}
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Host pools: placement by resources/capabilities/locality, autoscaling, idle shutdown,
|
||||
budgets, TTL extension, and Docker sandboxes placed on pool hosts (fake hosts + a fake
|
||||
docker CLI, so no VMs or daemon are needed)."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright import Graph
|
||||
from pipewright.engine import Engine, RunOptions
|
||||
from pipewright.errors import BudgetExceeded, ConfigError
|
||||
from pipewright.hosts import Resources
|
||||
from pipewright.store import Store
|
||||
|
||||
FAKE_DOCKER = str(Path(__file__).with_name("fake_docker.py"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_docker(tmp_path, monkeypatch):
|
||||
root = tmp_path / "docker"
|
||||
monkeypatch.setenv("FAKE_DOCKER_ROOT", str(root))
|
||||
return root
|
||||
|
||||
|
||||
def pool_project(make_project, fake_docker, **hosts_cfg):
|
||||
cfg = {"type": "fake", "max": 2, "capacity": {"cpus": 4, "memory": "8g"}, "tick": 0.05,
|
||||
"docker": FAKE_DOCKER, **hosts_cfg}
|
||||
return make_project({"hosts": {"vms": cfg},
|
||||
"sandboxes": {"box": {"type": "docker", "hosts": "vms", "image": "img:1", "cpus": 2,
|
||||
"memory": "2g", "docker": FAKE_DOCKER}}})
|
||||
|
||||
|
||||
def test_parse_sizes():
|
||||
r = Resources.parse({"cpus": 8, "memory": "16g", "disk": "512MiB"})
|
||||
assert r.cpus == 8 and r.memory == 16 * 2**30 and r.disk == 512 * 2**20
|
||||
assert Resources(2, 2**30).fits_in(Resources(2, 2**31)) and not Resources(3, 0).fits_in(Resources(2, 2**31))
|
||||
|
||||
|
||||
def test_packing_and_scale_up(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
req = pool.requirements(Resources(2, 2**30))
|
||||
leases = await asyncio.gather(*(pool.acquire(req) for _ in range(3)))
|
||||
hosts = {lz.host.id for lz in leases}
|
||||
assert len(hosts) == 2 and pool.provider.created and len(pool.provider.created) == 2
|
||||
# bin packing: two leases share a host, the third has its own
|
||||
per_host = sorted(sum(1 for lz in leases if lz.host.id == h) for h in hosts)
|
||||
assert per_host == [1, 2]
|
||||
# a fourth request fits next to the single one
|
||||
lz4 = await asyncio.wait_for(pool.acquire(req), 2)
|
||||
assert len(pool.provider.created) == 2
|
||||
for lz in [*leases, lz4]:
|
||||
lz.release()
|
||||
await pool.drain()
|
||||
assert sorted(pool.provider.deleted) == sorted(pool.provider.created)
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_memory_is_capacity_not_slots(make_project, fake_docker):
|
||||
"""Two 8 GB tasks never share a 16 GB host that keeps 1 GB for itself."""
|
||||
proj = pool_project(make_project, fake_docker, capacity={"cpus": 8, "memory": "16g"},
|
||||
reserve={"memory": "1g"}, max=1)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
req = pool.requirements(Resources(2, 8 * 2**30))
|
||||
a = await pool.acquire(req)
|
||||
b = asyncio.ensure_future(pool.acquire(req))
|
||||
await asyncio.sleep(0.2)
|
||||
assert not b.done() # waits: max=1 and the host has 7 GB left
|
||||
a.release()
|
||||
lb = await asyncio.wait_for(b, 2)
|
||||
lb.release()
|
||||
with pytest.raises(ConfigError):
|
||||
pool.requirements(Resources(1, 16 * 2**30)) # can never fit
|
||||
await pool.drain()
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_locality_prefers_hosts_with_image(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, min=2)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
await pool.scale_to(2)
|
||||
h1, h2 = sorted(pool.hosts.values(), key=lambda h: h.created)
|
||||
pool.add_label(h2, "image:big:1")
|
||||
lz = await pool.acquire(pool.requirements(Resources(1, 0), prefer={"image:big:1"}))
|
||||
assert lz.host is h2
|
||||
lz.release()
|
||||
await pool.drain()
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_idle_shutdown_and_min(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, idle_shutdown=0.1, min=1)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
req = pool.requirements(Resources(4, 0))
|
||||
a, b = await asyncio.gather(pool.acquire(req), pool.acquire(req))
|
||||
assert len(pool.hosts) == 2
|
||||
a.release()
|
||||
b.release()
|
||||
await asyncio.sleep(0.5)
|
||||
assert len([h for h in pool.hosts.values() if h.state == "ready"]) == 1 # down to min
|
||||
assert len(pool.provider.deleted) == 1
|
||||
await pool.drain()
|
||||
assert len(pool.provider.deleted) == 2
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_budget_stops_scaling(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, budget={"hours": 0.0}, max=2)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
with pytest.raises(BudgetExceeded):
|
||||
await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 2)
|
||||
await pool.drain()
|
||||
assert not pool.provider.created
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_create_failure_retried_and_ttl_extended(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, fail_create=1, ttl=1, extend_margin=0.95, create_backoff=0.05)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
lz = await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 5)
|
||||
assert pool.stats["failed_create"] == 1 and len(pool.provider.created) == 1
|
||||
await asyncio.sleep(0.3)
|
||||
assert pool.provider.extended
|
||||
lz.release()
|
||||
await pool.drain()
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_create_limit_and_failures_are_bounded(make_project, fake_docker):
|
||||
from pipewright.errors import InfraError
|
||||
|
||||
proj = pool_project(make_project, fake_docker, fail_create=100, create_backoff=0.01, max=2, create_retries=1)
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
with pytest.raises((InfraError, BudgetExceeded)):
|
||||
await asyncio.wait_for(pool.acquire(pool.requirements(Resources(1, 0))), 5)
|
||||
await asyncio.sleep(0.3)
|
||||
assert pool.stats["failed_create"] <= pool.create_limit == 8
|
||||
await pool.drain()
|
||||
|
||||
asyncio.run(go())
|
||||
|
||||
|
||||
def test_kvm_runtime_setup_and_requirement(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, kvm=True, docker_kvm_runtime=True,
|
||||
setup=["echo setup-ran"])
|
||||
pool = proj.host_pool("vms")
|
||||
|
||||
async def go():
|
||||
lz = await pool.acquire(pool.requirements(Resources(1, 0), kvm=True))
|
||||
cmds = [c for _, c in pool.provider.commands]
|
||||
assert "bash -s" in cmds and "echo setup-ran" in cmds and "kvm" in lz.host.labels
|
||||
lz.release()
|
||||
await pool.drain()
|
||||
|
||||
asyncio.run(go())
|
||||
proj2 = pool_project(make_project, fake_docker) # hosts without kvm
|
||||
with pytest.raises(ConfigError):
|
||||
proj2.host_pool("vms").requirements(Resources(1, 0), kvm=True)
|
||||
|
||||
|
||||
def test_engine_runs_sandboxes_on_pool(make_project, fake_docker):
|
||||
proj = pool_project(make_project, fake_docker, idle_shutdown=60)
|
||||
g = Graph("pooled")
|
||||
src = g.add("src", "source.inline", kind="t", records=[{"id": f"r{i}", "n": i} for i in range(6)])
|
||||
g.add("check", "sandbox.check", input=src, pool="box", checks=[
|
||||
{"name": "even", "command": f"{sys.executable} -c 'import sys; sys.exit({{{{ payload.n }}}} % 2)'",
|
||||
"expect": "pass"}])
|
||||
store = Store(proj.store_dir)
|
||||
try:
|
||||
summary = asyncio.run(Engine(g.to_spec(), proj, store).run(RunOptions()))
|
||||
finally:
|
||||
store.close()
|
||||
assert summary["status"] == "completed", summary["errors"]
|
||||
run = Store(proj.store_dir).run(summary["run_id"])
|
||||
hosts = run["stats"]["hosts"]["vms"]
|
||||
assert hosts["created"] == 2 and hosts["deleted"] == 2 and hosts["placed"] == 6 # 6 x 2 cpus on 4-cpu hosts
|
||||
calls = [json.loads(x) for x in (fake_docker / "calls.jsonl").read_text().splitlines()]
|
||||
runs = [c for c in calls if c["args"][0] == "run"]
|
||||
assert len(runs) == 6 and all(c["host"].startswith("ssh://fake-vms-") for c in runs)
|
||||
assert all("--cpus" in c["args"] and "2" in c["args"] for c in runs)
|
||||
# the image was checked once per host, then pulled with the first container
|
||||
assert len({c["host"] for c in calls if c["args"][:2] == ["image", "inspect"]}) == 2
|
||||
labels = {f"r{i}": None for i in range(6)}
|
||||
assert summary["funnel"]["nodes"]["check"]["events"]["ok"] == len(labels)
|
||||
|
||||
|
||||
def test_check_reports_unknown_host_pool(make_project):
|
||||
from pipewright.check import check
|
||||
|
||||
proj = make_project({"sandboxes": {"box": {"type": "docker", "hosts": "nope", "image": "x"}}})
|
||||
g = Graph("x")
|
||||
g.add("src", "source.inline", kind="t", records=[{"id": 1}])
|
||||
diags = check(g.to_spec(), proj)
|
||||
assert any(d.code == "PW012" and "host pool 'nope'" in d.message for d in diags)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Building on earlier results: cross-graph imports, store.query, lineage across graphs,
|
||||
re-entrant loops across runs."""
|
||||
|
||||
import json
|
||||
|
||||
import yaml
|
||||
|
||||
from pipewright import Graph, ops
|
||||
from pipewright.check import check
|
||||
|
||||
from conftest import FAKE
|
||||
|
||||
|
||||
def ev(summary, node):
|
||||
return summary["funnel"]["nodes"][node]["events"]
|
||||
|
||||
|
||||
def test_two_graph_example_is_incremental(example):
|
||||
d = example("hardening")
|
||||
b1 = ops.run_graph(d / "graph_build.py", limit=3) # add, classify, reverse_words
|
||||
assert b1["funnel"]["nodes"]["bucket"]["out"] == {"too_easy": 1, "learnable": 1, "too_hard": 1}
|
||||
h1 = ops.run_graph(d / "graph_harden.py")
|
||||
assert h1["status"] == "completed", h1["errors"]
|
||||
assert h1["funnel"]["nodes"]["build:bucket"]["out"] == {"too_easy": 1}
|
||||
assert h1["funnel"]["nodes"]["build:bucket"]["imported_from"]["graph"] == "build"
|
||||
assert h1["funnel"]["nodes"]["bucket"]["out"] == {"learnable": 1} # add_many: 1 of 2 rollouts pass
|
||||
# upstream grows: only the new too_easy task is hardened and probed
|
||||
ops.run_graph(d / "graph_build.py")
|
||||
h2 = ops.run_graph(d / "graph_harden.py")
|
||||
assert ev(h2, "harden") == {"ok": 2, "cached": 1}
|
||||
assert ev(h2, "probe") == {"ok": 4, "cached": 2}
|
||||
assert h2["funnel"]["nodes"]["bucket"]["out"] == {"learnable": 1, "too_hard": 1}
|
||||
# lineage crosses the graph boundary: the variant's root is build's synthesized task
|
||||
var = ops.query(d / "graph_harden.py", node="variant", where="payload.name == 'second_biggest'")["items"][0]
|
||||
roots = ops.lineage(d / "graph_harden.py", var["id"], roots=True)["roots"]
|
||||
assert [(r["key"], r["origin"]["graph"], r["producer"]) for r in roots] == [("biggest", "build", "synth")]
|
||||
desc = ops.lineage(d / "graph_build.py", "biggest", descendants=True)["descendants"]
|
||||
assert {x["key"] for x in desc if x["origin"]["graph"] == "harden"} >= {"second_biggest", "biggest"}
|
||||
# report shows the cross-graph edge; preview/funnel work with imports
|
||||
html = open(ops.report(d / "graph_harden.py")["path"]).read()
|
||||
assert "from graph build:bucket" in html and "edge ext" in html
|
||||
pv = ops.preview(d / "graph_harden.py", upto="variant", n=1)
|
||||
assert pv["status"] == "completed" and len(pv["items"]) == 1
|
||||
|
||||
|
||||
def test_check_reports_bad_imports(example):
|
||||
d = example("hardening")
|
||||
spec = yaml.safe_load(json.dumps({"name": "bad", "imports": {"build": {"graph": "graph_build.py"}},
|
||||
"nodes": {"x": {"type": "filter.expr", "inputs": {"in": "build:bucket.nope"},
|
||||
"params": {"expr": "true"}},
|
||||
"y": {"type": "filter.expr", "inputs": {"in": "build:nonode"},
|
||||
"params": {"expr": "true"}},
|
||||
"z": {"type": "filter.expr", "inputs": {"in": "other:a.b"},
|
||||
"params": {"expr": "true"}}}}))
|
||||
(d / "bad.yaml").write_text(yaml.safe_dump(spec))
|
||||
res = ops.check_graph(d / "bad.yaml")
|
||||
msgs = [x["message"] for x in res["diagnostics"] if x["code"] == "PW020"]
|
||||
assert any("no output port 'nope'" in m for m in msgs)
|
||||
assert any("has no node 'nonode'" in m for m in msgs)
|
||||
assert any("unknown import alias 'other'" in m for m in msgs)
|
||||
assert not res["ok"]
|
||||
|
||||
|
||||
def test_imported_port_kinds_are_checked(example):
|
||||
d = example("hardening")
|
||||
g = Graph("kinds")
|
||||
up = g.import_graph("build", "graph_build.py")
|
||||
g.add("only_issues", "llm.label", input=up.node("bucket").port("too_easy"), model="generator",
|
||||
prompt="x", labels={"a": {"type": "string"}})
|
||||
spec = g.to_spec()
|
||||
spec._base_dir = d
|
||||
from pipewright.project import Project
|
||||
|
||||
diags = check(spec, Project.discover(d))
|
||||
assert not [x for x in diags if x.level == "error"], [x.format() for x in diags]
|
||||
from pipewright.imports import expand_imports
|
||||
|
||||
ex = expand_imports(spec, Project.discover(d))
|
||||
assert ex.nodes["build:bucket"].params["ports"] == {"too_easy": "task_result"}
|
||||
|
||||
|
||||
def test_store_query_node_and_other_store(make_project, tmp_path):
|
||||
make_project(FAKE)
|
||||
g = Graph("scores")
|
||||
src = g.add("src", "source.inline", kind="t", records=[{"id": f"r{i}", "s": i / 10} for i in range(10)])
|
||||
g.add("lab", "label.expr", input=src, labels={"score": "payload.s"})
|
||||
g.save(tmp_path / "scores.yaml")
|
||||
ops.run_graph(tmp_path / "scores.yaml")
|
||||
|
||||
q = Graph("seeds")
|
||||
sel = q.add("sel", "store.query", graph="scores", node="lab", where="labels.score >= 0.75", kind="t")
|
||||
q.add("tag", "label.expr", input=sel, labels={"seeded": "True"})
|
||||
q.save(tmp_path / "seeds.yaml")
|
||||
r = ops.run_graph(tmp_path / "seeds.yaml")
|
||||
assert r["funnel"]["nodes"]["sel"]["out"] == {"out": 2} # 0.8, 0.9
|
||||
|
||||
# another project reading this store: items (and lineage) are copied over
|
||||
other = tmp_path / "other"
|
||||
other.mkdir()
|
||||
(other / "pipewright.yaml").write_text(yaml.safe_dump({"store": ".pw2", **FAKE}))
|
||||
q2 = Graph("remote-seeds")
|
||||
q2.add("sel", "store.query", store=str(tmp_path / "pipewright.yaml"), graph="scores", node="lab",
|
||||
labels={"score": 0.9})
|
||||
q2.save(other / "g.yaml")
|
||||
r2 = ops.run_graph(other / "g.yaml")
|
||||
assert r2["funnel"]["nodes"]["sel"]["out"] == {"out": 1}
|
||||
item = ops.items(other / "g.yaml", "sel")["items"][0]
|
||||
lin = ops.lineage(other / "g.yaml", item["id"])["lineage"]
|
||||
assert len(lin) == 2 # copied with its parent
|
||||
|
||||
res = ops.query(tmp_path / "scores.yaml", node="lab", where="labels.score < 0.2")
|
||||
assert res["total"] == 2 and res["as_node"]["type"] == "store.query"
|
||||
|
||||
|
||||
def test_reentrant_loop_across_runs(make_project, tmp_path):
|
||||
"""Failures of run N become seeds of run N+1 (self import), without a live cycle."""
|
||||
make_project(FAKE)
|
||||
g = Graph("loop")
|
||||
prev = g.import_graph("prev", "self") # run=previous by default for self
|
||||
seeds = g.add("seeds", "source.inline", kind="n", records=[{"id": "a", "v": 1}, {"id": "b", "v": 8}])
|
||||
step = g.add("step", "map.expr", input=[seeds, prev.node("audit").port("retry")],
|
||||
fields={"v": "payload.v * 2"})
|
||||
g.add("audit", "route.expr", input=step, routes={"done": "payload.v >= 10"}, default="retry")
|
||||
g.save(tmp_path / "loop.yaml")
|
||||
assert ops.check_graph(tmp_path / "loop.yaml")["ok"]
|
||||
outs = []
|
||||
for _ in range(4):
|
||||
r = ops.run_graph(tmp_path / "loop.yaml")
|
||||
assert r["status"] == "completed", r["errors"]
|
||||
outs.append(r["funnel"]["nodes"]["audit"]["out"])
|
||||
# a: 1->2 (retry) ->4 ->8 ->16 done; b: 8->16 done
|
||||
assert outs[0] == {"done": 1, "retry": 1}
|
||||
assert outs[1] == {"done": 1, "retry": 2} # a's 2 is retried as 4 (also re-emitted from seeds: memoized)
|
||||
vals = sorted(i["payload"]["v"] for i in ops.items(tmp_path / "loop.yaml", "audit", port="done", n=10)["items"])
|
||||
assert 16 in vals
|
||||
@@ -0,0 +1,41 @@
|
||||
from pipewright.items import Item
|
||||
from pipewright.store import Store
|
||||
|
||||
|
||||
def test_item_ids_are_content_and_lineage_hashes():
|
||||
a = Item(key="k", kind="issue", payload={"x": 1})
|
||||
b = Item(key="k", kind="issue", payload={"x": 1})
|
||||
assert a.id == b.id and len(a.id) == 24
|
||||
assert Item(key="k", kind="issue", payload={"x": 2}).id != a.id
|
||||
d = a.derive(update_labels={"y": True})
|
||||
assert d.parents == (a.id,) and d.labels == {"y": True} and d.payload == a.payload
|
||||
assert d.id != a.id
|
||||
s = d.stamped("node1", "label.expr@1")
|
||||
assert s.producer == "node1" and s.id != d.id and s.parents == d.parents
|
||||
assert a.content_hash == Item(key="other", kind="issue", payload={"x": 1}).content_hash
|
||||
|
||||
|
||||
def test_item_get_paths():
|
||||
it = Item(key="k", kind="t", payload={"a": {"b": [1, {"c": 3}]}}, labels={"s": 0.5})
|
||||
assert it.get("payload.a.b.1.c") == 3
|
||||
assert it.get("labels.s") == 0.5
|
||||
assert it.get("key") == "k"
|
||||
assert it.get("payload.missing", "d") == "d"
|
||||
|
||||
|
||||
def test_store_roundtrip(tmp_path):
|
||||
st = Store(tmp_path / "s")
|
||||
a = Item(key="k", kind="t", payload={"x": 1})
|
||||
b = a.derive(update_payload={"x": 2}).stamped("n", "op@1")
|
||||
st.put_item(a)
|
||||
st.put_item(b)
|
||||
st2 = Store(tmp_path / "s")
|
||||
assert st2.get_item(b.id) == b
|
||||
assert [i.id for i in st2.lineage(b.id)] == [b.id, a.id]
|
||||
assert st2.children(a.id) == [b.id]
|
||||
ref = st2.put_blob(b"hello", "text/plain", "h.txt")
|
||||
assert st2.get_blob(ref) == b"hello" and ref.size == 5
|
||||
st2.memo_put("sig", a.id, "n", "ok", {"out": [b.id]}, None, "r1", 0.1)
|
||||
m = st2.memo_get("sig", a.id)
|
||||
assert m.status == "ok" and m.outputs == {"out": [b.id]}
|
||||
assert st2.memo_get("sig", "nope") is None
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Live smoke tests against the real provider configured in the examples'
|
||||
pipewright.live.yaml (DeepSeek via Morph). Run with `pytest --live`; kept small and
|
||||
paced (the key's per-minute limits are shared)."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright import ops
|
||||
from pipewright.models.base import ModelClient
|
||||
from pipewright.project import Project
|
||||
|
||||
pytestmark = pytest.mark.live
|
||||
|
||||
|
||||
def test_live_issue_triage(example):
|
||||
d = example("issue_triage")
|
||||
s = ops.run_graph(d / "graph.py", project=d / "pipewright.live.yaml", limit=4)
|
||||
assert s["status"] == "completed", s["errors"]
|
||||
items = ops.items(d / "graph.py", "classify", project=d / "pipewright.live.yaml", n=10)["items"]
|
||||
assert len(items) == 4
|
||||
for it in items:
|
||||
assert it["labels"]["category"] in ("bug", "feature", "question", "docs")
|
||||
assert 0 <= it["labels"]["severity"] <= 3
|
||||
by_key = {it["key"]: it["labels"] for it in items}
|
||||
assert by_key["gh-101"]["category"] == "bug" # a crash with a traceback
|
||||
assert by_key["gh-102"]["category"] == "feature" # dark mode
|
||||
usage = s["usage"][0]
|
||||
assert usage["calls"] >= 4 and usage["input_tokens"] > 0 and usage["output_tokens"] > 0
|
||||
|
||||
|
||||
def test_live_streaming_path(example):
|
||||
d = example("issue_triage")
|
||||
proj = Project.load(d / "pipewright.live.yaml")
|
||||
proj.config.providers["morph"]["stream"] = True
|
||||
alias = proj.config.models["labeler"].model_copy(update={"cache": False})
|
||||
client = ModelClient("labeler", alias, proj.provider("morph"))
|
||||
|
||||
async def main():
|
||||
try:
|
||||
return await client.chat([{"role": "user", "content": "Reply with exactly the word: pong"}], max_tokens=200)
|
||||
finally:
|
||||
await proj.aclose()
|
||||
|
||||
res = asyncio.run(main())
|
||||
assert "pong" in res.content.lower() and res.usage.output_tokens > 0
|
||||
|
||||
|
||||
def test_live_coding_agent(example):
|
||||
d = example("coding_tasks")
|
||||
s = ops.run_graph(d / "graph.py", project=d / "pipewright.live.yaml", limit=2)
|
||||
assert s["status"] in ("completed", "completed_with_errors"), s["errors"]
|
||||
nodes = s["funnel"]["nodes"]
|
||||
assert nodes["synth"]["out"]["out"] == 2
|
||||
# every validated task got 2 rollouts that were graded (no provider failures recorded as results)
|
||||
n_valid = nodes["valid"]["out"].get("out", 0)
|
||||
assert nodes["probe"]["out"].get("out", 0) == 2 * n_valid
|
||||
assert sum(nodes["bucket"]["out"].values()) == n_valid
|
||||
@@ -0,0 +1,24 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("mcp")
|
||||
|
||||
|
||||
def test_mcp_exposes_ops(example):
|
||||
from pipewright.mcp_server import build_server
|
||||
|
||||
d = example("issue_triage")
|
||||
server = build_server()
|
||||
|
||||
async def main():
|
||||
names = {t.name for t in await server.list_tools()}
|
||||
res = await server.call_tool("check_graph", {"graph": str(d / "graph.py")})
|
||||
return names, res
|
||||
|
||||
names, res = asyncio.run(main())
|
||||
assert {"nodes_describe", "check_graph", "patch_graph", "preview", "run_graph", "funnel", "items", "query",
|
||||
"lineage", "hosts"} <= names
|
||||
content = res.content if hasattr(res, "content") else res[0]
|
||||
assert json.loads(content[0].text)["ok"] is True
|
||||
@@ -0,0 +1,104 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from pipewright.errors import ProviderError
|
||||
from pipewright.models.base import ModelClient
|
||||
from pipewright.models.fake import FakeProvider, sample_from_schema
|
||||
from pipewright.models.openai_compat import OpenAICompatProvider
|
||||
from pipewright.project import ModelAlias
|
||||
from pipewright.store import Store
|
||||
|
||||
OK = {"id": "x", "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 5, "completion_tokens": 1}}
|
||||
|
||||
|
||||
def provider(handler, **cfg):
|
||||
return OpenAICompatProvider("p", {"base_url": "http://up/v1", "_transport": httpx.MockTransport(handler), **cfg})
|
||||
|
||||
|
||||
def client(prov, tmp_path=None, **alias):
|
||||
store = Store(tmp_path) if tmp_path else None
|
||||
usage = []
|
||||
c = ModelClient("a", ModelAlias(provider="p", model="m", max_retries=4, **alias), prov, store=store,
|
||||
on_usage=lambda *a: usage.append(a))
|
||||
return c, usage
|
||||
|
||||
|
||||
def test_plain_completion_and_usage(tmp_path):
|
||||
prov = provider(lambda req: httpx.Response(200, json=OK), pricing={"input_per_mtok": 1e6, "output_per_mtok": 0})
|
||||
c, usage = client(prov, tmp_path)
|
||||
res = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
|
||||
assert res.content == "hi" and res.usage.input_tokens == 5 and res.usage.cost_usd == 5.0
|
||||
again = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
|
||||
assert again.cached and usage[-1][-1] is True # request cache hit, accounted as cached
|
||||
|
||||
|
||||
def test_429_with_retry_after_is_retried():
|
||||
calls = []
|
||||
|
||||
def handler(req):
|
||||
calls.append(1)
|
||||
if len(calls) < 3:
|
||||
return httpx.Response(429, headers={"retry-after": "0.05"}, json={"error": "slow down"})
|
||||
return httpx.Response(200, json=OK)
|
||||
|
||||
c, _ = client(provider(handler))
|
||||
assert asyncio.run(c.chat([{"role": "user", "content": "x"}])).content == "hi"
|
||||
assert len(calls) == 3 and c.provider.limiter.stats["rejected"] == 2
|
||||
|
||||
|
||||
def test_http200_stream_with_error_event_becomes_429():
|
||||
calls = []
|
||||
|
||||
def handler(req):
|
||||
calls.append(json.loads(req.content))
|
||||
if len(calls) == 1:
|
||||
body = b": heartbeat\n\n: heartbeat\n\ndata: {\"error\": {\"code\": \"capacity_saturated\", \"message\": \"busy\"}}\n\n"
|
||||
return httpx.Response(200, content=body, headers={"content-type": "text/event-stream"})
|
||||
chunks = [{"choices": [{"index": 0, "delta": {"role": "assistant", "content": "he"}}]},
|
||||
{"choices": [{"index": 0, "delta": {"content": "llo"}, "finish_reason": "stop"}]},
|
||||
{"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2}}]
|
||||
body = b"".join(b"data: " + json.dumps(c).encode() + b"\n\n" for c in chunks) + b"data: [DONE]\n\n"
|
||||
return httpx.Response(200, content=body, headers={"content-type": "text/event-stream"})
|
||||
|
||||
prov = provider(handler, stream=True)
|
||||
c, _ = client(prov)
|
||||
res = asyncio.run(c.chat([{"role": "user", "content": "x"}]))
|
||||
assert res.content == "hello" and res.usage.output_tokens == 2
|
||||
assert calls[0]["stream"] is True and prov.limiter.stats["rejected"] == 1
|
||||
|
||||
|
||||
def test_http200_body_error_and_4xx():
|
||||
def handler(req):
|
||||
return httpx.Response(200, json={"error": {"code": 503, "message": "overloaded"}})
|
||||
|
||||
prov = provider(handler)
|
||||
with pytest.raises(ProviderError) as e:
|
||||
asyncio.run(prov.complete({"model": "m", "messages": []}))
|
||||
assert e.value.status == 503 and e.value.retryable
|
||||
|
||||
c, _ = client(provider(lambda r: httpx.Response(400, json={"error": "bad"})))
|
||||
with pytest.raises(ProviderError) as e:
|
||||
asyncio.run(c.chat([{"role": "user", "content": "x"}]))
|
||||
assert e.value.status == 400 and not e.value.retryable
|
||||
|
||||
|
||||
def test_literal_api_key_rejected():
|
||||
prov = provider(lambda r: httpx.Response(200, json=OK), api_key="sk-literal")
|
||||
with pytest.raises(ProviderError):
|
||||
asyncio.run(prov.complete({"model": "m", "messages": []}))
|
||||
|
||||
|
||||
def test_fake_provider_schema_and_failures():
|
||||
schema = {"type": "object", "properties": {"c": {"type": "string", "enum": ["a", "b"]},
|
||||
"s": {"type": "integer", "minimum": 0, "maximum": 2}}}
|
||||
v = sample_from_schema(schema, "seed")
|
||||
assert v["c"] in ("a", "b") and 0 <= v["s"] <= 2
|
||||
prov = FakeProvider("f", {"fail": {"first": 2, "status": 429, "retry_after": 0.01}})
|
||||
c, _ = client(prov)
|
||||
res = asyncio.run(c.chat([{"role": "user", "content": "x"}], response_format={
|
||||
"type": "json_schema", "json_schema": {"schema": schema}}))
|
||||
assert set(json.loads(res.content)) == {"c", "s"} and prov.calls == 3
|
||||
@@ -0,0 +1,85 @@
|
||||
"""A local plugin pack registering one of each: node type, provider, sandbox, harness."""
|
||||
|
||||
import textwrap
|
||||
|
||||
from pipewright import ops
|
||||
|
||||
PACK = textwrap.dedent('''
|
||||
from pydantic import BaseModel
|
||||
from pipewright import NodeType, Port, register_node, register_provider, register_sandbox, register_harness
|
||||
from pipewright.models.base import ModelProvider
|
||||
from pipewright.sandbox.fake import FakeProvider as FakeSandboxes
|
||||
from pipewright.harness.base import Harness, Trajectory
|
||||
|
||||
|
||||
class ShoutParams(BaseModel):
|
||||
field: str = "text"
|
||||
|
||||
|
||||
@register_node
|
||||
class Shout(NodeType):
|
||||
"""Upper-case a payload field."""
|
||||
name = "mypack.shout"
|
||||
kind = "map"
|
||||
Params = ShoutParams
|
||||
inputs = {"in": Port(kind="note")}
|
||||
outputs = {"out": Port(kind="note")}
|
||||
example = {"field": "text"}
|
||||
|
||||
async def process(self, item, ctx):
|
||||
return item.derive(update_payload={self.params.field: item.payload[self.params.field].upper()})
|
||||
|
||||
|
||||
class Echo(ModelProvider):
|
||||
type = "echo"
|
||||
|
||||
async def complete(self, payload):
|
||||
text = payload["messages"][-1]["content"]
|
||||
return {"choices": [{"index": 0, "message": {"role": "assistant", "content": text[::-1]}}],
|
||||
"usage": {"prompt_tokens": 1, "completion_tokens": 1}}
|
||||
|
||||
|
||||
register_provider("echo", Echo)
|
||||
register_sandbox("mybox", FakeSandboxes)
|
||||
|
||||
|
||||
class Noop(Harness):
|
||||
type = "noop"
|
||||
|
||||
async def run(self, task, sandbox, ctx):
|
||||
return Trajectory(harness=self.name, status="completed", final=task.prompt)
|
||||
|
||||
|
||||
register_harness("noop", Noop)
|
||||
''')
|
||||
|
||||
GRAPH = """
|
||||
name: plug
|
||||
nodes:
|
||||
notes: {type: source.inline, params: {kind: note, records: [{id: n1, text: hello}]}}
|
||||
shout: {type: mypack.shout, inputs: {in: notes}}
|
||||
rev: {type: llm.generate, inputs: {in: shout}, params: {model: rev, prompt: "{{ payload.text }}", output_field: r}}
|
||||
agent: {type: agent.run, inputs: {in: rev}, params: {harness: h, pool: box, prompt: "{{ payload.r }}"}}
|
||||
sink: {type: sink.jsonl, inputs: {in: agent}, params: {path: out/p.jsonl}}
|
||||
"""
|
||||
|
||||
PROJECT = """
|
||||
plugins: [mypack_nodes]
|
||||
providers: {e: {type: echo}}
|
||||
models: {rev: {provider: e, model: echo-1}}
|
||||
sandboxes: {box: {type: mybox}}
|
||||
harnesses: {h: {type: noop}}
|
||||
"""
|
||||
|
||||
|
||||
def test_local_plugin_pack(tmp_path):
|
||||
(tmp_path / "mypack_nodes.py").write_text(PACK)
|
||||
(tmp_path / "pipewright.yaml").write_text(PROJECT)
|
||||
(tmp_path / "g.yaml").write_text(GRAPH)
|
||||
chk = ops.check_graph(tmp_path / "g.yaml")
|
||||
assert chk["ok"], chk
|
||||
s = ops.run_graph(tmp_path / "g.yaml")
|
||||
assert s["status"] == "completed", s["errors"]
|
||||
item = ops.items(tmp_path / "g.yaml", "agent")["items"][0]
|
||||
assert item["payload"]["r"] == "OLLEH" and item["labels"]["agent_status"] == "completed"
|
||||
assert ops.nodes_describe("mypack.shout")["inputs"]["in"]["kind"] == "note"
|
||||
@@ -0,0 +1,59 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
|
||||
from pipewright.models.base import ModelClient
|
||||
from pipewright.models.fake import FakeProvider
|
||||
from pipewright.models.proxy import LoggingProxy
|
||||
from pipewright.project import ModelAlias
|
||||
|
||||
|
||||
def make_client(cfg=None):
|
||||
prov = FakeProvider("f", cfg or {"rules": [{"match": "hello", "content": "hi there"}]})
|
||||
return ModelClient("a", ModelAlias(provider="f", model="fake-m", max_retries=1, cache=False), prov)
|
||||
|
||||
|
||||
def test_proxy_records_turns_and_streams():
|
||||
async def main():
|
||||
proxy = LoggingProxy()
|
||||
port = await proxy.listen("127.0.0.1")
|
||||
s = proxy.open_session(make_client())
|
||||
base = f"http://127.0.0.1:{port}/v1"
|
||||
async with httpx.AsyncClient() as http:
|
||||
h = {"Authorization": f"Bearer {s.token}"}
|
||||
r1 = await http.post(f"{base}/chat/completions", headers=h,
|
||||
json={"model": "whatever", "messages": [{"role": "user", "content": "hello"}]})
|
||||
msgs = [{"role": "user", "content": "hello"}, r1.json()["choices"][0]["message"],
|
||||
{"role": "user", "content": "hello again"}]
|
||||
r2 = await http.post(f"{base}/chat/completions", headers=h,
|
||||
json={"model": "whatever", "messages": msgs, "stream": True})
|
||||
bad = await http.post(f"{base}/chat/completions", headers={"Authorization": "Bearer nope"}, json={})
|
||||
models = await http.get(f"{base}/models", headers=h)
|
||||
await proxy.aclose()
|
||||
return s, r1, r2, bad, models
|
||||
|
||||
s, r1, r2, bad, models = asyncio.run(main())
|
||||
assert r1.status_code == 200 and r1.json()["choices"][0]["message"]["content"] == "hi there"
|
||||
assert r2.headers["content-type"] == "text/event-stream"
|
||||
events = [json.loads(line[6:]) for line in r2.text.splitlines() if line.startswith("data: {")]
|
||||
assert events[0]["choices"][0]["delta"]["content"] == "hi there"
|
||||
assert bad.status_code == 401 and models.json()["data"][0]["id"] == "fake-m"
|
||||
assert len(s.turns) == 2 and {t["conversation"] for t in s.turns} == {"c0"} # continuation detected
|
||||
assert len(s.messages()) == 4 and not s.failed_last_call
|
||||
|
||||
|
||||
def test_proxy_surfaces_provider_failure():
|
||||
async def main():
|
||||
proxy = LoggingProxy()
|
||||
port = await proxy.listen("127.0.0.1")
|
||||
s = proxy.open_session(make_client({"fail": {"first": 99, "status": 503}}))
|
||||
async with httpx.AsyncClient() as http:
|
||||
r = await http.post(f"http://127.0.0.1:{port}/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {s.token}"},
|
||||
json={"messages": [{"role": "user", "content": "x"}]})
|
||||
await proxy.aclose()
|
||||
return s, r
|
||||
|
||||
s, r = asyncio.run(main())
|
||||
assert r.status_code == 503 and s.failed_last_call and s.turns[-1]["status"] == 503
|
||||
@@ -0,0 +1,118 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright.errors import InfraError
|
||||
from pipewright.sandbox.docker import DockerProvider
|
||||
from pipewright.sandbox.fake import FakeProvider
|
||||
from pipewright.sandbox.local import LocalProvider
|
||||
|
||||
|
||||
def test_local_sandbox_exec_files_timeout():
|
||||
async def main():
|
||||
prov = LocalProvider("local", {"setup": ["echo setup > s.txt"]})
|
||||
async with prov.lease() as sb:
|
||||
await sb.write("a/b.txt", "hello")
|
||||
assert (await sb.read("a/b.txt")) == b"hello"
|
||||
r = await sb.exec("cat a/b.txt s.txt; echo err >&2; exit 3")
|
||||
assert r.exit_code == 3 and r.stdout == "hellosetup\n" and r.stderr == "err\n"
|
||||
t = await sb.exec("sleep 5", timeout=0.3)
|
||||
assert t.timed_out and not t.ok
|
||||
wd = sb.workdir
|
||||
import os
|
||||
|
||||
assert not os.path.exists(wd) # destroyed on release
|
||||
return prov.stats
|
||||
|
||||
st = asyncio.run(main())
|
||||
assert st["created"] == 1 and st["destroyed"] == 1
|
||||
|
||||
|
||||
def test_lease_lifecycle_failures_and_reuse():
|
||||
async def main():
|
||||
prov = FakeProvider("f", {"fail_create": 1, "slots": 1})
|
||||
with pytest.raises(InfraError):
|
||||
async with prov.lease():
|
||||
pass
|
||||
assert prov.slots.in_use == 0 # slot released after a failed create
|
||||
reuse = FakeProvider("r", {"reuse": True})
|
||||
async with reuse.lease() as a:
|
||||
pass
|
||||
async with reuse.lease() as b:
|
||||
pass
|
||||
assert a is b and reuse.stats["reused"] == 1
|
||||
await reuse.drain()
|
||||
assert reuse.destroyed == [a.id]
|
||||
setup = FakeProvider("s", {"setup": ["make"], "rules": [{"match": "make", "exit_code": 2}]})
|
||||
with pytest.raises(InfraError, match="setup"):
|
||||
async with setup.lease():
|
||||
pass
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
@pytest.mark.docker
|
||||
def test_docker_sandbox():
|
||||
async def main():
|
||||
prov = DockerProvider("t", {"image": "python:3.12-slim", "network": "none", "memory": "256m"})
|
||||
async with prov.lease() as sb:
|
||||
await sb.write("x/y.py", "print(6*7)")
|
||||
r = await sb.exec("python3 x/y.py")
|
||||
assert r.stdout.strip() == "42" and sb.workdir == "/workspace"
|
||||
assert (await sb.read("/workspace/x/y.py")) == b"print(6*7)"
|
||||
t = await sb.exec("sleep 10", timeout=1)
|
||||
assert t.timed_out
|
||||
net = await sb.exec("python3 -c \"import socket; socket.create_connection(('1.1.1.1', 80), 3)\"")
|
||||
assert net.exit_code != 0
|
||||
with pytest.raises(FileNotFoundError):
|
||||
await sb.read("nope")
|
||||
await prov.drain()
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
@pytest.mark.docker
|
||||
def test_docker_egress_allowlist():
|
||||
async def main():
|
||||
prov = DockerProvider("allow", {"image": "python:3.12-slim", "network": "allowlist", "allow": ["pypi.org"]})
|
||||
code = ("import urllib.request,sys\n"
|
||||
"try:\n urllib.request.urlopen(sys.argv[1], timeout=20); print('OK')\n"
|
||||
"except Exception as e: print('FAIL', e)\n")
|
||||
try:
|
||||
async with prov.lease() as sb:
|
||||
await sb.write("probe.py", code)
|
||||
denied = await sb.exec("python3 probe.py https://example.com/")
|
||||
allowed = await sb.exec("python3 probe.py https://pypi.org/simple/")
|
||||
direct = await sb.exec("env -u HTTPS_PROXY -u https_proxy python3 probe.py https://pypi.org/simple/")
|
||||
denied_hosts = list(prov._egress.denied)
|
||||
finally:
|
||||
await prov.drain()
|
||||
return denied, allowed, direct, denied_hosts
|
||||
|
||||
denied, allowed, direct, denied_hosts = asyncio.run(main())
|
||||
assert "FAIL" in denied.stdout and "example.com" in denied_hosts
|
||||
assert "FAIL" in direct.stdout # no route around the proxy
|
||||
assert "OK" in allowed.stdout, allowed.stdout + allowed.stderr
|
||||
|
||||
|
||||
@pytest.mark.docker
|
||||
def test_ssh_docker_host():
|
||||
"""Docker on another machine over SSH (set PW_TEST_SSH_HOST=ssh://user@host)."""
|
||||
import os
|
||||
|
||||
host = os.environ.get("PW_TEST_SSH_HOST")
|
||||
if not host:
|
||||
pytest.skip("set PW_TEST_SSH_HOST")
|
||||
from pipewright.registry import registry
|
||||
|
||||
async def main():
|
||||
prov = registry.sandboxes["ssh_docker"]("remote", {"host": host, "image": "python:3.12-slim"})
|
||||
assert prov.capabilities.remote and prov.slots.slots >= 1
|
||||
async with prov.lease() as sb:
|
||||
await sb.write("a.txt", "remote")
|
||||
r = await sb.exec("cat a.txt && hostname")
|
||||
await prov.drain()
|
||||
return r
|
||||
|
||||
r = asyncio.run(main())
|
||||
assert r.ok and r.stdout.startswith("remote")
|
||||
@@ -0,0 +1,112 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from pipewright.errors import BudgetExceeded
|
||||
from pipewright.scheduler import BudgetTracker, RateLimiter, SlotPool
|
||||
|
||||
|
||||
def test_rate_limiter_paces_requests_per_window():
|
||||
async def main():
|
||||
lim = RateLimiter(requests_per_minute=3, window=0.4)
|
||||
t0 = time.monotonic()
|
||||
times = []
|
||||
for _ in range(6):
|
||||
await lim.acquire(10)
|
||||
times.append(time.monotonic() - t0)
|
||||
return times
|
||||
|
||||
times = asyncio.run(main())
|
||||
assert max(times[:3]) < 0.1 # first window admits 3 immediately
|
||||
assert times[3] >= 0.35 and times[5] >= 0.35 # the rest waits for the window to roll
|
||||
|
||||
|
||||
def test_rejected_requests_count_and_close_gate():
|
||||
async def main():
|
||||
lim = RateLimiter(requests_per_minute=100, window=1.0)
|
||||
await lim.acquire(1)
|
||||
lim.reject(retry_after=0.3) # 429 with Retry-After
|
||||
t0 = time.monotonic()
|
||||
await lim.acquire(1)
|
||||
return time.monotonic() - t0, lim.snapshot()
|
||||
|
||||
waited, snap = asyncio.run(main())
|
||||
assert waited >= 0.3
|
||||
assert snap["rejected"] == 1 and snap["in_window"] == 2 # the rejected request still counts
|
||||
|
||||
|
||||
def test_output_token_budget_uses_estimate_and_settles():
|
||||
async def main():
|
||||
lim = RateLimiter(output_tokens_per_minute=1000, window=0.3, initial_output_estimate=400)
|
||||
a = await lim.acquire(0)
|
||||
b = await lim.acquire(0)
|
||||
t0 = time.monotonic()
|
||||
a.settle(10)
|
||||
b.settle(10) # actual output much smaller than the estimate
|
||||
await lim.acquire(0)
|
||||
return time.monotonic() - t0
|
||||
|
||||
assert asyncio.run(main()) < 0.1
|
||||
|
||||
|
||||
def test_priority_order():
|
||||
async def main():
|
||||
lim = RateLimiter(requests_per_minute=1, window=0.2)
|
||||
await lim.acquire(0)
|
||||
order = []
|
||||
|
||||
async def req(name, prio):
|
||||
await lim.acquire(0, priority=prio)
|
||||
order.append(name)
|
||||
|
||||
await asyncio.gather(req("shallow", 0), req("deep", -5), req("mid", -2))
|
||||
return order
|
||||
|
||||
assert asyncio.run(main()) == ["deep", "mid", "shallow"]
|
||||
|
||||
|
||||
def test_slot_pool_limits_concurrency():
|
||||
async def main():
|
||||
pool = SlotPool(2)
|
||||
live, peak = 0, 0
|
||||
|
||||
async def work():
|
||||
nonlocal live, peak
|
||||
await pool.acquire()
|
||||
live += 1
|
||||
peak = max(peak, live)
|
||||
await asyncio.sleep(0.02)
|
||||
live -= 1
|
||||
pool.release()
|
||||
|
||||
await asyncio.gather(*(work() for _ in range(7)))
|
||||
return peak, pool.in_use
|
||||
|
||||
assert asyncio.run(main()) == (2, 0)
|
||||
|
||||
|
||||
def test_budget():
|
||||
b = BudgetTracker(usd=1.0)
|
||||
b.add(usd=0.4)
|
||||
b.check()
|
||||
b.add(usd=0.7)
|
||||
with pytest.raises(BudgetExceeded):
|
||||
b.check()
|
||||
assert "usd" in b.snapshot()["exceeded"]
|
||||
|
||||
|
||||
def test_counter_budget_limits_only_that_counter():
|
||||
import pytest
|
||||
|
||||
from pipewright.errors import BudgetExceeded
|
||||
from pipewright.scheduler import BudgetTracker
|
||||
|
||||
b = BudgetTracker(counters={"rollouts.terra": 2})
|
||||
b.count("rollouts.terra")
|
||||
b.count("rollouts.terra")
|
||||
with pytest.raises(BudgetExceeded):
|
||||
b.count("rollouts.terra")
|
||||
b.count("other", 5) # unlimited counters are tracked
|
||||
b.check() # global budget not exceeded
|
||||
assert b.snapshot()["counters"] == {"rollouts.terra": 2, "other": 5}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Several worker processes on one store (`--shard I/N`), then an unsharded replay."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
from conftest import FAKE
|
||||
|
||||
|
||||
def test_concurrent_shards_share_one_store(tmp_path):
|
||||
(tmp_path / "pipewright.yaml").write_text(yaml.safe_dump({"store": ".pipewright", **FAKE}))
|
||||
recs = [{"id": f"r{i}", "body": "w " * (i % 7 + 1)} for i in range(300)]
|
||||
(tmp_path / "g.yaml").write_text(yaml.safe_dump({"name": "sh", "nodes": {
|
||||
"src": {"type": "source.inline", "params": {"kind": "d", "records": recs}},
|
||||
"lab": {"type": "label.expr", "inputs": {"in": "src"}, "params": {"labels": {"n": "words(payload.body)"}}},
|
||||
"gen": {"type": "llm.generate", "inputs": {"in": "lab"}, "params": {"model": "m", "prompt": "{{ key }}"}},
|
||||
"grp": {"type": "join.group", "inputs": {"in": "gen"}, "params": {"by": "labels.n", "keep_members": False}},
|
||||
"out": {"type": "sink.jsonl", "inputs": {"in": "gen"}, "params": {"path": "out/x.jsonl"}},
|
||||
}}))
|
||||
cmd = [sys.executable, "-m", "pipewright.cli", "run", "g.yaml", "--quiet", "--json"]
|
||||
procs = [subprocess.Popen(cmd + ["--shard", f"{i}/3", "--group", "g1"], cwd=tmp_path, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True) for i in range(3)]
|
||||
outs = [p.communicate(timeout=120) for p in procs]
|
||||
res = [json.loads(o) for o, _ in outs]
|
||||
assert all(r["status"] == "completed" for r in res), [e[-500:] for _, e in outs]
|
||||
per_shard = [r["funnel"]["nodes"]["gen"]["events"]["ok"] for r in res]
|
||||
assert sum(per_shard) == 300 and all(n > 50 for n in per_shard)
|
||||
assert not (tmp_path / "out/x.jsonl").exists() # sinks are skipped in shard runs
|
||||
f = json.loads(subprocess.run([sys.executable, "-m", "pipewright.cli", "funnel", "g.yaml", "--group", "g1",
|
||||
"--json"], cwd=tmp_path, capture_output=True, text=True).stdout)
|
||||
assert f["nodes"]["gen"]["events"]["ok"] == 300 and len(f["runs"]) == 3
|
||||
final = json.loads(subprocess.run(cmd, cwd=tmp_path, capture_output=True, text=True).stdout)
|
||||
assert final["funnel"]["nodes"]["gen"]["events"] == {"ok": 300, "cached": 300} # pure replay
|
||||
assert (tmp_path / "out/x.jsonl").read_text().count("\n") == 300
|
||||
@@ -0,0 +1,115 @@
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import time
|
||||
|
||||
from pipewright.models.base import rate_limiter_from
|
||||
from pipewright.scheduler import RateLimiter, SharedLedger
|
||||
|
||||
|
||||
class FakeClock:
|
||||
def __init__(self, t: float = 1_000_000.0):
|
||||
self.t = t
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.t
|
||||
|
||||
|
||||
def _pair(tmp_path, clock=time.time, **kw):
|
||||
path = tmp_path / "k.sqlite"
|
||||
a = RateLimiter(shared=SharedLedger(path, clock=clock, max_poll=0.05), **kw)
|
||||
b = RateLimiter(shared=SharedLedger(path, clock=clock, max_poll=0.05), **kw)
|
||||
return a, b
|
||||
|
||||
|
||||
async def _try(lim: RateLimiter, timeout: float = 0.15):
|
||||
try:
|
||||
return await asyncio.wait_for(lim.acquire(10), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return None
|
||||
|
||||
|
||||
def test_two_limiters_share_one_window(tmp_path):
|
||||
clock = FakeClock()
|
||||
a, b = _pair(tmp_path, clock, requests_per_minute=3)
|
||||
|
||||
async def main():
|
||||
got = [await _try(a), await _try(b), await _try(a)]
|
||||
assert all(got)
|
||||
assert await _try(b) is None and await _try(a) is None # window full for both
|
||||
clock.t += 61 # window rolls
|
||||
assert await _try(b) is not None
|
||||
|
||||
asyncio.run(main())
|
||||
assert a.snapshot()["in_window"] == 1 and b.stats["admitted"] == 2
|
||||
|
||||
|
||||
def test_gate_set_by_one_blocks_the_other(tmp_path):
|
||||
a, b = _pair(tmp_path, requests_per_minute=100)
|
||||
|
||||
async def main():
|
||||
await a.acquire(1)
|
||||
a.reject(retry_after=0.3)
|
||||
t0 = time.monotonic()
|
||||
await b.acquire(1)
|
||||
return time.monotonic() - t0
|
||||
|
||||
assert asyncio.run(main()) >= 0.25
|
||||
assert b.snapshot()["in_window"] == 2 # the rejected request still counts
|
||||
|
||||
|
||||
def test_settle_updates_shared_totals(tmp_path):
|
||||
clock = FakeClock()
|
||||
a, b = _pair(tmp_path, clock, output_tokens_per_minute=1000, initial_output_estimate=400)
|
||||
|
||||
async def main():
|
||||
x = await _try(a)
|
||||
y = await _try(b)
|
||||
assert await _try(a) is None # 400 + 400 + 400 > 1000
|
||||
x.settle(10)
|
||||
y.settle(20)
|
||||
assert a.shared.totals(a.window)["output_tokens"] == 30
|
||||
assert await _try(b) is not None
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
def test_config_shared_key_and_dir(tmp_path):
|
||||
lim = rate_limiter_from({"requests_per_minute": 5, "shared": True, "shared_dir": "rate"}, "morph", tmp_path)
|
||||
assert lim.shared.path == tmp_path / "rate" / "morph.sqlite"
|
||||
lim = rate_limiter_from({"shared": "team/key"}, "morph")
|
||||
assert lim.shared.path.name == "team_key.sqlite"
|
||||
assert rate_limiter_from({"requests_per_minute": 5}, "morph").shared is None
|
||||
|
||||
|
||||
def _worker(path: str, barrier, q) -> None:
|
||||
async def main():
|
||||
lim = RateLimiter(requests_per_minute=4, window=2.0, shared=SharedLedger(path, max_poll=0.02))
|
||||
lim.shared.totals(1.0) # open + create the ledger before the race starts
|
||||
barrier.wait(10)
|
||||
stop = time.time() + 1.0 # well inside the 2 s window: nothing expires
|
||||
n = 0
|
||||
while time.time() < stop:
|
||||
try:
|
||||
await asyncio.wait_for(lim.acquire(1), max(0.01, stop - time.time()))
|
||||
n += 1
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
return n
|
||||
|
||||
q.put(asyncio.run(main()))
|
||||
|
||||
|
||||
def test_multiprocess_joint_admission(tmp_path):
|
||||
ctx = mp.get_context("spawn")
|
||||
q, barrier = ctx.Queue(), ctx.Barrier(3)
|
||||
procs = [ctx.Process(target=_worker, args=(str(tmp_path / "rate.sqlite"), barrier, q)) for _ in range(3)]
|
||||
for p in procs:
|
||||
p.start()
|
||||
try:
|
||||
counts = [q.get(timeout=15) for _ in procs]
|
||||
finally:
|
||||
for p in procs:
|
||||
p.join(5)
|
||||
if p.is_alive():
|
||||
p.kill()
|
||||
assert sum(counts) == 4, counts
|
||||
@@ -0,0 +1,101 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from pipewright import Graph
|
||||
from pipewright.engine import Engine, RunOptions
|
||||
from pipewright.nodes.builtin import SinkJsonl
|
||||
from pipewright.store import Store
|
||||
|
||||
|
||||
def recs(n):
|
||||
return [{"id": f"r{i}", "body": f"text {i}"} for i in range(n)]
|
||||
|
||||
|
||||
def spec(records, **sink):
|
||||
g = Graph("sink")
|
||||
src = g.add("src", "source.inline", kind="doc", records=records)
|
||||
g.add("sink", "sink.jsonl", input=src, path="out/x.jsonl", **sink)
|
||||
return g.to_spec()
|
||||
|
||||
|
||||
def run(s, proj):
|
||||
store = Store(proj.store_dir)
|
||||
try:
|
||||
summary = asyncio.run(Engine(s, proj, store).run(RunOptions()))
|
||||
finally:
|
||||
store.close()
|
||||
return summary["funnel"]["nodes"]["sink"]
|
||||
|
||||
|
||||
def lines(proj):
|
||||
return (proj.base_dir / "out/x.jsonl").read_text().splitlines()
|
||||
|
||||
|
||||
def test_rerun_appends_only_new_items(make_project):
|
||||
proj = make_project()
|
||||
run(spec(recs(3)), proj)
|
||||
first = lines(proj)
|
||||
assert len(first) == 3
|
||||
assert (proj.base_dir / "out/x.jsonl.pwindex").exists()
|
||||
run(spec(recs(3)), proj)
|
||||
assert lines(proj) == first # nothing new
|
||||
run(spec(recs(3) + [{"id": "a-new", "body": "fresh"}]), proj)
|
||||
after = lines(proj)
|
||||
assert after[:3] == first and len(after) == 4
|
||||
assert json.loads(after[3])["key"] == "a-new" # appended at the end, not re-sorted
|
||||
run(spec(recs(1)), proj) # items that vanish stay in the append-only log
|
||||
assert len(lines(proj)) == 4
|
||||
|
||||
|
||||
def test_first_append_run_matches_rewrite(make_project):
|
||||
proj = make_project()
|
||||
run(spec(recs(4), mode="rewrite"), proj)
|
||||
rewritten = lines(proj)
|
||||
(proj.base_dir / "out/x.jsonl").unlink()
|
||||
run(spec(recs(4)), proj)
|
||||
assert lines(proj) == rewritten
|
||||
|
||||
|
||||
def test_truncated_file_triggers_full_rewrite(make_project):
|
||||
proj = make_project()
|
||||
run(spec(recs(3)), proj)
|
||||
full = lines(proj)
|
||||
out = proj.base_dir / "out/x.jsonl"
|
||||
out.write_text(full[0] + "\n") # someone truncated it
|
||||
run(spec(recs(3)), proj)
|
||||
assert lines(proj) == full
|
||||
out.unlink() # missing file
|
||||
run(spec(recs(3)), proj)
|
||||
assert lines(proj) == full
|
||||
|
||||
|
||||
def test_param_change_triggers_rewrite(make_project):
|
||||
proj = make_project()
|
||||
run(spec(recs(3)), proj)
|
||||
run(spec(recs(3), fields=["key", "payload.body"]), proj)
|
||||
rows = [json.loads(x) for x in lines(proj)]
|
||||
assert len(rows) == 3 and all(set(r) == {"key", "payload.body"} for r in rows)
|
||||
run(spec(recs(3), fields=["key", "payload.body"], lineage=True), proj)
|
||||
assert all("producer" in json.loads(x) for x in lines(proj))
|
||||
|
||||
|
||||
def test_rewrite_mode_rewrites_every_run(make_project):
|
||||
proj = make_project()
|
||||
run(spec(recs(3), mode="rewrite"), proj)
|
||||
run(spec(recs(2), mode="rewrite"), proj)
|
||||
assert [json.loads(x)["key"] for x in lines(proj)] == ["r0", "r1"]
|
||||
assert not (proj.base_dir / "out/x.jsonl.pwindex").exists()
|
||||
|
||||
|
||||
def test_write_result_reports_total_and_appended(tmp_path):
|
||||
from pipewright.items import new_item
|
||||
|
||||
class Ctx:
|
||||
def resolve_path(self, p):
|
||||
return tmp_path / p
|
||||
|
||||
sink = SinkJsonl("sink", SinkJsonl.Params(path="o.jsonl"))
|
||||
items = [new_item(f"k{i}", "doc", {"i": i}) for i in range(3)]
|
||||
assert asyncio.run(sink.write(items[:2], Ctx())) == {"path": str(tmp_path / "o.jsonl"), "rows": 2, "appended": 2}
|
||||
assert asyncio.run(sink.write(items, Ctx()))["rows"] == 3
|
||||
assert asyncio.run(sink.write(items, Ctx()))["appended"] == 0
|
||||
Reference in New Issue
Block a user