replaygate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. replaygate/__init__.py +3 -0
  2. replaygate/_seed.py +16 -0
  3. replaygate/adapters/__init__.py +1 -0
  4. replaygate/adapters/crewai.py +74 -0
  5. replaygate/adapters/langgraph.py +131 -0
  6. replaygate/adapters/mlflow.py +51 -0
  7. replaygate/adapters/spans.py +70 -0
  8. replaygate/attribute/__init__.py +0 -0
  9. replaygate/attribute/causal.py +27 -0
  10. replaygate/backends/__init__.py +0 -0
  11. replaygate/backends/base.py +51 -0
  12. replaygate/backends/cloud.py +123 -0
  13. replaygate/backends/fixture.py +48 -0
  14. replaygate/backends/ollama.py +66 -0
  15. replaygate/cli.py +220 -0
  16. replaygate/evaluate/__init__.py +0 -0
  17. replaygate/evaluate/judge.py +51 -0
  18. replaygate/evaluate/population.py +42 -0
  19. replaygate/evaluate/quality.py +40 -0
  20. replaygate/graph/__init__.py +0 -0
  21. replaygate/graph/dag.py +35 -0
  22. replaygate/instrument.py +146 -0
  23. replaygate/intervene/__init__.py +0 -0
  24. replaygate/intervene/apply.py +12 -0
  25. replaygate/models.py +147 -0
  26. replaygate/replay/__init__.py +0 -0
  27. replaygate/replay/engine.py +115 -0
  28. replaygate/replay/validity.py +39 -0
  29. replaygate/report/__init__.py +0 -0
  30. replaygate/report/diff.py +125 -0
  31. replaygate/report/verdict.py +128 -0
  32. replaygate/soundness/__init__.py +0 -0
  33. replaygate/soundness/ledger.py +34 -0
  34. replaygate/store/__init__.py +0 -0
  35. replaygate/store/db.py +145 -0
  36. replaygate/store/validate.py +47 -0
  37. replaygate-0.1.0.dist-info/METADATA +208 -0
  38. replaygate-0.1.0.dist-info/RECORD +42 -0
  39. replaygate-0.1.0.dist-info/WHEEL +5 -0
  40. replaygate-0.1.0.dist-info/entry_points.txt +2 -0
  41. replaygate-0.1.0.dist-info/licenses/LICENSE +21 -0
  42. replaygate-0.1.0.dist-info/top_level.txt +1 -0
