Viewing files at commit f0c34b306c79Commit detailsView latest

Browse files
scripts/oakbench/campaign_report.py 352 lines · 22.0 KB · python
1
"""Diagnostic campaign accounting from a frozen schedule and durable journal.
2
3
No publication claim is certified here. Block bootstrap describes recorded
4
paired trials; repeated fixed fixtures are not independent task populations.
5
"""
6
from __future__ import annotations
7
8
import itertools
9
import math
10
import statistics
11
from statistics import NormalDist
12
13
from oakbench.stats import bootstrap_ci, validate_interval_settings
14
from oakbench.populations import population_conflicts, comparison_identity, comparison_conflicts
15
16
CONDITION_FIELDS = ("workflow", "instruction_level", "agent", "model")
17
OUTCOMES = ("success", "failure", "timeout", "infrastructure_failure", "interrupted", "skipped", "unstarted")
18
COMPLETE = {"success", "failure", "timeout"}
19
METRICS = {
20
    "agent_active_ms": ("wall_clock_metrics", "agent_active_ms"),
21
    "task_total_ms": ("wall_clock_metrics", "total_ms"),
22
    "reported_tokens": ("token_metrics", "total_tokens_reported"),
23
    "cost_weighted_token_proxy": ("token_metrics", "cost_weighted_total"),
24
    "assistant_turns": ("turn_metrics", "assistant_turns_total"),
25
    "tool_calls": ("tool_call_metrics", "tool_calls_total"),
26
}
27
28
29
def _number(value):
30
    return float(value) if type(value) in (int, float) and math.isfinite(value) and value >= 0 else None
31
32
33
def _metric(row, path):
34
    if isinstance(row, dict) and path[0] in {"token_metrics", "turn_metrics", "tool_call_metrics"}:
35
        execution = (row.get("source") or {}).get("agent_execution", {})
36
        incomplete = (isinstance(execution, dict) and
37
                      (execution.get("capture_complete") is False or execution.get("incomplete") is True or
38
                       execution.get("usage_complete") is False or execution.get("transcript_metrics_complete") is False or
39
                       execution.get("counters_coverage") == "observed_lower_bounds" or execution.get("output_limited") is True or
40
                       execution.get("timed_out") is True or execution.get("output_truncated") is True))
41
        if row.get("outcome") == "timeout" or row.get("output_truncated") is True or incomplete:
42
            return None
43
    value = row
44
    for part in path:
45
        value = value.get(part) if isinstance(value, dict) else None
46
    return _number(value)
47
48
49
def _wilson(successes, n, confidence):
50
    if n == 0:
51
        return None
52
    z = NormalDist().inv_cdf((1 + confidence) / 2)
53
    p = successes / n
54
    scale = 1 + z * z / n
55
    centre = (p + z * z / (2 * n)) / scale
56
    radius = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / scale
57
    return [max(0.0, centre - radius), min(1.0, centre + radius)]
58
59
60
def _outcome(event):
61
    row = event.get("row")
62
    explicit = event.get("outcome")
63
    if explicit is not None and isinstance(row, dict) and explicit != row.get("outcome"):
64
        raise ValueError("event outcome contradicts terminal row")
65
    if event.get("measurement_invalidated") is True:
66
        if explicit != "error" or row is not None or not event.get("invalidation_reason"):
67
            raise ValueError("invalidated measurement has contradictory terminal evidence")
68
        return "skipped", None
69
    if isinstance(row, dict) and row.get("returncode") == 77:
70
        if row.get("outcome") != "error" or row.get("success") is not False or not row.get("skip_reason"):
71
            raise ValueError("unmeasured instrument row has contradictory outcome")
72
        return "skipped", row
73
    if isinstance(row, dict) and (row.get("outcome_attribution") in {"harness", "subject"} or row.get("agent_launched") is False):
74
        return "infrastructure_failure", row
75
    if explicit in {"skipped", "skip"}:
76
        return "skipped", row
77
    if explicit == "interrupted":
78
        return "interrupted", row
79
    if explicit in {"error", "infrastructure_failure"}:
80
        if row is not None and (not isinstance(row, dict) or row.get("outcome") != "error" or row.get("success") is not False):
81
            raise ValueError("infrastructure error contradicts terminal task row")
82
        return "infrastructure_failure", row
83
    if not isinstance(row, dict) or type(row.get("success")) is not bool:
