agent-blackbox-cli 0.3.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.
- agent_blackbox_cli-0.3.0.dist-info/METADATA +623 -0
- agent_blackbox_cli-0.3.0.dist-info/RECORD +43 -0
- agent_blackbox_cli-0.3.0.dist-info/WHEEL +5 -0
- agent_blackbox_cli-0.3.0.dist-info/entry_points.txt +2 -0
- agent_blackbox_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
- agent_blackbox_cli-0.3.0.dist-info/top_level.txt +1 -0
- blackbox/__init__.py +61 -0
- blackbox/__main__.py +6 -0
- blackbox/adapters/__init__.py +0 -0
- blackbox/adapters/_linking.py +31 -0
- blackbox/adapters/base.py +38 -0
- blackbox/adapters/claude_code.py +341 -0
- blackbox/adapters/codex.py +318 -0
- blackbox/adapters/labelled_turns.py +371 -0
- blackbox/adapters/registry.py +30 -0
- blackbox/aggregate.py +119 -0
- blackbox/analysis.py +325 -0
- blackbox/bench.py +466 -0
- blackbox/cli.py +405 -0
- blackbox/cost.py +138 -0
- blackbox/describe.py +116 -0
- blackbox/detectors/__init__.py +32 -0
- blackbox/detectors/base.py +83 -0
- blackbox/detectors/context_bloat.py +137 -0
- blackbox/detectors/contradictions.py +180 -0
- blackbox/detectors/error_clusters.py +114 -0
- blackbox/detectors/retry_loops.py +98 -0
- blackbox/detectors/stalls.py +117 -0
- blackbox/detectors/thrash.py +86 -0
- blackbox/diff.py +123 -0
- blackbox/discover.py +189 -0
- blackbox/events.py +163 -0
- blackbox/graph.py +150 -0
- blackbox/guard.py +528 -0
- blackbox/guard_cli.py +349 -0
- blackbox/pricing.py +137 -0
- blackbox/py.typed +0 -0
- blackbox/replay.py +65 -0
- blackbox/report/__init__.py +0 -0
- blackbox/report/html.py +375 -0
- blackbox/report/text.py +287 -0
- blackbox/store.py +215 -0
- blackbox/toolinfo.py +336 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Adapter selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from blackbox.adapters import claude_code, codex, labelled_turns
|
|
6
|
+
from blackbox.adapters.base import Trace
|
|
7
|
+
|
|
8
|
+
ADAPTERS = (claude_code, codex, labelled_turns)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class NoAdapterError(RuntimeError):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load(path: str, adapter: str | None = None) -> Trace:
|
|
16
|
+
"""Parse ``path`` with the named adapter, or the first one that recognises it."""
|
|
17
|
+
if adapter:
|
|
18
|
+
for mod in ADAPTERS:
|
|
19
|
+
if mod.NAME == adapter:
|
|
20
|
+
return mod.parse(path)
|
|
21
|
+
names = ", ".join(m.NAME for m in ADAPTERS)
|
|
22
|
+
raise NoAdapterError(f"unknown adapter {adapter!r}; available: {names}")
|
|
23
|
+
|
|
24
|
+
for mod in ADAPTERS:
|
|
25
|
+
if mod.sniff(path):
|
|
26
|
+
return mod.parse(path)
|
|
27
|
+
raise NoAdapterError(
|
|
28
|
+
f"no adapter recognised {path!r}. Supported: "
|
|
29
|
+
+ ", ".join(m.NAME for m in ADAPTERS)
|
|
30
|
+
)
|
blackbox/aggregate.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Analysis across many runs.
|
|
2
|
+
|
|
3
|
+
One session answers "what happened here". A corpus answers the questions
|
|
4
|
+
people actually have: what does this agent get wrong *habitually*, what is the
|
|
5
|
+
standing cost of those habits, and is any of it getting better.
|
|
6
|
+
|
|
7
|
+
Everything here is a reduction over per-run :class:`~blackbox.analysis.Analysis`
|
|
8
|
+
objects, so an aggregate can never disagree with the individual reports.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from collections import Counter, defaultdict
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from blackbox.analysis import Analysis, analyze
|
|
19
|
+
from blackbox.detectors.base import Config
|
|
20
|
+
from blackbox.events import Usage
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Corpus:
|
|
25
|
+
runs: list[tuple[str, Analysis]] = field(default_factory=list)
|
|
26
|
+
failed: list[tuple[str, str]] = field(default_factory=list)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def total_usd(self) -> float:
|
|
30
|
+
return sum(a.cost.total_usd for _, a in self.runs)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def total_usage(self) -> Usage:
|
|
34
|
+
total = Usage()
|
|
35
|
+
for _, a in self.runs:
|
|
36
|
+
total = total + a.cost.total_usage
|
|
37
|
+
return total
|
|
38
|
+
|
|
39
|
+
def summary(self) -> dict[str, Any]:
|
|
40
|
+
tool_calls = sum(a.summary()["tool_calls"] for _, a in self.runs)
|
|
41
|
+
failures = sum(a.summary()["tool_failures"] for _, a in self.runs)
|
|
42
|
+
active = sum(a.summary()["active_seconds"] for _, a in self.runs)
|
|
43
|
+
findings = sum(len(a.findings) for _, a in self.runs)
|
|
44
|
+
|
|
45
|
+
wasted = sum(a.wasted()["usd"] for _, a in self.runs)
|
|
46
|
+
usage = self.total_usage
|
|
47
|
+
|
|
48
|
+
# What fraction of billed input was served from cache. Low means the
|
|
49
|
+
# prefix is being rebuilt; high means the cache is doing its job.
|
|
50
|
+
billed_input = usage.billed_input_tokens
|
|
51
|
+
cache_hit = usage.cache_read_tokens / billed_input if billed_input else 0.0
|
|
52
|
+
|
|
53
|
+
detector_counts: Counter[str] = Counter()
|
|
54
|
+
detector_usd: dict[str, float] = defaultdict(float)
|
|
55
|
+
thrashed: dict[str, int] = defaultdict(int)
|
|
56
|
+
loops: list[tuple[int, str, str]] = []
|
|
57
|
+
bloat: list[tuple[float, int, str, str]] = []
|
|
58
|
+
|
|
59
|
+
for source, analysis in self.runs:
|
|
60
|
+
name = os.path.basename(source)
|
|
61
|
+
for finding in analysis.findings:
|
|
62
|
+
detector_counts[finding.detector] += 1
|
|
63
|
+
detector_usd[finding.detector] += analysis.finding_usd(finding)
|
|
64
|
+
metrics = finding.metrics
|
|
65
|
+
if finding.detector == "thrash":
|
|
66
|
+
thrashed[metrics["path"]] += metrics["writes"]
|
|
67
|
+
elif finding.detector == "retry_loop" and metrics.get("kind") == "retry_loop":
|
|
68
|
+
loops.append((metrics["repeats"], metrics.get("tool", "?"), name))
|
|
69
|
+
elif finding.detector == "context_bloat":
|
|
70
|
+
bloat.append(
|
|
71
|
+
(metrics["est_downstream_usd"], metrics["est_tokens"], metrics.get("tool", "?"), name)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
"runs": len(self.runs),
|
|
76
|
+
"unreadable": len(self.failed),
|
|
77
|
+
"total_usd": round(self.total_usd, 4),
|
|
78
|
+
"wasted_usd": round(wasted, 4),
|
|
79
|
+
"wasted_share": round(wasted / self.total_usd, 6) if self.total_usd else 0.0,
|
|
80
|
+
"tool_calls": tool_calls,
|
|
81
|
+
"tool_failures": failures,
|
|
82
|
+
"failure_rate": round(failures / tool_calls, 6) if tool_calls else 0.0,
|
|
83
|
+
"active_seconds": round(active, 2),
|
|
84
|
+
"findings": findings,
|
|
85
|
+
"cache_hit_rate": round(cache_hit, 6),
|
|
86
|
+
"cache_write_1h_tokens": usage.cache_write_1h_tokens,
|
|
87
|
+
"tokens": usage.total_tokens,
|
|
88
|
+
"by_detector": {k: detector_counts[k] for k in sorted(detector_counts)},
|
|
89
|
+
"usd_by_detector": {k: round(detector_usd[k], 4) for k in sorted(detector_usd)},
|
|
90
|
+
"top_thrashed": [
|
|
91
|
+
{"path": path, "writes": writes}
|
|
92
|
+
for path, writes in sorted(thrashed.items(), key=lambda kv: (-kv[1], kv[0]))[:8]
|
|
93
|
+
],
|
|
94
|
+
"worst_loops": [
|
|
95
|
+
{"repeats": repeats, "tool": tool, "run": run}
|
|
96
|
+
for repeats, tool, run in sorted(loops, reverse=True)[:8]
|
|
97
|
+
],
|
|
98
|
+
"worst_bloat": [
|
|
99
|
+
{"est_usd": usd, "est_tokens": tokens, "tool": tool, "run": run}
|
|
100
|
+
for usd, tokens, tool, run in sorted(bloat, reverse=True)[:8]
|
|
101
|
+
],
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load(
|
|
106
|
+
paths: list[str],
|
|
107
|
+
config: Config | None = None,
|
|
108
|
+
price_overrides: dict[str, Any] | None = None,
|
|
109
|
+
) -> Corpus:
|
|
110
|
+
"""Analyse many traces, carrying on past the ones that cannot be read."""
|
|
111
|
+
corpus = Corpus()
|
|
112
|
+
for path in paths:
|
|
113
|
+
try:
|
|
114
|
+
corpus.runs.append(
|
|
115
|
+
(path, analyze(path, config=config, price_overrides=price_overrides))
|
|
116
|
+
)
|
|
117
|
+
except Exception as exc: # a corpus scan must not die on one bad file
|
|
118
|
+
corpus.failed.append((path, f"{type(exc).__name__}: {exc}"))
|
|
119
|
+
return corpus
|
blackbox/analysis.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""The analysis pipeline: trace -> graph -> cost -> findings -> payload.
|
|
2
|
+
|
|
3
|
+
The payload is the tool's actual output contract. It contains no wall-clock
|
|
4
|
+
reads, no absolute ordering that depends on dict iteration, and no floating
|
|
5
|
+
point that is not rounded at the boundary -- so two runs over the same input
|
|
6
|
+
serialise to identical bytes. :func:`Analysis.digest` is that guarantee made
|
|
7
|
+
checkable, and ``tests/test_determinism.py`` enforces it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from collections import Counter
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from blackbox import cost as cost_mod
|
|
20
|
+
from blackbox import detectors as detectors_mod
|
|
21
|
+
from blackbox import graph as graph_mod
|
|
22
|
+
from blackbox.adapters import registry
|
|
23
|
+
from blackbox.adapters.base import Trace
|
|
24
|
+
from blackbox.describe import evidence_detail
|
|
25
|
+
from blackbox.detectors.base import Config, Finding
|
|
26
|
+
from blackbox.toolinfo import is_human_in_the_loop
|
|
27
|
+
from blackbox.events import TOOL_CALL, TOOL_RESULT as _TR # noqa: F401
|
|
28
|
+
from blackbox.events import (
|
|
29
|
+
ASSISTANT_MESSAGE,
|
|
30
|
+
TOOL_CALL,
|
|
31
|
+
TOOL_RESULT,
|
|
32
|
+
USER_MESSAGE,
|
|
33
|
+
Event,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
SCHEMA_VERSION = 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Analysis:
|
|
41
|
+
trace: Trace
|
|
42
|
+
graph: graph_mod.Graph
|
|
43
|
+
cost: cost_mod.CostReport
|
|
44
|
+
findings: list[Finding]
|
|
45
|
+
config: Config = field(default_factory=Config)
|
|
46
|
+
price_overrides: dict[str, Any] = field(default_factory=dict)
|
|
47
|
+
|
|
48
|
+
# -- summary -----------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def summary(self) -> dict[str, Any]:
|
|
51
|
+
events = self.graph.events
|
|
52
|
+
kinds = Counter(e.kind for e in events)
|
|
53
|
+
tools = Counter(e.tool_name or "?" for e in events if e.kind == TOOL_CALL)
|
|
54
|
+
# A declined call is a human saying no, not a tool breaking. Counting
|
|
55
|
+
# it as a failure overstates how badly the run went.
|
|
56
|
+
failures = sum(
|
|
57
|
+
1
|
|
58
|
+
for e in events
|
|
59
|
+
if e.kind == TOOL_RESULT and e.tool_ok is False and "declined" not in e.flags
|
|
60
|
+
)
|
|
61
|
+
declined = sum(1 for e in events if "declined" in e.flags)
|
|
62
|
+
|
|
63
|
+
# Time the run spent waiting on a person. Stalls deliberately exclude
|
|
64
|
+
# it, so it is reported here instead of vanishing.
|
|
65
|
+
human_wait = 0.0
|
|
66
|
+
for call in self.graph.tool_calls():
|
|
67
|
+
if not is_human_in_the_loop(call.tool_name):
|
|
68
|
+
continue
|
|
69
|
+
result = self.graph.result_for(call)
|
|
70
|
+
if result is not None and call.ts and result.ts:
|
|
71
|
+
gap = (result.ts - call.ts).total_seconds()
|
|
72
|
+
if gap > 0:
|
|
73
|
+
human_wait += gap
|
|
74
|
+
|
|
75
|
+
stamped = sorted(e.ts for e in events if e.ts is not None)
|
|
76
|
+
first_ts = stamped[0].isoformat() if stamped else None
|
|
77
|
+
last_ts = stamped[-1].isoformat() if stamped else None
|
|
78
|
+
span = round((stamped[-1] - stamped[0]).total_seconds(), 2) if len(stamped) > 1 else 0.0
|
|
79
|
+
|
|
80
|
+
# Span alone is misleading for a session resumed over days: it counts
|
|
81
|
+
# the nights. Active time sums only the gaps short enough to be work.
|
|
82
|
+
active = 0.0
|
|
83
|
+
for earlier, later in zip(stamped, stamped[1:]):
|
|
84
|
+
gap = (later - earlier).total_seconds()
|
|
85
|
+
if 0 <= gap <= self.config.idle_seconds:
|
|
86
|
+
active += gap
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
"events": len(events),
|
|
90
|
+
"user_messages": kinds.get(USER_MESSAGE, 0),
|
|
91
|
+
"assistant_messages": kinds.get(ASSISTANT_MESSAGE, 0),
|
|
92
|
+
"tool_calls": kinds.get(TOOL_CALL, 0),
|
|
93
|
+
"tool_results": kinds.get(TOOL_RESULT, 0),
|
|
94
|
+
"tool_failures": failures,
|
|
95
|
+
"declined_calls": declined,
|
|
96
|
+
"human_wait_seconds": round(human_wait, 2),
|
|
97
|
+
"orphan_events": self.graph.orphans,
|
|
98
|
+
"skipped_lines": self.trace.skipped_lines,
|
|
99
|
+
"models": sorted({e.model for e in events if e.model}),
|
|
100
|
+
"branches": [
|
|
101
|
+
{
|
|
102
|
+
"name": b.name,
|
|
103
|
+
"events": b.event_count,
|
|
104
|
+
"tool_calls": b.tool_calls,
|
|
105
|
+
"first_seq": b.first_seq,
|
|
106
|
+
"last_seq": b.last_seq,
|
|
107
|
+
}
|
|
108
|
+
for b in self.graph.branches
|
|
109
|
+
],
|
|
110
|
+
"subagent_branches": sum(1 for b in self.graph.branches if not b.is_main),
|
|
111
|
+
"tools": [
|
|
112
|
+
{"tool": name, "calls": count}
|
|
113
|
+
# -count then name: ties never reorder between runs.
|
|
114
|
+
for name, count in sorted(tools.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
115
|
+
],
|
|
116
|
+
"first_ts": first_ts,
|
|
117
|
+
"last_ts": last_ts,
|
|
118
|
+
"span_seconds": span,
|
|
119
|
+
"active_seconds": round(active, 2),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# -- cost attribution --------------------------------------------------
|
|
124
|
+
|
|
125
|
+
# Findings whose implicated turns represent work that did not advance the
|
|
126
|
+
# task. Polling is excluded (it is normal), and context_bloat is excluded
|
|
127
|
+
# because its figure is a downstream *estimate* -- mixing it with measured
|
|
128
|
+
# spend would launder an estimate into a hard number.
|
|
129
|
+
WASTE_DETECTORS = ("retry_loop", "thrash", "error_cluster")
|
|
130
|
+
|
|
131
|
+
def _issuing_turn(self, uid: str) -> Event | None:
|
|
132
|
+
"""Walk from a piece of evidence to the model turn that paid for it."""
|
|
133
|
+
node = self.graph.by_uid.get(uid)
|
|
134
|
+
if node is None:
|
|
135
|
+
return None
|
|
136
|
+
for _ in range(3): # result -> call -> assistant message
|
|
137
|
+
if not node.usage.is_empty():
|
|
138
|
+
return node
|
|
139
|
+
if not node.parent_uid:
|
|
140
|
+
return None
|
|
141
|
+
parent = self.graph.by_uid.get(node.parent_uid)
|
|
142
|
+
if parent is None:
|
|
143
|
+
return None
|
|
144
|
+
node = parent
|
|
145
|
+
return node if not node.usage.is_empty() else None
|
|
146
|
+
|
|
147
|
+
def _turns_behind(self, finding: Finding) -> set[str]:
|
|
148
|
+
turns = set()
|
|
149
|
+
for uid in finding.evidence:
|
|
150
|
+
turn = self._issuing_turn(uid)
|
|
151
|
+
if turn is not None:
|
|
152
|
+
turns.add(turn.uid)
|
|
153
|
+
return turns
|
|
154
|
+
|
|
155
|
+
def finding_usd(self, finding: Finding) -> float:
|
|
156
|
+
"""What the model turns behind this finding cost.
|
|
157
|
+
|
|
158
|
+
This is the *direct* cost of the turns that issued the implicated
|
|
159
|
+
calls. It deliberately excludes the downstream cost of carrying their
|
|
160
|
+
results in context, which cannot be attributed exactly -- so every
|
|
161
|
+
figure here is a floor, never an estimate dressed up as a total.
|
|
162
|
+
"""
|
|
163
|
+
return sum(
|
|
164
|
+
cost_mod.event_usd(self.graph.by_uid[uid]) for uid in sorted(self._turns_behind(finding))
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def wasted(self) -> dict[str, Any]:
|
|
168
|
+
"""Run-level waste: the union of turns behind the waste findings.
|
|
169
|
+
|
|
170
|
+
A union, not a sum: one turn can be implicated by several findings at
|
|
171
|
+
once (a failing call that was also retried), and adding the findings
|
|
172
|
+
up would bill that turn twice.
|
|
173
|
+
"""
|
|
174
|
+
turns: set[str] = set()
|
|
175
|
+
per_detector: dict[str, set[str]] = {}
|
|
176
|
+
for finding in self.findings:
|
|
177
|
+
if finding.detector not in self.WASTE_DETECTORS:
|
|
178
|
+
continue
|
|
179
|
+
if finding.detector == "retry_loop" and finding.metrics.get("kind") == "expected_repeat":
|
|
180
|
+
continue
|
|
181
|
+
behind = self._turns_behind(finding)
|
|
182
|
+
turns |= behind
|
|
183
|
+
per_detector.setdefault(finding.detector, set()).update(behind)
|
|
184
|
+
|
|
185
|
+
total = sum(cost_mod.event_usd(self.graph.by_uid[uid]) for uid in sorted(turns))
|
|
186
|
+
return {
|
|
187
|
+
"usd": round(total, 6),
|
|
188
|
+
"share_of_run": round(total / self.cost.total_usd, 6) if self.cost.total_usd else 0.0,
|
|
189
|
+
"turns": len(turns),
|
|
190
|
+
"by_detector": {
|
|
191
|
+
name: round(
|
|
192
|
+
sum(cost_mod.event_usd(self.graph.by_uid[uid]) for uid in sorted(uids)), 6
|
|
193
|
+
)
|
|
194
|
+
for name, uids in sorted(per_detector.items())
|
|
195
|
+
},
|
|
196
|
+
"is_floor": True,
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
def cost_payload(self) -> dict[str, Any]:
|
|
200
|
+
c = self.cost
|
|
201
|
+
return {
|
|
202
|
+
"total_usd": round(c.total_usd, 6),
|
|
203
|
+
"complete": c.is_complete,
|
|
204
|
+
"unpriced_models": sorted(c.unpriced_models),
|
|
205
|
+
"unpriced_tokens": c.unpriced_tokens,
|
|
206
|
+
"pricing_as_of": c.pricing_as_of,
|
|
207
|
+
"cache_write_1h_usd_share": round(c.cache_write_1h_usd_share, 6),
|
|
208
|
+
"totals": {
|
|
209
|
+
"input_tokens": c.total_usage.input_tokens,
|
|
210
|
+
"output_tokens": c.total_usage.output_tokens,
|
|
211
|
+
"cache_read_tokens": c.total_usage.cache_read_tokens,
|
|
212
|
+
"cache_write_5m_tokens": c.total_usage.cache_write_5m_tokens,
|
|
213
|
+
"cache_write_1h_tokens": c.total_usage.cache_write_1h_tokens,
|
|
214
|
+
"thinking_tokens": c.total_usage.thinking_tokens,
|
|
215
|
+
},
|
|
216
|
+
"by_model": [
|
|
217
|
+
{
|
|
218
|
+
"model": mc.model,
|
|
219
|
+
"calls": mc.calls,
|
|
220
|
+
"priced": mc.priced,
|
|
221
|
+
"input_tokens": mc.usage.input_tokens,
|
|
222
|
+
"output_tokens": mc.usage.output_tokens,
|
|
223
|
+
"cache_read_tokens": mc.usage.cache_read_tokens,
|
|
224
|
+
"cache_write_5m_tokens": mc.usage.cache_write_5m_tokens,
|
|
225
|
+
"cache_write_1h_tokens": mc.usage.cache_write_1h_tokens,
|
|
226
|
+
"thinking_tokens": mc.usage.thinking_tokens,
|
|
227
|
+
"input_usd": round(mc.input_usd, 6),
|
|
228
|
+
"output_usd": round(mc.output_usd, 6),
|
|
229
|
+
"cache_read_usd": round(mc.cache_read_usd, 6),
|
|
230
|
+
"cache_write_usd": round(mc.cache_write_usd, 6),
|
|
231
|
+
"total_usd": round(mc.total_usd, 6),
|
|
232
|
+
}
|
|
233
|
+
for mc in c.by_model
|
|
234
|
+
],
|
|
235
|
+
"by_branch": {k: round(v, 6) for k, v in sorted(c.by_branch.items())},
|
|
236
|
+
"wasted": self.wasted(),
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
def payload(self) -> dict[str, Any]:
|
|
240
|
+
return {
|
|
241
|
+
"schema_version": SCHEMA_VERSION,
|
|
242
|
+
"source": os.path.basename(self.trace.source),
|
|
243
|
+
"adapter": self.trace.adapter,
|
|
244
|
+
"config": self.config.to_dict(),
|
|
245
|
+
"price_overrides": self.price_overrides,
|
|
246
|
+
"trace_meta": {k: self.trace.meta[k] for k in sorted(self.trace.meta)},
|
|
247
|
+
"summary": self.summary(),
|
|
248
|
+
"cost": self.cost_payload(),
|
|
249
|
+
"findings": [self._finding_payload(f) for f in self.findings],
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
def _finding_payload(self, finding: Finding) -> dict[str, Any]:
|
|
253
|
+
payload = finding.to_dict()
|
|
254
|
+
payload["direct_usd"] = round(self.finding_usd(finding), 6)
|
|
255
|
+
payload["evidence_detail"] = [
|
|
256
|
+
evidence_detail(self.graph.by_uid[uid])
|
|
257
|
+
for uid in finding.evidence
|
|
258
|
+
if uid in self.graph.by_uid
|
|
259
|
+
][:12]
|
|
260
|
+
return payload
|
|
261
|
+
|
|
262
|
+
def digest(self) -> str:
|
|
263
|
+
"""SHA-256 over the canonical payload."""
|
|
264
|
+
blob = json.dumps(self.payload(), sort_keys=True, default=str, ensure_ascii=True)
|
|
265
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()
|
|
266
|
+
|
|
267
|
+
def findings_digest(self) -> str:
|
|
268
|
+
blob = json.dumps(
|
|
269
|
+
[f.to_dict() for f in self.findings], sort_keys=True, default=str, ensure_ascii=True
|
|
270
|
+
)
|
|
271
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def analyze_events(
|
|
275
|
+
events: list[Event],
|
|
276
|
+
*,
|
|
277
|
+
source: str,
|
|
278
|
+
adapter: str,
|
|
279
|
+
meta: dict[str, Any] | None = None,
|
|
280
|
+
config: Config | None = None,
|
|
281
|
+
skipped_lines: int = 0,
|
|
282
|
+
price_overrides: dict[str, Any] | None = None,
|
|
283
|
+
) -> Analysis:
|
|
284
|
+
"""Run the pipeline over already-parsed events (the replay entry point)."""
|
|
285
|
+
config = config or Config()
|
|
286
|
+
g = graph_mod.build(events)
|
|
287
|
+
c = cost_mod.compute(g.events)
|
|
288
|
+
findings = detectors_mod.run_all(g, config)
|
|
289
|
+
trace = Trace(
|
|
290
|
+
events=g.events,
|
|
291
|
+
source=source,
|
|
292
|
+
adapter=adapter,
|
|
293
|
+
meta=meta or {},
|
|
294
|
+
skipped_lines=skipped_lines,
|
|
295
|
+
)
|
|
296
|
+
return Analysis(
|
|
297
|
+
trace=trace,
|
|
298
|
+
graph=g,
|
|
299
|
+
cost=c,
|
|
300
|
+
findings=findings,
|
|
301
|
+
config=config,
|
|
302
|
+
price_overrides=price_overrides or {},
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def analyze(
|
|
307
|
+
path: str,
|
|
308
|
+
config: Config | None = None,
|
|
309
|
+
adapter: str | None = None,
|
|
310
|
+
price_overrides: dict[str, Any] | None = None,
|
|
311
|
+
) -> Analysis:
|
|
312
|
+
"""Parse and analyse a trace file."""
|
|
313
|
+
from blackbox import pricing
|
|
314
|
+
|
|
315
|
+
applied = pricing.set_overrides(price_overrides) if price_overrides else {}
|
|
316
|
+
trace = registry.load(path, adapter=adapter)
|
|
317
|
+
return analyze_events(
|
|
318
|
+
trace.events,
|
|
319
|
+
source=trace.source,
|
|
320
|
+
adapter=trace.adapter,
|
|
321
|
+
meta=trace.meta,
|
|
322
|
+
config=config,
|
|
323
|
+
skipped_lines=trace.skipped_lines,
|
|
324
|
+
price_overrides=applied,
|
|
325
|
+
)
|