tempergraph 0.7.1__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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
"""The history reader of the audit (AUD-B3, AUD-B5, AUD-B10, AUD-B11, AUD-B12, AUD-B15): the workflow's local run
|
|
2
|
+
records turned into per-unit facts that every history rule reads and nothing else.
|
|
3
|
+
|
|
4
|
+
It reads `runs/<workflow>/<task>/run.jsonl`, the activity journals of the sessions and the findings documents of the
|
|
5
|
+
runs in `--window` days and in `--version`, read-only. A log it cannot read (no parseable `run_started`) is counted in
|
|
6
|
+
`unreadable` and left out, a line it cannot parse is counted and skipped, never raised. A run whose sessions have no
|
|
7
|
+
activity journal (an older engine) is counted in `unclassified`: what needs input summaries is then `unclassified`,
|
|
8
|
+
never 0 (AUD-B10). It writes nothing and starts nothing (AUD-B6).
|
|
9
|
+
|
|
10
|
+
Record shapes it reads beyond the run log's own (`run_started`, `unit_entered`, `attempt_start`, `agent_run`,
|
|
11
|
+
`check`, `judgement`, `gate`, `pause`, `human`, `supervision`, `outcome`): `judgement.no_change` (the blockers that
|
|
12
|
+
are `no_change`), `attempt_start.prompt_cut` (the renderer cut the prompt), `council` (CNL-B10, CNL-B12: `rounds`
|
|
13
|
+
with `choices` and `changed` per member, and the `outcome`) and `contest` (CTS-B7: `slots` with their keys, and the
|
|
14
|
+
`winner`). A fact the log does not carry leaves the rule that needs it quiet and its sample empty.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import json
|
|
21
|
+
import re
|
|
22
|
+
import statistics
|
|
23
|
+
from collections.abc import Mapping, Sequence
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from tempergraph.run.log import split_session_key
|
|
29
|
+
|
|
30
|
+
MISSING = re.compile(r"⟨missing:[^⟩]*⟩")
|
|
31
|
+
STEP_KINDS = frozenset({"step", "retry"})
|
|
32
|
+
PASS_TOKENS = frozenset({"PROCEED", "NEXT"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(kw_only=True)
|
|
36
|
+
class Attempt:
|
|
37
|
+
"""One `agent_run` record: a session and how it ended."""
|
|
38
|
+
|
|
39
|
+
run: str
|
|
40
|
+
unit: str
|
|
41
|
+
kind: str
|
|
42
|
+
ok: bool | None
|
|
43
|
+
timed_out: bool
|
|
44
|
+
stalled: bool
|
|
45
|
+
duration_s: float | None
|
|
46
|
+
timeout_s: float | None
|
|
47
|
+
infra_cause: str | None
|
|
48
|
+
tool_wall_share: float
|
|
49
|
+
cost: float | None
|
|
50
|
+
peak_context: int | None
|
|
51
|
+
output_tokens: int | None
|
|
52
|
+
end_shape: str | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(kw_only=True)
|
|
56
|
+
class Visit:
|
|
57
|
+
"""One entry of a unit: the gate's tokens in order."""
|
|
58
|
+
|
|
59
|
+
run: str
|
|
60
|
+
unit: str
|
|
61
|
+
ts: str
|
|
62
|
+
version: str
|
|
63
|
+
tokens: list[str] = field(default_factory=list)
|
|
64
|
+
attempts: int = 0
|
|
65
|
+
fallback: bool = False
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def first_pass(self) -> bool:
|
|
69
|
+
return bool(self.tokens) and self.tokens[0] in PASS_TOKENS
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(kw_only=True)
|
|
73
|
+
class Retry:
|
|
74
|
+
run: str
|
|
75
|
+
unit: str
|
|
76
|
+
blockers: list[str]
|
|
77
|
+
no_change: list[str]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(kw_only=True)
|
|
81
|
+
class Check:
|
|
82
|
+
run: str
|
|
83
|
+
unit: str
|
|
84
|
+
visit: int
|
|
85
|
+
result: str
|
|
86
|
+
evidence: str
|
|
87
|
+
ran_nothing: bool
|
|
88
|
+
attempts_after: bool = False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(kw_only=True)
|
|
92
|
+
class Pause:
|
|
93
|
+
run: str
|
|
94
|
+
unit: str
|
|
95
|
+
kind: str
|
|
96
|
+
decision: str | None
|
|
97
|
+
feedback: bool
|
|
98
|
+
changed: bool
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(kw_only=True)
|
|
102
|
+
class Call:
|
|
103
|
+
name: str
|
|
104
|
+
capability: str | None
|
|
105
|
+
input_summary: str | None
|
|
106
|
+
ok: bool | None
|
|
107
|
+
subagent: bool = False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(kw_only=True)
|
|
111
|
+
class Session:
|
|
112
|
+
"""One session as the activity journal and the run log show it (TSA-B6)."""
|
|
113
|
+
|
|
114
|
+
run: str
|
|
115
|
+
key: str
|
|
116
|
+
unit: str
|
|
117
|
+
kind: str
|
|
118
|
+
started_tools: tuple[str, ...] | None # None: no journal
|
|
119
|
+
calls: list[Call]
|
|
120
|
+
denied: list[tuple[str, str | None]] # (name, scrubbed input summary)
|
|
121
|
+
journal: bool
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def judge(self) -> bool:
|
|
125
|
+
return self.kind.startswith("judge")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(kw_only=True)
|
|
129
|
+
class Grant:
|
|
130
|
+
run: str
|
|
131
|
+
unit: str
|
|
132
|
+
capability: str | None
|
|
133
|
+
prefix: str | None
|
|
134
|
+
action: str
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(kw_only=True)
|
|
138
|
+
class HistoryFacts:
|
|
139
|
+
workflow: str = ""
|
|
140
|
+
version: str = "all"
|
|
141
|
+
window_days: int = 30
|
|
142
|
+
root: Path | None = None # the state root the facts were read from (the owners of rendered rules read it too)
|
|
143
|
+
today: dt.date | None = None
|
|
144
|
+
runs: int = 0
|
|
145
|
+
unreadable: int = 0
|
|
146
|
+
unclassified: int = 0 # runs with sessions and no activity journal
|
|
147
|
+
bad_records: int = 0
|
|
148
|
+
run_ids: list[str] = field(default_factory=list)
|
|
149
|
+
attempts: list[Attempt] = field(default_factory=list)
|
|
150
|
+
visits: list[Visit] = field(default_factory=list)
|
|
151
|
+
retries: list[Retry] = field(default_factory=list)
|
|
152
|
+
checks: list[Check] = field(default_factory=list)
|
|
153
|
+
missing: list[tuple[str, str, str]] = field(default_factory=list) # (run, unit, marker)
|
|
154
|
+
cut_prompts: list[tuple[str, str]] = field(default_factory=list) # (run, unit)
|
|
155
|
+
pauses: list[Pause] = field(default_factory=list)
|
|
156
|
+
supervision: list[dict[str, Any]] = field(default_factory=list)
|
|
157
|
+
outcomes: list[tuple[str, str]] = field(default_factory=list) # (run, verdict)
|
|
158
|
+
rerun_sources: set[str] = field(default_factory=set)
|
|
159
|
+
councils: list[dict[str, Any]] = field(default_factory=list)
|
|
160
|
+
contests: list[dict[str, Any]] = field(default_factory=list)
|
|
161
|
+
sessions: list[Session] = field(default_factory=list)
|
|
162
|
+
grants: list[Grant] = field(default_factory=list)
|
|
163
|
+
findings: list[dict[str, Any]] = field(default_factory=list) # the runs' findings documents, with `run`
|
|
164
|
+
digests: list[tuple[str, str, str, str, str]] = field(default_factory=list) # (ts, run, unit, role, digest)
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def journal_runs(self) -> int:
|
|
168
|
+
return self.runs - self.unclassified
|
|
169
|
+
|
|
170
|
+
def refusal_counts(self) -> int | str:
|
|
171
|
+
"""Refusals recorded, or `unclassified` when no run in the window has an activity journal (AUD-B10)."""
|
|
172
|
+
if self.runs and self.journal_runs == 0:
|
|
173
|
+
return "unclassified"
|
|
174
|
+
return sum(len(s.denied) for s in self.sessions if s.journal)
|
|
175
|
+
|
|
176
|
+
def units(self) -> list[str]:
|
|
177
|
+
return list(dict.fromkeys([a.unit for a in self.attempts] + [v.unit for v in self.visits]))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _read(path: Path) -> tuple[list[dict[str, Any]], int] | None:
|
|
181
|
+
try:
|
|
182
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
183
|
+
except OSError:
|
|
184
|
+
return None
|
|
185
|
+
out: list[dict[str, Any]] = []
|
|
186
|
+
bad = 0
|
|
187
|
+
for line in text.splitlines():
|
|
188
|
+
if not line.strip():
|
|
189
|
+
continue
|
|
190
|
+
try:
|
|
191
|
+
rec = json.loads(line)
|
|
192
|
+
except ValueError:
|
|
193
|
+
bad += 1
|
|
194
|
+
continue
|
|
195
|
+
if isinstance(rec, dict):
|
|
196
|
+
out.append(rec)
|
|
197
|
+
else:
|
|
198
|
+
bad += 1
|
|
199
|
+
return out, bad
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _ts(value: Any) -> dt.datetime | None:
|
|
203
|
+
try:
|
|
204
|
+
got = dt.datetime.fromisoformat(str(value))
|
|
205
|
+
except ValueError:
|
|
206
|
+
return None
|
|
207
|
+
return got if got.tzinfo else got.replace(tzinfo=dt.UTC)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _cost(usage: Mapping[str, Any] | None) -> float | None:
|
|
211
|
+
u = usage or {}
|
|
212
|
+
rep, est = u.get("reported_cost_usd"), u.get("estimated_cost_usd")
|
|
213
|
+
return float(rep) if rep is not None else float(est) if est is not None else None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _num(value: Any) -> float | None:
|
|
217
|
+
return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def read_history(root: Path, workflow: str, version: str, window_days: int, today: dt.date, *,
|
|
221
|
+
current: str | None = None) -> HistoryFacts:
|
|
222
|
+
"""AUD-B3, AUD-B11, AUD-B12, AUD-B15: the facts of the workflow's runs in the window and version."""
|
|
223
|
+
facts = HistoryFacts(workflow=workflow, version=version, window_days=window_days, root=root, today=today)
|
|
224
|
+
base = root / "runs" / workflow
|
|
225
|
+
since = dt.datetime.combine(today - dt.timedelta(days=window_days), dt.time.min, tzinfo=dt.UTC)
|
|
226
|
+
want = current if version == "current" else None if version == "all" else version
|
|
227
|
+
try:
|
|
228
|
+
tasks = sorted(p for p in base.iterdir() if p.is_dir()) if base.is_dir() else []
|
|
229
|
+
except OSError:
|
|
230
|
+
tasks = []
|
|
231
|
+
for task in tasks:
|
|
232
|
+
log = task / "run.jsonl"
|
|
233
|
+
if not log.exists():
|
|
234
|
+
if any(task.iterdir()):
|
|
235
|
+
facts.unreadable += 1
|
|
236
|
+
continue
|
|
237
|
+
got = _read(log)
|
|
238
|
+
start = next((r for r in got[0] if r.get("kind") == "run_started"), None) if got else None
|
|
239
|
+
started = _ts(start.get("ts")) if start else None
|
|
240
|
+
if got is None or start is None or started is None:
|
|
241
|
+
facts.unreadable += 1
|
|
242
|
+
continue
|
|
243
|
+
if started < since or (want is not None and start.get("workflow_version") != want):
|
|
244
|
+
continue
|
|
245
|
+
facts.bad_records += got[1]
|
|
246
|
+
facts.runs += 1
|
|
247
|
+
facts.run_ids.append(task.name)
|
|
248
|
+
_ingest(facts, root, workflow, task, got[0], start)
|
|
249
|
+
return facts
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _ingest(facts: HistoryFacts, root: Path, workflow: str, task: Path, recs: Sequence[Mapping[str, Any]],
|
|
253
|
+
start: Mapping[str, Any]) -> None:
|
|
254
|
+
run = task.name
|
|
255
|
+
ts = str(start.get("ts"))
|
|
256
|
+
ver = str(start.get("workflow_version") or "")
|
|
257
|
+
source = (start.get("rerun_of") or {}) if isinstance(start.get("rerun_of"), Mapping) else {}
|
|
258
|
+
src = source.get("task_id") or source.get("thread_id") or source.get("thread")
|
|
259
|
+
if src:
|
|
260
|
+
facts.rerun_sources.add(str(src).rsplit("/", 1)[-1])
|
|
261
|
+
visit: Visit | None = None
|
|
262
|
+
judged: dict[str, Retry] = {}
|
|
263
|
+
pending: dict[str, Pause] = {}
|
|
264
|
+
fails: dict[str, list[str]] = {}
|
|
265
|
+
timeouts: dict[str, float | None] = {}
|
|
266
|
+
sessions = 0
|
|
267
|
+
for r in recs:
|
|
268
|
+
kind = r.get("kind")
|
|
269
|
+
unit = str(r.get("unit") or split_session_key(str(r.get("session_key") or ""))[0] or "")
|
|
270
|
+
line = json.dumps(r, ensure_ascii=False)
|
|
271
|
+
if kind in ("attempt_start", "agent_run") and MISSING.search(line):
|
|
272
|
+
facts.missing.append((run, unit, MISSING.search(line).group(0))) # type: ignore[union-attr]
|
|
273
|
+
if kind == "unit_entered":
|
|
274
|
+
visit = Visit(run=run, unit=unit, ts=str(r.get("ts") or ts), version=ver)
|
|
275
|
+
facts.visits.append(visit)
|
|
276
|
+
fails[unit] = []
|
|
277
|
+
elif kind == "attempt_start":
|
|
278
|
+
timeouts[str(r.get("session_key"))] = _num(r.get("timeout_s"))
|
|
279
|
+
if r.get("prompt_cut"):
|
|
280
|
+
facts.cut_prompts.append((run, unit))
|
|
281
|
+
if str(r.get("session_kind") or "step") not in STEP_KINDS:
|
|
282
|
+
continue # a judge session is not a visit's attempt
|
|
283
|
+
if r.get("prompt_digest"):
|
|
284
|
+
facts.digests.append((str(r.get("ts") or ts), run, unit, "step", str(r["prompt_digest"])))
|
|
285
|
+
if visit is not None and visit.unit == unit:
|
|
286
|
+
visit.attempts += 1
|
|
287
|
+
elif kind == "agent_run":
|
|
288
|
+
sessions += 1
|
|
289
|
+
key = str(r.get("session_key") or "")
|
|
290
|
+
sk = str(r.get("session_kind") or "step")
|
|
291
|
+
if sk in STEP_KINDS:
|
|
292
|
+
facts.attempts.append(Attempt(
|
|
293
|
+
run=run, unit=unit, kind=sk, ok=r.get("ok"), timed_out=bool(r.get("timed_out")),
|
|
294
|
+
stalled=bool(r.get("stalled")), duration_s=_num(r.get("duration_s")),
|
|
295
|
+
timeout_s=timeouts.get(key), infra_cause=r.get("infra_cause"),
|
|
296
|
+
tool_wall_share=float(r.get("tool_wall_share") or 0.0), cost=_cost(r.get("usage")),
|
|
297
|
+
peak_context=int((r.get("usage") or {}).get("peak_context_tokens") or 0) or None,
|
|
298
|
+
output_tokens=int((r.get("usage") or {}).get("output_tokens") or 0) or None,
|
|
299
|
+
end_shape=r.get("end_shape") or _digest_shape(task, key)))
|
|
300
|
+
else:
|
|
301
|
+
facts.attempts.append(Attempt(
|
|
302
|
+
run=run, unit=unit, kind=sk, ok=r.get("ok"), timed_out=bool(r.get("timed_out")),
|
|
303
|
+
stalled=bool(r.get("stalled")), duration_s=_num(r.get("duration_s")), timeout_s=None,
|
|
304
|
+
infra_cause=r.get("infra_cause"), tool_wall_share=0.0, cost=_cost(r.get("usage")),
|
|
305
|
+
peak_context=None, output_tokens=None))
|
|
306
|
+
elif kind == "check":
|
|
307
|
+
res = str(r.get("result") or "")
|
|
308
|
+
ev = str(r.get("evidence") or "")
|
|
309
|
+
ran_nothing = ((r.get("commands_run") == 0 and int(r.get("commands_declared") or 1) > 0)
|
|
310
|
+
or "not run" in ev.lower())
|
|
311
|
+
facts.checks.append(Check(run=run, unit=unit, visit=len(facts.visits), result=res, evidence=ev,
|
|
312
|
+
ran_nothing=ran_nothing))
|
|
313
|
+
if res == "FAIL":
|
|
314
|
+
fails.setdefault(unit, []).append(ev)
|
|
315
|
+
elif kind == "judgement":
|
|
316
|
+
blockers = [str(b) for b in r.get("blockers") or []]
|
|
317
|
+
judged[unit] = Retry(run=run, unit=unit, blockers=blockers,
|
|
318
|
+
no_change=[str(b) for b in r.get("no_change") or []])
|
|
319
|
+
if r.get("brief_digest"):
|
|
320
|
+
facts.digests.append((str(r.get("ts") or ts), run, unit, "judge", str(r["brief_digest"])))
|
|
321
|
+
elif kind == "gate":
|
|
322
|
+
token = str(r.get("token") or r.get("verdict") or "")
|
|
323
|
+
if visit is not None and visit.unit == unit:
|
|
324
|
+
visit.tokens.append(token)
|
|
325
|
+
visit.fallback = visit.fallback or token == "FALLBACK"
|
|
326
|
+
if str(r.get("verdict")) == "RETRY" and unit in judged:
|
|
327
|
+
facts.retries.append(judged[unit])
|
|
328
|
+
elif kind == "route" and r.get("chosen_by") == "fallback" and visit is not None:
|
|
329
|
+
visit.fallback = True
|
|
330
|
+
elif kind == "pause":
|
|
331
|
+
pending[unit] = Pause(run=run, unit=unit, kind=str(r.get("pause_kind") or ""), decision=None,
|
|
332
|
+
feedback=False, changed=False)
|
|
333
|
+
facts.pauses.append(pending[unit])
|
|
334
|
+
elif kind == "human" and unit in pending:
|
|
335
|
+
p = pending.pop(unit)
|
|
336
|
+
p.decision, p.feedback, p.changed = (str(r.get("decision") or ""), bool(r.get("feedback")),
|
|
337
|
+
bool(r.get("workspace_changed")))
|
|
338
|
+
elif kind == "supervision":
|
|
339
|
+
facts.supervision.append(dict(r))
|
|
340
|
+
elif kind == "outcome":
|
|
341
|
+
facts.outcomes = [o for o in facts.outcomes if o[0] != run] + [(run, str(r.get("verdict") or ""))]
|
|
342
|
+
elif kind == "grant":
|
|
343
|
+
facts.grants.append(Grant(run=run, unit=unit, capability=r.get("capability"), prefix=r.get("prefix"),
|
|
344
|
+
action=str(r.get("action") or "")))
|
|
345
|
+
elif kind == "council":
|
|
346
|
+
facts.councils.append({"run": run, **dict(r)})
|
|
347
|
+
elif kind == "contest":
|
|
348
|
+
facts.contests.append({"run": run, **dict(r)})
|
|
349
|
+
# repeated check evidence needs the visit's attempts after the repeat
|
|
350
|
+
for c in facts.checks:
|
|
351
|
+
if c.run == run and c.result == "FAIL":
|
|
352
|
+
same = [x for x in facts.checks if x.run == run and x.unit == c.unit and x.visit == c.visit
|
|
353
|
+
and x.result == "FAIL" and x.evidence == c.evidence]
|
|
354
|
+
visit_of = [v for v in facts.visits if v.run == run and v.unit == c.unit]
|
|
355
|
+
c.attempts_after = len(same) >= 2 and bool(visit_of) and visit_of[-1].attempts > len(same)
|
|
356
|
+
_sessions(facts, task, run, recs)
|
|
357
|
+
if sessions and not any(s.journal for s in facts.sessions if s.run == run):
|
|
358
|
+
facts.unclassified += 1
|
|
359
|
+
from tempergraph.improve import record
|
|
360
|
+
|
|
361
|
+
for f in record.read_findings(root, workflow, run):
|
|
362
|
+
facts.findings.append({"run": run, **f})
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _digest_shape(task: Path, key: str) -> str | None:
|
|
366
|
+
"""The timeout shape the session digest recorded (`hung`, `slow_host`, `model_silent`), read-only."""
|
|
367
|
+
try:
|
|
368
|
+
doc = json.loads((task / "sessions" / key / "digest.json").read_text(encoding="utf-8"))
|
|
369
|
+
except (OSError, ValueError):
|
|
370
|
+
return None
|
|
371
|
+
end = doc.get("end") if isinstance(doc, dict) else None
|
|
372
|
+
shape = end.get("timeout_shape") if isinstance(end, dict) else None
|
|
373
|
+
return str(shape) if shape else None
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _sessions(facts: HistoryFacts, task: Path, run: str, recs: Sequence[Mapping[str, Any]]) -> None:
|
|
377
|
+
"""TSA-B6: per session the start tool list, the calls with their scrubbed input summaries, the denied names."""
|
|
378
|
+
for r in recs:
|
|
379
|
+
if r.get("kind") != "agent_run" or not r.get("session_key"):
|
|
380
|
+
continue
|
|
381
|
+
key = str(r["session_key"])
|
|
382
|
+
unit = str(r.get("unit") or split_session_key(key)[0] or "")
|
|
383
|
+
journal = task / "sessions" / key / "activity.jsonl"
|
|
384
|
+
got = _read(journal) if journal.is_file() else None
|
|
385
|
+
calls: list[Call] = []
|
|
386
|
+
denied: list[tuple[str, str | None]] = []
|
|
387
|
+
started: tuple[str, ...] | None = None
|
|
388
|
+
if got is not None:
|
|
389
|
+
done = {str(x.get("call_id")): x for x in got[0] if x.get("ev") == "tool_finished"}
|
|
390
|
+
for row in got[0]:
|
|
391
|
+
ev = row.get("ev")
|
|
392
|
+
if ev == "session_started":
|
|
393
|
+
started = tuple(str(t) for t in row.get("tools") or ())
|
|
394
|
+
elif ev == "tool_started":
|
|
395
|
+
fin = done.get(str(row.get("call_id")))
|
|
396
|
+
calls.append(Call(name=str(row.get("name") or ""), capability=row.get("capability"),
|
|
397
|
+
input_summary=row.get("input_summary"),
|
|
398
|
+
ok=None if fin is None else fin.get("ok"), subagent=bool(row.get("subagent"))))
|
|
399
|
+
elif ev == "denied":
|
|
400
|
+
summary = row.get("input_summary")
|
|
401
|
+
denied.append((str(row.get("name") or ""), str(summary) if summary else None))
|
|
402
|
+
else:
|
|
403
|
+
calls = [Call(name=str(n), capability=None, input_summary=None, ok=None) for n in r.get("tools") or ()]
|
|
404
|
+
facts.sessions.append(Session(run=run, key=key, unit=unit, kind=str(r.get("session_kind") or "step"),
|
|
405
|
+
started_tools=started, calls=calls, denied=denied, journal=got is not None))
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def p90(values: Sequence[float]) -> float:
|
|
409
|
+
"""The 90th percentile with linear interpolation between ranks (inclusive method)."""
|
|
410
|
+
if not values:
|
|
411
|
+
return 0.0
|
|
412
|
+
if len(values) == 1:
|
|
413
|
+
return float(values[0])
|
|
414
|
+
return float(statistics.quantiles(sorted(values), n=10, method="inclusive")[-1])
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""The history rules of C1, C2 and C3 (ARC-B9, ARC-B10, ARC-B11) and the hot spots per unit (AUD-B3).
|
|
2
|
+
|
|
3
|
+
Every function reads `HistoryFacts` only: no file, no executor, no model. A rule returns findings with the catalog's
|
|
4
|
+
severity, confidence, cause and remedy; the evidence names the counts, `n` (the runs read) and the window. A rule is
|
|
5
|
+
called only with at least its `min_n` runs (`audit.__init__`); the smaller sample counts a rule states inside itself
|
|
6
|
+
(5 RETRYs, 5 visits, 20 attempts) keep it quiet when the runs hold too few of them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections import Counter
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from tempergraph.audit.catalog import PARAMS, rule
|
|
16
|
+
from tempergraph.audit.history import STEP_KINDS, Attempt, HistoryFacts, p90
|
|
17
|
+
from tempergraph.audit.report import AuditFinding, order
|
|
18
|
+
from tempergraph.contracts import WorkflowSpec
|
|
19
|
+
|
|
20
|
+
P = {k: v.default for k, v in PARAMS.items()}
|
|
21
|
+
Rule = Callable[[WorkflowSpec, HistoryFacts], list[AuditFinding]]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RuleSkipped(Exception): # noqa: N818 - a signal, not an error: the rule's input is missing (ARC-B7)
|
|
25
|
+
"""A rule that cannot judge on the facts it was given: it is listed as skipped with this reason, never passed."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, reason: str) -> None:
|
|
28
|
+
super().__init__(reason)
|
|
29
|
+
self.reason = reason
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def finding(rule_id: str, facts: HistoryFacts, unit: str | None, statement: str, *, item: str | None = None,
|
|
33
|
+
evidence: dict[str, Any] | None = None, session: str | None = None) -> AuditFinding:
|
|
34
|
+
"""A history finding: the catalog's record, the evidence counts, `n` and the window (AUD-B3)."""
|
|
35
|
+
r = rule(rule_id)
|
|
36
|
+
return AuditFinding(rule=r.id, layer=r.layer, severity=r.severity, confidence=r.confidence,
|
|
37
|
+
cause=r.cause, unit=unit, item=item, session=session, statement=statement,
|
|
38
|
+
evidence={**(evidence or {}), "n": facts.runs, "window_days": facts.window_days},
|
|
39
|
+
remedy=r.remedy)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def step_attempts(facts: HistoryFacts, unit: str) -> list[Attempt]:
|
|
43
|
+
return [a for a in facts.attempts if a.unit == unit and a.kind in STEP_KINDS]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def total_spend(facts: HistoryFacts) -> float:
|
|
47
|
+
return sum(a.cost or 0.0 for a in facts.attempts)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def repeat_share(facts: HistoryFacts, unit: str) -> tuple[float, str]:
|
|
51
|
+
"""The gate's repeats (retry sessions) as a share of the workflow's spend, else of its sessions."""
|
|
52
|
+
spend = total_spend(facts)
|
|
53
|
+
if spend > 0:
|
|
54
|
+
return sum(a.cost or 0.0 for a in facts.attempts if a.unit == unit and a.kind == "retry") / spend, "cost"
|
|
55
|
+
total = len(facts.attempts)
|
|
56
|
+
return (sum(1 for a in facts.attempts if a.unit == unit and a.kind == "retry") / total if total else 0.0,
|
|
57
|
+
"attempts")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _visits(facts: HistoryFacts, unit: str) -> list[Any]:
|
|
61
|
+
return [v for v in facts.visits if v.unit == unit and v.tokens]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# -- C1 ---------------------------------------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def loop_driver_criterion(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
68
|
+
out = []
|
|
69
|
+
for unit in dict.fromkeys(r.unit for r in facts.retries):
|
|
70
|
+
retries = [r for r in facts.retries if r.unit == unit]
|
|
71
|
+
if len(retries) < P["loop_min_retries"]:
|
|
72
|
+
continue
|
|
73
|
+
leads = Counter(r.blockers[0] for r in retries if r.blockers)
|
|
74
|
+
if not leads:
|
|
75
|
+
continue
|
|
76
|
+
crit, led = leads.most_common(1)[0]
|
|
77
|
+
share, basis = repeat_share(facts, unit)
|
|
78
|
+
if led / len(retries) >= P["loop_lead_share"] and share >= P["loop_repeat_share"]:
|
|
79
|
+
out.append(finding("loop-driver-criterion", facts, unit,
|
|
80
|
+
f"criterion {crit!r} leads {led} of {len(retries)} RETRY verdicts of {unit} and its "
|
|
81
|
+
f"repeats are {share:.0%} of spend", item=crit,
|
|
82
|
+
evidence={"criterion": crit, "retries": len(retries), "led": led,
|
|
83
|
+
"repeat_share": round(share, 3), "basis": basis}))
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def low_first_pass(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
88
|
+
out = []
|
|
89
|
+
for unit in dict.fromkeys(v.unit for v in facts.visits):
|
|
90
|
+
visits = _visits(facts, unit)
|
|
91
|
+
passed = sum(1 for v in visits if v.first_pass)
|
|
92
|
+
if len(visits) >= P["min_visits"] and passed / len(visits) < P["first_pass_floor"]:
|
|
93
|
+
out.append(finding("low-first-pass", facts, unit, f"{unit} passes first time in {passed} of "
|
|
94
|
+
f"{len(visits)} visits", evidence={"visits": len(visits), "first_pass": passed,
|
|
95
|
+
"yield": round(passed / len(visits), 3)}))
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def no_change_retried(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
100
|
+
out = []
|
|
101
|
+
for unit in dict.fromkeys(r.unit for r in facts.retries):
|
|
102
|
+
hits = [r for r in facts.retries if r.unit == unit and r.blockers and set(r.blockers) <= set(r.no_change)]
|
|
103
|
+
if hits:
|
|
104
|
+
out.append(finding("no-change-retried", facts, unit, f"{len(hits)} RETRYs of {unit} had only "
|
|
105
|
+
"`no_change` blockers, which a retry cannot fix",
|
|
106
|
+
evidence={"retries": len(hits), "criteria": sorted({b for r in hits for b in r.blockers})}))
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def repeated_check_evidence(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
111
|
+
out = []
|
|
112
|
+
for unit in dict.fromkeys(c.unit for c in facts.checks):
|
|
113
|
+
hits = {(c.run, c.visit) for c in facts.checks if c.unit == unit and c.attempts_after}
|
|
114
|
+
if hits:
|
|
115
|
+
out.append(finding("repeated-check-evidence", facts, unit, f"{len(hits)} visits of {unit} failed the "
|
|
116
|
+
"check twice with the same evidence and ran a new attempt",
|
|
117
|
+
evidence={"visits": len(hits)}))
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def missing_field_rendered(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
122
|
+
out = []
|
|
123
|
+
for unit in dict.fromkeys(m[1] for m in facts.missing):
|
|
124
|
+
hits = [m for m in facts.missing if m[1] == unit]
|
|
125
|
+
for marker in dict.fromkeys(m[2] for m in hits):
|
|
126
|
+
out.append(finding("missing-field-rendered", facts, unit, f"a step record of {unit} shows {marker}",
|
|
127
|
+
item=marker, evidence={"records": sum(1 for m in hits if m[2] == marker),
|
|
128
|
+
"runs": len({m[0] for m in hits if m[2] == marker})}))
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def fallback_rate(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
133
|
+
out = []
|
|
134
|
+
for unit in dict.fromkeys(v.unit for v in facts.visits):
|
|
135
|
+
visits = _visits(facts, unit)
|
|
136
|
+
took = sum(1 for v in visits if v.fallback)
|
|
137
|
+
if len(visits) >= P["min_visits"] and took / len(visits) >= P["fallback_share"]:
|
|
138
|
+
out.append(finding("fallback-rate", facts, unit, f"{unit} took its fallback in {took} of {len(visits)} "
|
|
139
|
+
"visits", evidence={"visits": len(visits), "fallbacks": took,
|
|
140
|
+
"share": round(took / len(visits), 3)}))
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# -- C2 ---------------------------------------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def check_ran_nothing(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
148
|
+
out = []
|
|
149
|
+
for unit in dict.fromkeys(c.unit for c in facts.checks):
|
|
150
|
+
hits = [c for c in facts.checks if c.unit == unit and c.ran_nothing]
|
|
151
|
+
if hits:
|
|
152
|
+
out.append(finding("check-ran-nothing", facts, unit, f"the check of {unit} ran none of its declared "
|
|
153
|
+
f"commands in {len(hits)} records", evidence={"checks": len(hits),
|
|
154
|
+
"runs": len({c.run for c in hits})}))
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def infra_heavy(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
159
|
+
out = []
|
|
160
|
+
for unit in dict.fromkeys(a.unit for a in facts.attempts):
|
|
161
|
+
attempts = step_attempts(facts, unit)
|
|
162
|
+
infra = [a for a in attempts if a.infra_cause]
|
|
163
|
+
if len(attempts) >= P["infra_min_attempts"] and len(infra) / len(attempts) >= P["infra_share"]:
|
|
164
|
+
lead = Counter(str(a.infra_cause) for a in infra).most_common(1)[0][0]
|
|
165
|
+
out.append(finding("infra-heavy", facts, unit, f"{len(infra)} of {len(attempts)} attempts of {unit} "
|
|
166
|
+
f"ended on an infrastructure cause, most often {lead}",
|
|
167
|
+
evidence={"attempts": len(attempts), "infra": len(infra), "leading_cause": lead,
|
|
168
|
+
"share": round(len(infra) / len(attempts), 3)}))
|
|
169
|
+
return out
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# -- C3 ---------------------------------------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _passing(facts: HistoryFacts, unit: str) -> list[Attempt]:
|
|
176
|
+
return [a for a in step_attempts(facts, unit) if a.ok and not a.timed_out and not a.stalled
|
|
177
|
+
and a.duration_s is not None]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _limit(facts: HistoryFacts, unit: str) -> float | None:
|
|
181
|
+
limits = [a.timeout_s for a in step_attempts(facts, unit) if a.timeout_s]
|
|
182
|
+
return max(limits) if limits else None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def timeout_below_pass_p90(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
186
|
+
out = []
|
|
187
|
+
for unit in dict.fromkeys(a.unit for a in facts.attempts):
|
|
188
|
+
passing, limit = _passing(facts, unit), _limit(facts, unit)
|
|
189
|
+
if len(passing) < P["min_passing_attempts"] or limit is None:
|
|
190
|
+
continue
|
|
191
|
+
q = p90([float(a.duration_s or 0) for a in passing])
|
|
192
|
+
if limit < P["timeout_fit_ratio"] * q:
|
|
193
|
+
rec = round(P["timeout_recommend_ratio"] * q)
|
|
194
|
+
out.append(finding("timeout-below-pass-p90", facts, unit, f"the {int(limit)} s limit of {unit} is below "
|
|
195
|
+
f"{P['timeout_fit_ratio']} x the p90 of passing attempts ({round(q)} s); about {rec} s "
|
|
196
|
+
"would fit", evidence={"limit_s": int(limit), "p90_s": round(q),
|
|
197
|
+
"recommended_s": rec, "passing": len(passing)}))
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def attempts_at_limit(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
202
|
+
out = []
|
|
203
|
+
for unit in dict.fromkeys(a.unit for a in facts.attempts):
|
|
204
|
+
attempts = step_attempts(facts, unit)
|
|
205
|
+
bad = [a for a in attempts if a.timed_out or a.stalled]
|
|
206
|
+
if len(attempts) >= P["min_visits"] and bad and len(bad) / len(attempts) >= P["timeout_share"]:
|
|
207
|
+
shapes = Counter(a.end_shape or ("slow_host" if a.tool_wall_share >= P["slow_tool_share"]
|
|
208
|
+
else "model_silent") for a in bad)
|
|
209
|
+
out.append(finding("attempts-at-limit", facts, unit, f"{len(bad)} of {len(attempts)} attempts of {unit} "
|
|
210
|
+
"timed out or stalled", evidence={"attempts": len(attempts), "at_limit": len(bad),
|
|
211
|
+
"shapes": dict(shapes)}))
|
|
212
|
+
return out
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def limit_far_above_p90(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
216
|
+
out = []
|
|
217
|
+
for unit in dict.fromkeys(a.unit for a in facts.attempts):
|
|
218
|
+
passing, limit = _passing(facts, unit), _limit(facts, unit)
|
|
219
|
+
if len(passing) < P["min_passing_attempts"] or limit is None:
|
|
220
|
+
continue
|
|
221
|
+
q = p90([float(a.duration_s or 0) for a in passing])
|
|
222
|
+
if q > 0 and limit > P["timeout_loose_ratio"] * q:
|
|
223
|
+
out.append(finding("limit-far-above-p90", facts, unit, f"the {int(limit)} s limit of {unit} is over "
|
|
224
|
+
f"{P['timeout_loose_ratio']:g} x the p90 of passing attempts ({round(q)} s)",
|
|
225
|
+
evidence={"limit_s": int(limit), "p90_s": round(q), "passing": len(passing)}))
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def request_timed_out(spec: WorkflowSpec, facts: HistoryFacts) -> list[AuditFinding]:
|
|
230
|
+
out = []
|
|
231
|
+
for unit in dict.fromkeys(a.unit for a in facts.attempts):
|
|
232
|
+
attempts = step_attempts(facts, unit)
|
|
233
|
+
hits = [a for a in attempts if a.infra_cause == "request_timed_out"]
|
|
234
|
+
if hits:
|
|
235
|
+
largest = max((a.output_tokens or 0 for a in attempts), default=0)
|
|
236
|
+
out.append(finding("request-timed-out", facts, unit, f"{len(hits)} requests of {unit} timed out; its "
|
|
237
|
+
f"largest single response was {largest} tokens",
|
|
238
|
+
evidence={"requests": len(hits), "largest_response_tokens": largest}))
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
HISTORY_C1_C3: dict[str, Rule] = {
|
|
243
|
+
"loop-driver-criterion": loop_driver_criterion, "low-first-pass": low_first_pass,
|
|
244
|
+
"no-change-retried": no_change_retried, "repeated-check-evidence": repeated_check_evidence,
|
|
245
|
+
"missing-field-rendered": missing_field_rendered, "fallback-rate": fallback_rate,
|
|
246
|
+
"check-ran-nothing": check_ran_nothing, "infra-heavy": infra_heavy,
|
|
247
|
+
"timeout-below-pass-p90": timeout_below_pass_p90, "attempts-at-limit": attempts_at_limit,
|
|
248
|
+
"limit-far-above-p90": limit_far_above_p90, "request-timed-out": request_timed_out,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def hot_spots(facts: HistoryFacts, findings: list[AuditFinding]) -> list[dict[str, Any]]:
|
|
253
|
+
"""AUD-B3: per unit the repeat share of spend, first-pass yield, timeouts, refusals and pauses per run."""
|
|
254
|
+
out = []
|
|
255
|
+
for unit in facts.units():
|
|
256
|
+
visits = _visits(facts, unit)
|
|
257
|
+
mine = order([f for f in findings if f.unit == unit], ())
|
|
258
|
+
refusals: int | str = ("unclassified" if facts.runs and facts.journal_runs == 0 else
|
|
259
|
+
sum(len(s.denied) for s in facts.sessions if s.unit == unit and s.journal))
|
|
260
|
+
out.append({"unit": unit, "findings": len(mine), "leading_rule": mine[0].rule if mine else None,
|
|
261
|
+
"repeat_share": round(repeat_share(facts, unit)[0], 3),
|
|
262
|
+
"first_pass_yield": round(sum(1 for v in visits if v.first_pass) / len(visits), 3) if visits
|
|
263
|
+
else None,
|
|
264
|
+
"timeouts": sum(1 for a in step_attempts(facts, unit) if a.timed_out or a.stalled),
|
|
265
|
+
"refusals": refusals,
|
|
266
|
+
"pauses_per_run": round(sum(1 for p in facts.pauses if p.unit == unit) / facts.runs, 3)
|
|
267
|
+
if facts.runs else None})
|
|
268
|
+
return out
|