84
        raise ValueError("finished trial lacks an explicit row success outcome")
85
    outcome = row.get("outcome")
86
    if outcome not in {"pass", "fail", "timeout", "error"} or (row["success"] != (outcome == "pass")):
87
        raise ValueError("contradictory or unknown row outcome")
88
    return {"pass": "success", "fail": "failure", "timeout": "timeout", "error": "infrastructure_failure"}[outcome], row
89
90
91
def _trials(plan, events):
92
    if plan.get("schema_version") != 1 or not isinstance(plan.get("schedule"), list):
93
        raise ValueError("unsupported campaign plan")
94
    if not isinstance(plan.get("plan_sha256"), str) or not plan["plan_sha256"]:
95
        raise ValueError("campaign plan digest missing")
96
    trials = {}
97
    cells = set()
98
    for item in plan["schedule"]:
99
        if not all(key in item for key in ("trial_id", "block_id", "subject", *CONDITION_FIELDS)):
100
            raise ValueError("schedule trial missing identity")
101
        trial_id = item["trial_id"]
102
        cell = tuple(item[key] for key in (*CONDITION_FIELDS, "block_id", "subject"))
103
        if trial_id in trials or cell in cells:
104
            raise ValueError("duplicate scheduled trial or subject in paired block")
105
        cells.add(cell)
106
        trials[trial_id] = {"trial": item, "started": False, "finished": False,
107
                            "outcome": "unstarted", "row": None}
108
    for event in events:
109
        if event.get("plan_sha256") != plan["plan_sha256"]:
110
            raise ValueError("journal plan digest mismatch")
111
        if event.get("event") == "journal_recovery":
112
            continue
113
        if event.get("trial_id") not in trials:
114
            raise ValueError("journal names unscheduled trial")
115
        state = trials[event["trial_id"]]
116
        if event.get("event") == "started":
117
            if state["started"] or state["finished"]:
118
                raise ValueError("duplicate or out-of-order trial start")
119
            state.update(started=True, outcome="interrupted")
120
            frozen_timeout = plan.get("manifest", {}).get("trial_timeout_seconds")
121
            state["budget_truncated"] = frozen_timeout is not None and event.get("timeout_seconds") != frozen_timeout
122
        elif event.get("event") == "finished":
123
            if state["finished"]:
124
                raise ValueError("duplicate terminal trial event")
125
            outcome, row = _outcome(event)
126
            if not state["started"] and outcome != "skipped":
127
                raise ValueError("finished trial has no start event")
128
            if isinstance(row, dict):
129
                trial = state["trial"]
130
                for row_key, expected in (("task_id", trial["trial_id"]), ("bench_id", plan.get("campaign_id")),
131
                                          ("run", trial.get("repetition"))):
132
                    if row_key in row and row[row_key] != expected:
133
                        raise ValueError("row trial identity contradicts schedule")
134
                for row_key, trial_key in (("subject", "subject"), ("scenario", "workflow")):
135
                    if row_key in row and row[row_key] != trial[trial_key]:
136
                        raise ValueError("row identity contradicts scheduled trial")
137
                agent = row.get("agent", {})
138
                if isinstance(agent, dict):
139
                    for key, planned in (("name", "agent"), ("model", "model"), ("instruction_level", "instruction_level")):
140
                        if agent.get(key) is not None and agent[key] != trial[planned]:
141
                            raise ValueError("row agent condition contradicts scheduled trial")
142
            state.update(finished=True, outcome=outcome, row=row)
143
            if state.get("budget_truncated"):
144
                state["outcome"] = "interrupted"
145
        else:
146
            raise ValueError("unknown journal event")
147
    return list(trials.values())
148
149
150
def _counts(states):
151
    result = {"scheduled": len(states), "started": sum(state["started"] for state in states),
152
              "finished": sum(state["finished"] for state in states)}
153
    result["budget_truncated"] = sum(bool(state.get("budget_truncated")) for state in states)
154
    result.update({name: sum(state["outcome"] == name for state in states) for name in OUTCOMES})
155
    return result
156
157
158
def _resources(states):
159
    attempted = [state for state in states if state["started"]]
160
    successful = [state for state in states if state["outcome"] == "success"]
161
    resources = {}
162
    for name, path in METRICS.items():
163
        values = [value for state in attempted if (value := _metric(state["row"], path)) is not None]
