226 lines
8.9 KiB
Python
226 lines
8.9 KiB
Python
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
|