Viewing files at commit 1dc7410826b4Commit detailsView latest

Browse files
scripts/oakbench/campaign_report.py 371 lines · 23.5 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
        # Incompatible evidence refuses the PAIR, never the whole report: the
193
        # diagnostic report must still render (a default Git-vs-Oak campaign
194
        # legitimately carries different committed-tree evidence classes).
195
        refused: dict[str, list[str]] = {}
196
        for block in complete:
197
            if isinstance(left[block]["row"], dict) and isinstance(right[block]["row"], dict):
198
                mismatch = comparison_conflicts(comparison_identity(left[block]["row"]), comparison_identity(right[block]["row"]))
199
                # A measured incorrect worktree need not reach a committed-tree
200
                # proof. Keep that failure in the denominator; successful proof
201
                # classes must still agree before comparison.
202
                if any(row.get("workflow_integrity_passed") is False
203
                       and row.get("agent_launched") is True and row.get("outcome_attribution") == "agent"
204
                       for row in (left[block]["row"], right[block]["row"])):
205
                    mismatch = [field for field in mismatch if field != "workflow_integrity_evidence_class"]
206
                if mismatch:
207
                    refused[block] = mismatch
208
        complete = [block for block in complete if block not in refused]
209
        deltas = [int(right[block]["outcome"] == "success") - int(left[block]["outcome"] == "success")
210
                  for block in complete]
211
        interval = None
212
        if len(deltas) >= 2 and not refused:
213
            interval = list(bootstrap_ci([100 * delta for delta in deltas], statistics.fmean,
214
                                         samples=bootstrap_samples, confidence=confidence, seed=seed))
215
        # QA P1 A2: refusal removes the concordant-success pairs and keeps the
216
        # discordant ones, so any delta on the remainder is biased by
217
        # construction. A refused comparison publishes no delta at all.
218
        comparisons.append({
219
            "reference": reference, "candidate": candidate, "scheduled_blocks": len(blocks),
220
            "complete_pairs": len(complete), "incomplete_pairs": len(blocks) - len(complete),
221
            "incompatible_evidence_pairs": len(refused),
222
            "incompatible_evidence_fields": sorted({field for fields in refused.values() for field in fields}),
223
            "comparison_refused": bool(refused),
224
            "refusal_reason": ("incompatible_paired_evidence: " + ", ".join(
225
                sorted({field for fields in refused.values() for field in fields}))) if refused else None,
226
            "success_delta_percentage_points": 100 * statistics.fmean(deltas) if deltas and not refused else None,
227
            "confidence_interval": interval, "confidence": confidence,
228
            "method": "percentile_bootstrap_recorded_trial_blocks",
229
            "estimand": "candidate_minus_reference_verified_success_on_complete_pairs",
230
            "multiplicity_adjusted": False, "claim_eligible": False,
231
            "success_conditioned_efficiency": (None if refused else
232
                                               _paired_efficiency(left, right, complete, bootstrap_samples, confidence, seed)),
233
        })
234
    return comparisons
235
236
237
def _paired_efficiency(left, right, complete, samples, confidence, seed):
238
    successes = [block for block in complete if left[block]["outcome"] == right[block]["outcome"] == "success"]
239
    result = {}
240
    for metric, source_path in (("agent_active_ms", ("wall_clock_metrics", "measurement_source")),
241
                                ("reported_tokens", ("token_metrics", "token_source"))):
242
        pairs = []
243
        missing = incompatible = 0
244
        conventions = set()
245
        for block in successes:
246
            a, b = left[block]["row"], right[block]["row"]
247
            av, bv = _metric(a, METRICS[metric]), _metric(b, METRICS[metric])
248
            if av is None or bv is None:
249
                missing += 1
250
                continue
251
            a_source = a.get(source_path[0], {}).get(source_path[1])
252
            b_source = b.get(source_path[0], {}).get(source_path[1])
253
            if not isinstance(a_source, str) or not a_source or a_source != b_source:
254
                incompatible += 1
255
                continue
256
            conventions.add(a_source)
257
            pairs.append((av, bv))