164
        success_values = [value for state in successful if (value := _metric(state["row"], path)) is not None]
165
        observed_sum = sum(values) if values else None
166
        total = observed_sum if attempted and len(values) == len(attempted) else None
167
        resources[name] = {
168
            "attempted_n": len(attempted), "measured_n": len(values), "missing_n": len(attempted) - len(values),
169
            "observed_sum": observed_sum, "complete_total": total,
170
            "observed_cost_per_success": total / len(successful) if total is not None and successful else None,
171
            "success_conditioned": {
172
                "successful_n": len(successful), "measured_n": len(success_values),
173
                "missing_n": len(successful) - len(success_values),
174
                "median": statistics.median(success_values) if success_values else None,
175
                "mean": statistics.fmean(success_values) if success_values else None,
176
            },
177
        }
178
    return resources
179
180
181
def _paired(states, bootstrap_samples, confidence, seed):
182
    by_subject = {}
183
    for state in states:
184
        trial = state["trial"]
185
        by_subject.setdefault(trial["subject"], {})[trial["block_id"]] = state
186
    comparisons = []
187
    for reference, candidate in itertools.combinations(sorted(by_subject), 2):
188
        left, right = by_subject[reference], by_subject[candidate]
189
        blocks = sorted(set(left) | set(right))
190
        complete = [block for block in blocks if block in left and block in right
191
                    and left[block]["outcome"] in COMPLETE and right[block]["outcome"] in COMPLETE]
192
        for block in complete:
193
            if isinstance(left[block]["row"], dict) and isinstance(right[block]["row"], dict):
194
                mismatch = comparison_conflicts(comparison_identity(left[block]["row"]), comparison_identity(right[block]["row"]))
195
                # A measured incorrect worktree need not reach a committed-tree
196
                # proof. Keep that failure in the denominator; successful proof
197
                # classes must still agree before comparison.
198
                if any(row.get("workflow_integrity_passed") is False
199
                       and row.get("agent_launched") is True and row.get("outcome_attribution") == "agent"
200
                       for row in (left[block]["row"], right[block]["row"])):
201
                    mismatch = [field for field in mismatch if field != "workflow_integrity_evidence_class"]
202
                if mismatch:
203
                    raise ValueError("incompatible paired evidence: " + ", ".join(mismatch))
204
        deltas = [int(right[block]["outcome"] == "success") - int(left[block]["outcome"] == "success")
205
                  for block in complete]
206
        interval = None
207
        if len(deltas) >= 2:
208
            interval = list(bootstrap_ci([100 * delta for delta in deltas], statistics.fmean,
209
                                         samples=bootstrap_samples, confidence=confidence, seed=seed))
210
        comparisons.append({
211
            "reference": reference, "candidate": candidate, "scheduled_blocks": len(blocks),
212
            "complete_pairs": len(complete), "incomplete_pairs": len(blocks) - len(complete),
213
            "success_delta_percentage_points": 100 * statistics.fmean(deltas) if deltas else None,
214
            "confidence_interval": interval, "confidence": confidence,
215
            "method": "percentile_bootstrap_recorded_trial_blocks",
216
            "estimand": "candidate_minus_reference_verified_success_on_complete_pairs",
217
            "multiplicity_adjusted": False, "claim_eligible": False,
218
            "success_conditioned_efficiency": _paired_efficiency(left, right, complete, bootstrap_samples, confidence, seed),
219
        })
220
    return comparisons
221
222
223
def _paired_efficiency(left, right, complete, samples, confidence, seed):
224
    successes = [block for block in complete if left[block]["outcome"] == right[block]["outcome"] == "success"]
225
    result = {}
226
    for metric, source_path in (("agent_active_ms", ("wall_clock_metrics", "measurement_source")),
227
                                ("reported_tokens", ("token_metrics", "token_source"))):
228
        pairs = []
229
        missing = incompatible = 0
230
        conventions = set()
231
        for block in successes:
232
            a, b = left[block]["row"], right[block]["row"]
233
            av, bv = _metric(a, METRICS[metric]), _metric(b, METRICS[metric])
234
            if av is None or bv is None:
235
                missing += 1
236
                continue
237
            a_source = a.get(source_path[0], {}).get(source_path[1])
238
            b_source = b.get(source_path[0], {}).get(source_path[1])
239
            if not isinstance(a_source, str) or not a_source or a_source != b_source:
240
                incompatible += 1
241
                continue
242
            conventions.add(a_source)
243
            pairs.append((av, bv))
244
        # Different conventions are not one population even if each pair agrees.
245
        if len(conventions) > 1:
246
            incompatible += len(pairs)
247
            pairs = []
248
        def difference(values):
249
            return statistics.fmean(b - a for a, b in values)
250
        interval = None
251
        if len(pairs) >= 2:
252
            interval = list(bootstrap_ci([b - a for a, b in pairs], statistics.fmean,
253
                                         samples=samples, confidence=confidence, seed=seed))
254
        result[metric] = {"jointly_successful_pairs": len(successes), "measured_pairs": len(pairs),
255
                          "missing_metric_pairs": missing, "incompatible_or_unknown_source_pairs": incompatible,
256
                          "measurement_source": next(iter(conventions)) if len(conventions) == 1 else None,
257
                          "candidate_minus_reference_mean_delta": difference(pairs) if pairs else None,
258
                          "confidence_interval": interval, "confidence": confidence,
259
                          "estimand": "paired_mean_difference_conditioned_on_both_subjects_succeeding",
260
                          "lower_is_better": True, "claim_eligible": False}
261
    return result
262
263
264
def report_campaign(plan: dict, events: list[dict], *, bootstrap_samples=2000, confidence=.95, seed=20260910) -> dict:
265
    validate_interval_settings(bootstrap_samples, confidence)
266
    states = _trials(plan, events)
267
    grouped = {}
268
    for state in states:
269
        key = tuple(state["trial"][field] for field in CONDITION_FIELDS)
270
        grouped.setdefault(key, []).append(state)
271
    groups = []
272
    for key, condition_states in sorted(grouped.items(), key=lambda item: repr(item[0])):
273
        subjects = []
274
        for subject in sorted({state["trial"]["subject"] for state in condition_states}):
275
            selected = [state for state in condition_states if state["trial"]["subject"] == subject]
276
            conflicts = population_conflicts([state["row"] for state in selected if isinstance(state["row"], dict)])
277
            if conflicts:
278
                raise ValueError("incompatible campaign population: " + ", ".join(conflicts))
279
            counts = _counts(selected)
280
            complete = counts["started"] > 0 and not counts["interrupted"] and not counts["skipped"] and not counts["infrastructure_failure"]
281
            subjects.append({"subject": subject, "counts": counts,
282
                             "verified_success_fraction_of_started": counts["success"] / counts["started"] if counts["started"] else None,
283
                             "success_wilson_interval": _wilson(counts["success"], counts["started"], confidence) if complete else None,
284
                             "success_interval_reason": None if complete else "no_attempts_or_unresolved_started_trials",
285
                             "resources": _resources(selected)})
286
        groups.append({"condition": dict(zip(CONDITION_FIELDS, key)), "subjects": subjects,
287
                       "paired_comparisons": _paired(condition_states, bootstrap_samples, confidence, seed)})
288
    counts = _counts(states)
289
    reasons = ["diagnostic_report_only_no_confirmatory_inference", "independent_durable_evidence_not_certified_by_report"]
290
    if any(state["trial"]["agent"] == "mock" or
291
           (isinstance(state["row"], dict) and (state["row"].get("agent") or {}).get("adapter") == "deterministic_mock")
292
           for state in states):
293
        reasons.append("mock_agent_measurements_are_instrument_checks")
294
    if counts["budget_truncated"]:
295
        reasons.append("recorded_timeout_differs_from_frozen_budget")
296
    if any(event.get("event") == "journal_recovery" for event in events):
297
        reasons.append("journal_recovery_contains_uncertain_evidence")
298
    if counts["interrupted"] or counts["unstarted"] or counts["skipped"] or counts["infrastructure_failure"]:
299
        reasons.append("schedule_or_attempt_accounting_incomplete")
300
    if any(not state["trial"].get("model") for state in states):
301
        reasons.append("model_identity_unresolved")