replaygate/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """ReplayGate — causal regression testing for model/prompt changes in LLM-agent pipelines."""
2
+
3
+ __version__ = "0.1.0"
replaygate/_seed.py ADDED
@@ -0,0 +1,16 @@
1
+ """Global seeding so benchmarks and bootstrap CIs are reproducible."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+
7
+ import numpy as np
8
+
9
+ DEFAULT_SEED = 1729
10
+
11
+
12
+ def seed_all(seed: int = DEFAULT_SEED) -> np.random.Generator:
13
+ """Seed stdlib + numpy and return a dedicated numpy Generator."""
14
+ random.seed(seed)
15
+ np.random.seed(seed)
16
+ return np.random.default_rng(seed)
@@ -0,0 +1 @@
1
+ """Framework adapters that capture ReplayGate traces with minimal user code."""
@@ -0,0 +1,74 @@
1
+ """CrewAI → ReplayGate trace.
2
+
3
+ CrewAI is task-based: a Task may declare `context=[other_task, ...]`, which is an
4
+ EXPLICIT data dependency (unlike control-flow spans), so CrewAI maps unusually
5
+ cleanly — those context links become the declared dependency edges.
6
+
7
+ trace = trace_from_crewai(tasks=[t1, t2, t3], crew_output=crew.kickoff())
8
+
9
+ `tasks` is the ordered list of CrewAI Task objects; `crew_output` is the
10
+ CrewOutput returned by `crew.kickoff()` (its `.tasks_output[i].raw` aligns with
11
+ `tasks[i]`). Produces a single-trajectory trace; call once per run and merge, or
12
+ pass several runs via `extra_runs`. Validated against CrewAI's documented Task/
13
+ CrewOutput shape — confirm against your CrewAI version. DAG-only (task context
14
+ must be acyclic)."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from replaygate.adapters.spans import _as_str, _attr
19
+ from replaygate.replay.validity import fingerprint
20
+
21
+
22
+ def _task_name(task, idx: int) -> str:
23
+ name = _attr(task, "name")
24
+ if name:
25
+ return str(name)
26
+ desc = _attr(task, "description")
27
+ return (str(desc)[:40] if desc else f"task_{idx}")
28
+
29
+
30
+ def _run_outputs(tasks, crew_output) -> dict[str, str]:
31
+ outs = _attr(crew_output, "tasks_output") or []
32
+ result = {}
33
+ for i, task in enumerate(tasks):
34
+ name = _task_name(task, i)
35
+ to = outs[i] if i < len(outs) else None
36
+ result[name] = _as_str(_attr(to, "raw") if to is not None else "")
37
+ return result
38
+
39
+
40
+ def trace_from_crewai(tasks, crew_output, workflow_id: str = "crewai",
41
+ extra_runs=None, model_id: str = "task",
42
+ prompt_id: str = "default") -> dict:
43
+ names = [_task_name(t, i) for i, t in enumerate(tasks)]
44
+ name_set = set(names)
45
+ edges = set()
46
+ for i, t in enumerate(tasks):
47
+ for c in (_attr(t, "context") or []):
48
+ cn = _task_name(c, -1)
49
+ if cn in name_set:
50
+ edges.add((cn, names[i]))
51
+ preds = {n: [s for s, d in edges if d == n] for n in names}
52
+
53
+ runs = [crew_output] + list(extra_runs or [])
54
+ trajectories = []
55
+ for ri, out in enumerate(runs):
56
+ outputs = _run_outputs(tasks, out)
57
+ steps = []
58
+ for i, name in enumerate(names):
59
+ p = {d: outputs[d] for d in preds[name] if d in outputs}
60
+ o = outputs.get(name, "")
61
+ steps.append({
62
+ "step_index": i, "node_name": name,
63
+ "input_fingerprint": fingerprint(name, model_id, prompt_id, p),
64
+ "output": o, "model_id": model_id, "prompt_id": prompt_id,
65
+ "cost": {"tokens": max(1, len(o) // 4), "latency_ms": 0.0},
66
+ })
67
+ trajectories.append({"trajectory_id": f"{workflow_id}-t{ri}", "steps": steps})
68
+
69
+ return {
70
+ "workflow_id": workflow_id,
71
+ "graph": {"nodes": names, "edges": [list(e) for e in sorted(edges)]},
72
+ "prompts": {},
73
+ "trajectories": trajectories,
74
+ }
@@ -0,0 +1,131 @@
1
+ """Capture a ReplayGate trace from a compiled LangGraph app — near-zero code.
2
+
3
+ from replaygate.adapters.langgraph import trace_from_langgraph
4
+ app = graph.compile()
5
+
6
+ # minimal: every node gets a generic model/prompt id
7
+ trace = trace_from_langgraph(app, inputs=[{"q": q} for q in questions])
8
+
9
+ # recommended: give each LLM node its real prompt id + text, so a prompt-change
10
+ # intervention can target one node AND the recompute backend knows what to re-run
11
+ trace = trace_from_langgraph(
12
+ app, inputs,
13
+ node_prompts={"planner": "plan.v1", "answerer": "answer.v1"},
14
+ node_models={"planner": "gpt-4o", "answerer": "gpt-4o"},
15
+ prompts={"plan.v1": "Plan how to answer.", "answer.v1": "Answer using the plan."},
16
+ )
17
+ # -> ingest with store.workflow_from_dict(trace) or dump to JSON for the CLI
18
+
19
+ How it works: the compiled graph's nodes/edges give the declared dependency DAG,
20
+ and `app.stream(input, stream_mode="updates")` yields each node's output as it
21
+ runs, so inputs/outputs/fingerprints are captured automatically.
22
+
23
+ Why per-node ids matter: recompute looks a node's `prompt_id` up in the trace's
24
+ `prompts` map to rebuild what to run. If every node shares one id with no text
25
+ (the bare-minimum default), only the *intervened* node can be recomputed from a
26
+ supplied prompt — recomputing *downstream* nodes has no prompt to use. Pass
27
+ `node_prompts` + `prompts` (and `node_models`) so the affected subgraph is
28
+ recompute-READY.
29
+
30
+ SCOPE (what this does and does NOT do):
31
+ - It captures metadata (graph, per-node ids, prompts, fingerprints) so the trace
32
+ ingests and a change can be *gated*. It does NOT guarantee that recomputation
33
+ reproduces the original node's execution.
34
+ - A captured node's recorded output is whatever the node actually produced; the
35
+ recompute backend (e.g. Ollama) re-runs an LLM from the prompt + predecessor
36
+ outputs. If the original node was not that same LLM call (a Python function, a
37
+ tool call, hidden state), the recomputed output will differ for reasons that
38
+ are NOT a model/prompt regression. Point this at genuinely LLM-backed nodes.
39
+ - ENTRY nodes (no declared predecessor) do not carry their initial LangGraph
40
+ inputs in the fingerprint or `current_outputs`, and backends treat them as
41
+ sources (echo the recorded output). So an intervention on the FIRST node is
42
+ not faithfully recomputed yet — target a downstream node, or use the explicit
43
+ `InstrumentedAgent` seam. Capturing initial inputs as source dependencies is
44
+ future work.
45
+
46
+ HONEST CAVEAT (soundness): LangGraph nodes read a SHARED state object, so a
47
+ node's true inputs can include state written by non-adjacent nodes. Using the
48
+ graph's control-flow edges as the declared dependency edges therefore
49
+ UNDER-declares data dependencies — the classic missing-edge risk. This capture's
50
+ declared dependencies are UNVERIFIED (the trace carries
51
+ `dependency_coverage="unverified"`); `reuse_exposure` and the benchmark measure
52
+ the GENERAL risk, not whether THIS workflow's dependencies are complete. For
53
+ sound reuse, add the missing edges or use the explicit `InstrumentedAgent` seam.
54
+ v1 supports DAG graphs only (a node revisited in a loop is rejected)."""
55
+
56
+ from __future__ import annotations
57
+
58
+ import json
59
+ import warnings
60
+
61
+ from replaygate.replay.validity import fingerprint
62
+
63
+ _SPECIAL = {"__start__", "__end__"}
64
+
65
+ _MISSING_EDGE_WARNING = (
66
+ "replaygate: LangGraph control-flow edges may under-declare true data "
67
+ "dependencies (nodes share one state object), so THIS capture's declared "
68
+ "dependencies are unverified (dependency_coverage='unverified'). reuse_exposure "
69
+ "and the benchmark measure the general risk, not this workflow's completeness. "
70
+ "For sound reuse, add the missing edges or use the explicit InstrumentedAgent seam."
71
+ )
72
+
73
+
74
+ def trace_from_langgraph(app, inputs, workflow_id: str = "langgraph",
75
+ model_id: str = "node", prompt_id: str = "default",
76
+ node_models: dict | None = None,
77
+ node_prompts: dict | None = None,
78
+ prompts: dict | None = None,
79
+ warn: bool = True) -> dict:
80
+ """Run a compiled LangGraph `app` over each input and return a ReplayGate
81
+ trace dict (contract: trace-input.md). `inputs` is a list of initial states.
82
+
83
+ Per-node identity (so interventions can target one node and recompute works):
84
+ - node_models: {node: model_id} (falls back to `model_id`)
85
+ - node_prompts: {node: prompt_id} (falls back to `prompt_id`)
86
+ - prompts: {prompt_id: prompt_text} -> the trace's prompts map, which the
87
+ recompute backend reads to rebuild each node's prompt.
88
+ `warn=False` silences the missing-edge capture warning.
89
+ """
90
+ node_models = node_models or {}
91
+ node_prompts = node_prompts or {}
92
+
93
+ drawable = app.get_graph()
94
+ real = [n for n in drawable.nodes if n not in _SPECIAL]
95
+ edges = [(e.source, e.target) for e in drawable.edges
96
+ if e.source in real and e.target in real]
97
+ preds = {n: [s for s, t in edges if t == n] for n in real}
98
+
99
+ if warn and any(preds[n] for n in real):
100
+ warnings.warn(_MISSING_EDGE_WARNING, stacklevel=2)
101
+
102
+ trajectories = []
103
+ for i, inp in enumerate(inputs):
104
+ outputs: dict[str, str] = {}
105
+ steps: list[dict] = []
106
+ for chunk in app.stream(inp, stream_mode="updates"):
107
+ for node, update in chunk.items():
108
+ if node not in real:
109
+ continue
110
+ nm = node_models.get(node, model_id)
111
+ npid = node_prompts.get(node, prompt_id)
112
+ out = json.dumps(update, default=str, sort_keys=True)
113
+ p = {d: outputs[d] for d in preds[node] if d in outputs}
114
+ steps.append({
115
+ "step_index": len(steps), "node_name": node,
116
+ "input_fingerprint": fingerprint(node, nm, npid, p),
117
+ "output": out, "model_id": nm, "prompt_id": npid,
118
+ "cost": {"tokens": max(1, len(out) // 4), "latency_ms": 0.0},
119
+ })
120
+ outputs[node] = out
121
+ trajectories.append({"trajectory_id": f"{workflow_id}-t{i}", "steps": steps})
122
+
123
+ return {
124
+ "workflow_id": workflow_id,
125
+ "graph": {"nodes": real, "edges": [list(e) for e in edges]},
126
+ "prompts": dict(prompts or {}),
127
+ # Declared deps come from control-flow edges only; completeness is not proven
128
+ # for this workflow (shared-state reads may be undeclared). See module docstring.
129
+ "dependency_coverage": "unverified",
130
+ "trajectories": trajectories,
131
+ }
@@ -0,0 +1,51 @@
1
+ """MLflow Tracing → ReplayGate trace (thin shim over the generic span core).
2
+
3
+ import mlflow
4
+ # ... run your agent under mlflow tracing ...
5
+ traces = mlflow.search_traces(...) # or a single trace object
6
+ cs_trace = trace_from_mlflow(traces)
7
+
8
+ MLflow spans expose span_id / parent_id / name / outputs; we resolve
9
+ parent_id → parent node name and delegate to trace_from_spans. Works on MLflow
10
+ Trace objects (`.data.spans`) or already-extracted span lists. Validated against
11
+ MLflow's documented span shape — confirm against your MLflow version."""
12
+
13
+ from __future__ import annotations
14
+
15
+ from replaygate.adapters.spans import _attr, trace_from_spans
16
+
17
+
18
+ def _spans_of(trace):
19
+ # MLflow Trace -> .data.spans; else assume it's already a list of spans
20
+ data = _attr(trace, "data")
21
+ if data is not None:
22
+ spans = _attr(data, "spans")
23
+ if spans is not None:
24
+ return spans
25
+ if isinstance(trace, (list, tuple)):
26
+ return trace
27
+ raise TypeError("expected an MLflow Trace (with .data.spans) or a list of spans")
28
+
29
+
30
+ def _normalize(trace):
31
+ spans = _spans_of(trace)
32
+ id2name = {_attr(s, "span_id"): _attr(s, "name") for s in spans}
33
+ norm = []
34
+ for s in spans:
35
+ pid = _attr(s, "parent_id")
36
+ norm.append({
37
+ "name": _attr(s, "name"),
38
+ "parent": id2name.get(pid) if pid else None,
39
+ "output": _attr(s, "outputs"),
40
+ })
41
+ return norm
42
+
43
+
44
+ def trace_from_mlflow(traces, workflow_id: str = "mlflow", model_id: str = "span",
45
+ prompt_id: str = "default") -> dict:
46
+ """Accept a single MLflow Trace or a list of them; return a ReplayGate trace."""
47
+ many = traces if isinstance(traces, (list, tuple)) and traces and (
48
+ _attr(traces[0], "data") is not None) else [traces]
49
+ normalized = [_normalize(t) for t in many]
50
+ return trace_from_spans(normalized, workflow_id=workflow_id,
51
+ model_id=model_id, prompt_id=prompt_id)
@@ -0,0 +1,70 @@
1
+ """Generic span → ReplayGate trace core.
2
+
3
+ Most tracing stacks (OpenTelemetry / OpenInference, MLflow Tracing, the OpenAI
4
+ Agents SDK, LlamaIndex instrumentation) expose a run as spans with a name, a
5
+ parent, and an output. This converts any such span stream into a ReplayGate
6
+ trace: span name → node, parent→child → declared dependency edge, output →
7
+ recorded output, with fingerprints the replay validity predicate consumes.
8
+
9
+ A "span" here is a dict or object exposing:
10
+ - name : str (the node/step name)
11
+ - parent : str | None (the PARENT NODE NAME, or None for a root)
12
+ - output : str | Any (serialized if not a str)
13
+
14
+ `traces` is a list of trajectories; each trajectory is a list of spans in
15
+ execution order. Framework shims (mlflow.py, …) normalize to this shape.
16
+
17
+ Soundness caveat (same as all adapters): the parent/child span tree is a
18
+ CONTROL-FLOW structure. If a step truly reads data a non-parent span produced,
19
+ these edges under-declare the dependency (the missing-edge risk) — which
20
+ `reuse_exposure` and the benchmark measure, never hide. Add edges or use the
21
+ explicit seam where a step has hidden cross-span reads. DAG-only."""
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+
27
+ from replaygate.replay.validity import fingerprint
28
+
29
+
30
+ def _attr(span, key):
31
+ return span.get(key) if isinstance(span, dict) else getattr(span, key, None)
32
+
33
+
34
+ def _as_str(v) -> str:
35
+ return v if isinstance(v, str) else json.dumps(v, default=str, sort_keys=True)
36
+
37
+
38
+ def trace_from_spans(traces, workflow_id: str = "spans", model_id: str = "span",
39
+ prompt_id: str = "default") -> dict:
40
+ node_order: list[str] = []
41
+ edge_set: set[tuple[str, str]] = set()
42
+ trajectories = []
43
+
44
+ for i, spans in enumerate(traces):
45
+ outputs: dict[str, str] = {}
46
+ steps: list[dict] = []
47
+ for span in spans:
48
+ name = _attr(span, "name")
49
+ parent = _attr(span, "parent")
50
+ out = _as_str(_attr(span, "output"))
51
+ if name not in node_order:
52
+ node_order.append(name)
53
+ if parent:
54
+ edge_set.add((parent, name))
55
+ preds = {parent: outputs[parent]} if parent and parent in outputs else {}
56
+ steps.append({
57
+ "step_index": len(steps), "node_name": name,
58
+ "input_fingerprint": fingerprint(name, model_id, prompt_id, preds),
59
+ "output": out, "model_id": model_id, "prompt_id": prompt_id,
60
+ "cost": {"tokens": max(1, len(out) // 4), "latency_ms": 0.0},
61
+ })
62
+ outputs[name] = out
63
+ trajectories.append({"trajectory_id": f"{workflow_id}-t{i}", "steps": steps})
64
+
65
+ return {
66
+ "workflow_id": workflow_id,
67
+ "graph": {"nodes": node_order, "edges": [list(e) for e in sorted(edge_set)]},
68
+ "prompts": {},
69
+ "trajectories": trajectories,
70
+ }
File without changes
@@ -0,0 +1,27 @@
1
+ """Regression attribution: isolate each targeted node's causal contribution.
2
+
3
+ For each target, replay with the intervention restricted to that one node and
4
+ measure the mean quality delta it alone causes. The most-negative contribution
5
+ is the responsible decision. Single-fault first; interacting faults surface as
6
+ several negative contributions rather than all credit on one node."""
7
+
8
+ from __future__ import annotations
9
+
10
+ from replaygate.evaluate.quality import QualityEvaluator
11
+ from replaygate.graph.dag import DependencyGraph
12
+ from replaygate.models import Intervention, Trajectory
13
+ from replaygate.replay.engine import full_replay
14
+
15
+
16
+ def attribute(trajectories: list[Trajectory], graph: DependencyGraph,
17
+ intervention: Intervention, backend, evaluator: QualityEvaluator):
18
+ """Return [(node, mean_isolated_delta)] sorted most-negative first."""
19
+ contributions: list[tuple[str, float]] = []
20
+ for node, change in intervention.targets.items():
21
+ iso = Intervention(workflow_id=intervention.workflow_id, targets={node: change})
22
+ deltas = [full_replay(t, graph, iso, backend, evaluator).delta
23
+ for t in trajectories]
24
+ mean = sum(deltas) / len(deltas) if deltas else 0.0
25
+ contributions.append((node, mean))
26
+ contributions.sort(key=lambda x: x[1]) # most negative (worst) first
27
+ return contributions
File without changes
@@ -0,0 +1,51 @@
1
+ """Recompute backend contract (contracts/recompute-backend.md).
2
+
3
+ The backend recomputes a node under an intervention, given the CURRENT output of
4
+ every node. A backend may read whatever true inputs it needs from current_outputs
5
+ — modeling that the real agent's node reads its real inputs, which the tool's
6
+ declared graph may describe incompletely. Ordinary unavailability returns
7
+ Unavailable (never raises); an un-recomputable affected node makes the verdict
8
+ inconclusive, never "safe"."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Optional, Protocol, Union, runtime_checkable
14
+
15
+ from replaygate.models import Cost
16
+
17
+
18
+ @dataclass
19
+ class Produced:
20
+ output: str
21
+ cost: Cost
22
+
23
+
24
+ @dataclass
25
+ class Unavailable:
26
+ reason: str
27
+
28
+
29
+ Outcome = Union[Produced, Unavailable]
30
+
31
+
32
+ @runtime_checkable
33
+ class RecomputeBackend(Protocol):
34
+ def recompute(
35
+ self,
36
+ node_name: str,
37
+ model_id: str,
38
+ prompt_id: str,
39
+ current_outputs: dict[str, str],
40
+ predecessors: Optional[list[str]] = None,
41
+ ) -> Outcome:
42
+ ...
43
+
44
+
45
+ class UnavailableBackend:
46
+ """Default offline backend: cannot recompute anything."""
47
+ name = "unavailable"
48
+
49
+ def recompute(self, node_name, model_id, prompt_id, current_outputs,
50
+ predecessors=None) -> Outcome:
51
+ return Unavailable("no recompute backend configured")
@@ -0,0 +1,123 @@
1
+ """Cloud recompute backends (OpenAI / Anthropic), stdlib-only (urllib).
2
+
3
+ The API key is read from the ENVIRONMENT (OPENAI_API_KEY / ANTHROPIC_API_KEY) —
4
+ never passed on the command line, never logged, never echoed. Like every
5
+ backend, these degrade gracefully: a missing key, network/HTTP error, or an
6
+ exhausted call budget returns `Unavailable` (never raises), so a run proceeds
7
+ and affected nodes it cannot recompute become inconclusive (fails closed),
8
+ never "safe".
9
+
10
+ SCAFFOLD STATUS: offline-tested for the no-key / budget / response-parsing
11
+ paths; NOT exercised against the live OpenAI/Anthropic APIs here (no keys in this
12
+ environment). Validate against your account before relying on it.
13
+
14
+ Prompt construction matches the other backends: the system prompt comes from the
15
+ trace's prompt registry (prompt_id → text); the user message is the node's
16
+ declared-predecessor outputs. Only the user's own run sends data to the provider.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import urllib.error
24
+ import urllib.request
25
+ from typing import Optional
26
+
27
+ from replaygate.backends.base import Outcome, Produced, Unavailable
28
+ from replaygate.models import Cost
29
+
30
+
31
+ class _CloudBackend:
32
+ env_var = "" # subclass sets
33
+ default_model = ""
34
+ default_url = ""
35
+
36
+ def __init__(self, model: Optional[str] = None, prompts: Optional[dict] = None,
37
+ max_calls: Optional[int] = None, max_tokens: int = 256,
38
+ timeout: float = 60.0, base_url: Optional[str] = None,
39
+ api_key: Optional[str] = None):
40
+ self.model = model or self.default_model
41
+ self.prompts = prompts or {}
42
+ self.max_calls = max_calls
43
+ self.max_tokens = max_tokens
44
+ self.timeout = timeout
45
+ self.url = (base_url or self.default_url)
46
+ # read from env if not explicitly provided; value is never stored in logs/output
47
+ self._key = api_key or os.environ.get(self.env_var)
48
+ self.calls = 0
49
+ self.name = f"{self.__class__.__name__}:{self.model}"
50
+
51
+ # subclasses implement the request/response wire format
52
+ def _headers(self) -> dict: raise NotImplementedError
53
+ def _body(self, system: str, user: str) -> dict: raise NotImplementedError
54
+ def _parse(self, resp: dict) -> tuple[Optional[str], int]: raise NotImplementedError
55
+
56
+ def recompute(self, node_name, model_id, prompt_id, current_outputs,
57
+ predecessors=None) -> Outcome:
58
+ preds = predecessors if predecessors is not None else list(current_outputs)
59
+ if not preds: # source node: external input, echoed not regenerated
60
+ return Produced(output=current_outputs.get(node_name, ""), cost=Cost(0, 0.0))
61
+ if not self._key:
62
+ return Unavailable(f"no {self.env_var} in environment")
63
+ if self.max_calls is not None and self.calls >= self.max_calls:
64
+ return Unavailable("recompute budget exhausted")
65
+
66
+ system = self.prompts.get(prompt_id, f"You are the '{node_name}' step; "
67
+ f"produce only this step's output.")
68
+ user = "Inputs:\n" + "\n".join(f"[{p}]: {current_outputs.get(p, '')}" for p in preds)
69
+ payload = json.dumps(self._body(system, user)).encode()
70
+ req = urllib.request.Request(self.url, data=payload, headers=self._headers())
71
+ try:
72
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
73
+ body = json.loads(r.read().decode())
74
+ text, tokens = self._parse(body)
75
+ if not text:
76
+ return Unavailable("empty response")
77
+ self.calls += 1
78
+ return Produced(output=text, cost=Cost(tokens=tokens, latency_ms=0.0))
79
+ except (urllib.error.URLError, TimeoutError, ValueError, KeyError, OSError) as e:
80
+ return Unavailable(f"{type(e).__name__}: {e}")
81
+
82
+
83
+ class OpenAIBackend(_CloudBackend):
84
+ env_var = "OPENAI_API_KEY"
85
+ default_model = "gpt-4o-mini"
86
+ default_url = "https://api.openai.com/v1/chat/completions"
87
+
88
+ def _headers(self):
89
+ return {"Content-Type": "application/json", "Authorization": f"Bearer {self._key}"}
90
+
91
+ def _body(self, system, user):
92
+ return {"model": self.model, "max_tokens": self.max_tokens,
93
+ "messages": [{"role": "system", "content": system},
94
+ {"role": "user", "content": user}]}
95
+
96
+ def _parse(self, resp):
97
+ text = resp["choices"][0]["message"]["content"].strip()
98
+ tokens = int(resp.get("usage", {}).get("total_tokens", 0))
99
+ return text, tokens
100
+
101
+
102
+ class AnthropicBackend(_CloudBackend):
103
+ env_var = "ANTHROPIC_API_KEY"
104
+ default_model = "claude-3-5-haiku-latest"
105
+ default_url = "https://api.anthropic.com/v1/messages"
106
+
107
+ def _headers(self):
108
+ return {"Content-Type": "application/json", "x-api-key": self._key,
109
+ "anthropic-version": "2023-06-01"}
110
+
111
+ def _body(self, system, user):
112
+ return {"model": self.model, "max_tokens": self.max_tokens, "system": system,
113
+ "messages": [{"role": "user", "content": user}]}
114
+
115
+ def _parse(self, resp):
116
+ text = "".join(b.get("text", "") for b in resp.get("content", [])).strip()
117
+ u = resp.get("usage", {})
118
+ tokens = int(u.get("input_tokens", 0)) + int(u.get("output_tokens", 0))
119
+ return text, tokens
120
+
121
+
122
+ def make_cloud_backend(name: str, **kw) -> _CloudBackend:
123
+ return {"openai": OpenAIBackend, "anthropic": AnthropicBackend}[name](**kw)
@@ -0,0 +1,48 @@
1
+ """Deterministic numeric backend for the injected-fault benchmark.
2
+
3
+ Each node emits a numeric 'signal' (encoded as a string) computed from its TRUE
4
+ predecessors' signals plus a per-(node, model) delta. The true dependency
5
+ structure lives here, not in the declared graph — so a declared graph that omits
6
+ a true edge cannot be caught by reuse, which is exactly the false-negative the
7
+ benchmark measures. No LLM is involved, so results are reproducible offline."""
8
+
9
+ from __future__ import annotations
10
+
11
+ from replaygate.backends.base import Outcome, Produced
12
+ from replaygate.models import Cost
13
+
14
+
15
+ def _to_f(v: str) -> float:
16
+ try:
17
+ return float(v)
18
+ except (TypeError, ValueError):
19
+ return 0.0
20
+
21
+
22
+ class FixtureBackend:
23
+ """
24
+ true_deps: node -> list of true predecessor nodes (may exceed declared edges)
25
+ base: node -> base signal
26
+ model_delta: (node, model_id) -> additive delta (a 'bad' model lowers signal)
27
+ """
28
+ name = "fixture"
29
+
30
+ def __init__(self, true_deps, base, model_delta, sources=None):
31
+ self.true_deps = true_deps
32
+ self.base = base
33
+ self.model_delta = model_delta
34
+ self.sources = set(sources or ())
35
+ self.calls = 0
36
+
37
+ def recompute(self, node_name, model_id, prompt_id, current_outputs,
38
+ predecessors=None) -> Outcome:
39
+ self.calls += 1
40
+ # Sources are per-trajectory inputs, not recomputed: return them unchanged.
41
+ if node_name in self.sources:
42
+ return Produced(output=current_outputs.get(node_name, "0"),
43
+ cost=Cost(tokens=0, latency_ms=0.0))
44
+ signal = self.base.get(node_name, 0.0)
45
+ for p in self.true_deps.get(node_name, []):
46
+ signal += _to_f(current_outputs.get(p, "0"))
47
+ signal += self.model_delta.get((node_name, model_id), 0.0)
48
+ return Produced(output=f"{signal:.6f}", cost=Cost(tokens=10, latency_ms=1.0))