258
        # Different conventions are not one population even if each pair agrees.
259
        if len(conventions) > 1:
260
            incompatible += len(pairs)
261
            pairs = []
262
        def difference(values):
263
            return statistics.fmean(b - a for a, b in values)
264
        interval = None
265
        if len(pairs) >= 2:
266
            interval = list(bootstrap_ci([b - a for a, b in pairs], statistics.fmean,
267
                                         samples=samples, confidence=confidence, seed=seed))
268
        result[metric] = {"jointly_successful_pairs": len(successes), "measured_pairs": len(pairs),
269
                          "missing_metric_pairs": missing, "incompatible_or_unknown_source_pairs": incompatible,
270
                          "measurement_source": next(iter(conventions)) if len(conventions) == 1 else None,
271
                          "candidate_minus_reference_mean_delta": difference(pairs) if pairs else None,
272
                          "confidence_interval": interval, "confidence": confidence,
273
                          "estimand": "paired_mean_difference_conditioned_on_both_subjects_succeeding",
274
                          "lower_is_better": True, "claim_eligible": False}
275
    return result
276
277
278
def report_campaign(plan: dict, events: list[dict], *, bootstrap_samples=2000, confidence=.95, seed=20260910) -> dict:
279
    validate_interval_settings(bootstrap_samples, confidence)
280
    states = _trials(plan, events)
281
    grouped = {}
282
    for state in states:
283
        key = tuple(state["trial"][field] for field in CONDITION_FIELDS)
284
        grouped.setdefault(key, []).append(state)
285
    groups = []
286
    for key, condition_states in sorted(grouped.items(), key=lambda item: repr(item[0])):
287
        subjects = []
288
        for subject in sorted({state["trial"]["subject"] for state in condition_states}):
289
            selected = [state for state in condition_states if state["trial"]["subject"] == subject]
290
            conflicts = population_conflicts([state["row"] for state in selected if isinstance(state["row"], dict)])
291
            if conflicts:
292
                raise ValueError("incompatible campaign population: " + ", ".join(conflicts))
293
            counts = _counts(selected)
294
            complete = counts["started"] > 0 and not counts["interrupted"] and not counts["skipped"] and not counts["infrastructure_failure"]
295
            subjects.append({"subject": subject, "counts": counts,
296
                             "verified_success_fraction_of_started": counts["success"] / counts["started"] if counts["started"] else None,
297
                             "success_wilson_interval": _wilson(counts["success"], counts["started"], confidence) if complete else None,
298
                             "success_interval_reason": None if complete else "no_attempts_or_unresolved_started_trials",
299
                             "resources": _resources(selected)})
300
        groups.append({"condition": dict(zip(CONDITION_FIELDS, key)), "subjects": subjects,
301
                       "paired_comparisons": _paired(condition_states, bootstrap_samples, confidence, seed)})
302
    counts = _counts(states)
303
    reasons = ["diagnostic_report_only_no_confirmatory_inference", "independent_durable_evidence_not_certified_by_report"]
304
    if any(state["trial"]["agent"] == "mock" or
305
           (isinstance(state["row"], dict) and (state["row"].get("agent") or {}).get("adapter") == "deterministic_mock")
306
           for state in states):
307
        reasons.append("mock_agent_measurements_are_instrument_checks")
308
    if counts["budget_truncated"]:
309
        reasons.append("recorded_timeout_differs_from_frozen_budget")
310
    if any(event.get("event") == "journal_recovery" for event in events):
311
        reasons.append("journal_recovery_contains_uncertain_evidence")
312
    if counts["interrupted"] or counts["unstarted"] or counts["skipped"] or counts["infrastructure_failure"]:
313
        reasons.append("schedule_or_attempt_accounting_incomplete")
314
    if any(pair.get("comparison_refused") for group in groups for pair in group["paired_comparisons"]):
315
        reasons.append("paired_evidence_incompatible")
316
    if any(not state["trial"].get("model") for state in states):
317
        reasons.append("model_identity_unresolved")