302
    return {"schema_version": 1, "campaign_id": plan.get("campaign_id"), "plan_sha256": plan["plan_sha256"],
303
            "journal_recoveries": [event for event in events if event.get("event") == "journal_recovery"],
304
            "invalidated_count": sum(event.get("measurement_invalidated") is True for event in events),
305
            "invalidated_trials": [{"trial_id": event["trial_id"], "reason": event["invalidation_reason"],
306
                                    "rejected_row_retained": event.get("rejected_row") is not None}
307
                                   for event in events if event.get("measurement_invalidated") is True],
308
            "evidence_class": "diagnostic_agent_campaign", "claim_eligible": False,
309
            "claim_ineligibility_reasons": reasons, "counts": counts, "groups": groups,
310
            "confidence": confidence, "bootstrap_samples": bootstrap_samples, "analysis_seed": seed,
311
            "notes": ["Agent active time is outer CLI time including tool waits, not isolated model time.",
312
                      "Cost-weighted tokens are a proxy, never USD. Missing usage makes complete totals null.",
313
                      "Paired intervals condition on complete recorded blocks; incomplete pairs remain in denominators.",
314
                      "A nonempty requested model does not establish provider-resolved model identity.",
315
                      "Budget-truncated terminal trials are retained as interruptions and excluded from complete pairs.",
316
                      "Uncertain torn starts are conservative reservations, not observed execution or elapsed time.",
317
                      "Fixed-task repetitions do not establish independent-session or unseen-task generalization."]}
318
319
320
def render_markdown(summary: dict) -> str:
321
    lines = [f"# Agent campaign: {summary['campaign_id']}", "", "Diagnostic evidence only; no public claim is certified.", ""]
322
    lines.append(f"Invalidated measurements: {summary['invalidated_count']} (excluded from complete pairs).")
323
    for item in summary["invalidated_trials"]:
324
        lines.append(f"- {item['trial_id']}: {item['reason']}; rejected row retained in journal: {item['rejected_row_retained']}")
325
    lines.append("")
326
    def cell(value):
327
        return "unmeasured" if value is None else f"{value:.3f}"
328
    for group in summary["groups"]:
329
        lines.extend(["Condition: " + ", ".join(f"{key}={value}" for key, value in group["condition"].items()), "",
330
                      "| Subject | Scheduled | Started | Success | Failure | Timeout | Infrastructure | Interrupted | Skipped | Unstarted | Verified / started | Wilson interval |",
331
                      "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"])
332
        for subject in group["subjects"]:
333
            counts = subject["counts"]
334
            lines.append("| " + subject["subject"] + " | " + " | ".join(str(counts[name]) for name in
335
                         ("scheduled", "started", "success", "failure", "timeout", "infrastructure_failure", "interrupted", "skipped", "unstarted")) +
336
                         f" | {cell(subject['verified_success_fraction_of_started'])} | {subject['success_wilson_interval'] or 'unmeasured'} |")
337
        lines.extend(["", "Efficiency below is conditioned on successful trials; totals include all started attempts.", "",
338
                      "| Subject / metric | Successful median | Measured successes | All-attempt measured / started | Complete total |",
339
                      "| --- | ---: | ---: | --- | ---: |"])
340
        for subject in group["subjects"]:
341
            for metric, values in subject["resources"].items():
342
                success = values["success_conditioned"]
343
                lines.append(f"| {subject['subject']} / {metric} | {cell(success['median'])} | {success['measured_n']}/{success['successful_n']} | {values['measured_n']}/{values['attempted_n']} | {cell(values['complete_total'])} |")
344
        lines.append("")
345
        for pair in group["paired_comparisons"]:
346
            lines.append(f"{pair['candidate']} minus {pair['reference']}: {cell(pair['success_delta_percentage_points'])} percentage points on {pair['complete_pairs']}/{pair['scheduled_blocks']} complete pairs; descriptive bootstrap CI: {pair['confidence_interval'] or 'unmeasured'}; multiplicity unadjusted.")
347
            for metric, evidence in pair["success_conditioned_efficiency"].items():
348
                lines.append(f"Paired {metric} mean difference, conditioned on both succeeding: {cell(evidence['candidate_minus_reference_mean_delta'])}; CI {evidence['confidence_interval'] or 'unmeasured'}; measured {evidence['measured_pairs']}/{evidence['jointly_successful_pairs']} pairs; missing metrics {evidence['missing_metric_pairs']}; incompatible/unknown sources {evidence['incompatible_or_unknown_source_pairs']}. Negative favors candidate.")
349
        lines.append("")
350
    lines.extend(summary["notes"])
351
    lines.extend(["", "Claim ineligibility: " + "; ".join(summary["claim_ineligibility_reasons"]), ""])
352
    return "\n".join(lines)