318
    return {"schema_version": 1, "campaign_id": plan.get("campaign_id"), "plan_sha256": plan["plan_sha256"],
319
            "journal_recoveries": [event for event in events if event.get("event") == "journal_recovery"],
320
            "invalidated_count": sum(event.get("measurement_invalidated") is True for event in events),
321
            "invalidated_trials": [{"trial_id": event["trial_id"], "reason": event["invalidation_reason"],
322
                                    "rejected_row_retained": event.get("rejected_row") is not None}
323
                                   for event in events if event.get("measurement_invalidated") is True],
324
            "evidence_class": "diagnostic_agent_campaign", "claim_eligible": False,
325
            "claim_ineligibility_reasons": reasons, "counts": counts, "groups": groups,
326
            "confidence": confidence, "bootstrap_samples": bootstrap_samples, "analysis_seed": seed,
327
            "notes": ["Agent active time is outer CLI time including tool waits, not isolated model time.",
328
                      "Cost-weighted tokens are a proxy, never USD. Missing usage makes complete totals null.",
329
                      "Paired intervals condition on complete recorded blocks; incomplete pairs remain in denominators.",
330
                      "A nonempty requested model does not establish provider-resolved model identity.",
331
                      "Budget-truncated terminal trials are retained as interruptions and excluded from complete pairs.",
332
                      "Uncertain torn starts are conservative reservations, not observed execution or elapsed time.",
333
                      "Fixed-task repetitions do not establish independent-session or unseen-task generalization."]}
334
335
336
def render_markdown(summary: dict) -> str:
337
    lines = [f"# Agent campaign: {summary['campaign_id']}", "", "Diagnostic evidence only; no public claim is certified.", ""]
338
    lines.append(f"Invalidated measurements: {summary['invalidated_count']} (excluded from complete pairs).")
339
    for item in summary["invalidated_trials"]:
340
        lines.append(f"- {item['trial_id']}: {item['reason']}; rejected row retained in journal: {item['rejected_row_retained']}")
341
    lines.append("")
342
    def cell(value):
343
        return "unmeasured" if value is None else f"{value:.3f}"
344
    for group in summary["groups"]:
345
        lines.extend(["Condition: " + ", ".join(f"{key}={value}" for key, value in group["condition"].items()), "",
346
                      "| Subject | Scheduled | Started | Success | Failure | Timeout | Infrastructure | Interrupted | Skipped | Unstarted | Verified / started | Wilson interval |",
347
                      "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"])
348
        for subject in group["subjects"]:
349
            counts = subject["counts"]
350
            lines.append("| " + subject["subject"] + " | " + " | ".join(str(counts[name]) for name in
351
                         ("scheduled", "started", "success", "failure", "timeout", "infrastructure_failure", "interrupted", "skipped", "unstarted")) +
352
                         f" | {cell(subject['verified_success_fraction_of_started'])} | {subject['success_wilson_interval'] or 'unmeasured'} |")
353
        lines.extend(["", "Efficiency below is conditioned on successful trials; totals include all started attempts.", "",
354
                      "| Subject / metric | Successful median | Measured successes | All-attempt measured / started | Complete total |",
355
                      "| --- | ---: | ---: | --- | ---: |"])
356
        for subject in group["subjects"]:
357
            for metric, values in subject["resources"].items():
358
                success = values["success_conditioned"]
359
                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'])} |")
360
        lines.append("")
361
        for pair in group["paired_comparisons"]:
362
            if pair.get("comparison_refused"):
363
                lines.append(f"{pair['candidate']} vs {pair['reference']}: comparison REFUSED, {pair['incompatible_evidence_pairs']} pair(s) with incompatible evidence ({pair['refusal_reason']}); no success or efficiency delta is reported.")
364
                continue
365
            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.")
366
            for metric, evidence in pair["success_conditioned_efficiency"].items():
367
                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.")
368
        lines.append("")
369
    lines.extend(summary["notes"])
370
    lines.extend(["", "Claim ineligibility: " + "; ".join(summary["claim_ineligibility_reasons"]), ""])
371
    return "\n".join(lines)