| 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", "infrastructure_failure"}
|
| 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 isinstance(row, dict) and row.get("returncode") == 77:
|
| 66 | if row.get("outcome") != "error" or row.get("success") is not False or not row.get("skip_reason"):
|
| 67 | raise ValueError("unmeasured instrument row has contradictory outcome")
|
| 68 | return "skipped", row
|
| 69 | if explicit in {"skipped", "skip"}:
|
| 70 | return "skipped", row
|
| 71 | if explicit == "interrupted":
|
| 72 | return "interrupted", row
|
| 73 | if explicit in {"error", "infrastructure_failure"}:
|
| 74 | if row is not None and (not isinstance(row, dict) or row.get("outcome") != "error" or row.get("success") is not False):
|
| 75 | raise ValueError("infrastructure error contradicts terminal task row")
|
| 76 | return "infrastructure_failure", row
|
| 77 | if not isinstance(row, dict) or type(row.get("success")) is not bool:
|
| 78 | raise ValueError("finished trial lacks an explicit row success outcome")
|
| 79 | outcome = row.get("outcome")
|
| 80 | if outcome not in {"pass", "fail", "timeout", "error"} or (row["success"] != (outcome == "pass")):
|
| 81 | raise ValueError("contradictory or unknown row outcome")
|
| 82 | return {"pass": "success", "fail": "failure", "timeout": "timeout", "error": "infrastructure_failure"}[outcome], row
|
| 83 |
|
| 84 |
|
| 85 | def _trials(plan, events):
|
| 86 | if plan.get("schema_version") != 1 or not isinstance(plan.get("schedule"), list):
|
| 87 | raise ValueError("unsupported campaign plan")
|
| 88 | if not isinstance(plan.get("plan_sha256"), str) or not plan["plan_sha256"]:
|
| 89 | raise ValueError("campaign plan digest missing")
|
| 90 | trials = {}
|
| 91 | cells = set()
|
| 92 | for item in plan["schedule"]:
|
| 93 | if not all(key in item for key in ("trial_id", "block_id", "subject", *CONDITION_FIELDS)):
|
| 94 | raise ValueError("schedule trial missing identity")
|
| 95 | trial_id = item["trial_id"]
|
| 96 | cell = tuple(item[key] for key in (*CONDITION_FIELDS, "block_id", "subject"))
|
| 97 | if trial_id in trials or cell in cells:
|
| 98 | raise ValueError("duplicate scheduled trial or subject in paired block")
|
| 99 | cells.add(cell)
|
| 100 | trials[trial_id] = {"trial": item, "started": False, "finished": False,
|
| 101 | "outcome": "unstarted", "row": None}
|
| 102 | for event in events:
|
| 103 | if event.get("plan_sha256") != plan["plan_sha256"]:
|
| 104 | raise ValueError("journal plan digest mismatch")
|
| 105 | if event.get("event") == "journal_recovery":
|
| 106 | continue
|
| 107 | if event.get("trial_id") not in trials:
|
| 108 | raise ValueError("journal names unscheduled trial")
|
| 109 | state = trials[event["trial_id"]]
|
| 110 | if event.get("event") == "started":
|
| 111 | if state["started"] or state["finished"]:
|
| 112 | raise ValueError("duplicate or out-of-order trial start")
|
| 113 | state.update(started=True, outcome="interrupted")
|
| 114 | frozen_timeout = plan.get("manifest", {}).get("trial_timeout_seconds")
|
| 115 | state["budget_truncated"] = frozen_timeout is not None and event.get("timeout_seconds") != frozen_timeout
|
| 116 | elif event.get("event") == "finished":
|
| 117 | if state["finished"]:
|
| 118 | raise ValueError("duplicate terminal trial event")
|
| 119 | outcome, row = _outcome(event)
|
| 120 | if not state["started"] and outcome != "skipped":
|
| 121 | raise ValueError("finished trial has no start event")
|
| 122 | if isinstance(row, dict):
|
| 123 | trial = state["trial"]
|
| 124 | for row_key, expected in (("task_id", trial["trial_id"]), ("bench_id", plan.get("campaign_id")),
|
| 125 | ("run", trial.get("repetition"))):
|
| 126 | if row_key in row and row[row_key] != expected:
|
| 127 | raise ValueError("row trial identity contradicts schedule")
|
| 128 | for row_key, trial_key in (("subject", "subject"), ("scenario", "workflow")):
|
| 129 | if row_key in row and row[row_key] != trial[trial_key]:
|
| 130 | raise ValueError("row identity contradicts scheduled trial")
|
| 131 | agent = row.get("agent", {})
|
| 132 | if isinstance(agent, dict):
|
| 133 | for key, planned in (("name", "agent"), ("model", "model"), ("instruction_level", "instruction_level")):
|
| 134 | if agent.get(key) is not None and agent[key] != trial[planned]:
|
| 135 | raise ValueError("row agent condition contradicts scheduled trial")
|
| 136 | state.update(finished=True, outcome=outcome, row=row)
|
| 137 | if state.get("budget_truncated"):
|
| 138 | state["outcome"] = "interrupted"
|
| 139 | else:
|
| 140 | raise ValueError("unknown journal event")
|
| 141 | return list(trials.values())
|
| 142 |
|
| 143 |
|
| 144 | def _counts(states):
|
| 145 | result = {"scheduled": len(states), "started": sum(state["started"] for state in states),
|
| 146 | "finished": sum(state["finished"] for state in states)}
|
| 147 | result["budget_truncated"] = sum(bool(state.get("budget_truncated")) for state in states)
|
| 148 | result.update({name: sum(state["outcome"] == name for state in states) for name in OUTCOMES})
|
| 149 | return result
|
| 150 |
|
| 151 |
|
| 152 | def _resources(states):
|
| 153 | attempted = [state for state in states if state["started"]]
|
| 154 | successful = [state for state in states if state["outcome"] == "success"]
|
| 155 | resources = {}
|
| 156 | for name, path in METRICS.items():
|
| 157 | values = [value for state in attempted if (value := _metric(state["row"], path)) is not None]
|
| 158 | success_values = [value for state in successful if (value := _metric(state["row"], path)) is not None]
|
| 159 | observed_sum = sum(values) if values else None
|
| 160 | total = observed_sum if attempted and len(values) == len(attempted) else None
|
| 161 | resources[name] = {
|
| 162 | "attempted_n": len(attempted), "measured_n": len(values), "missing_n": len(attempted) - len(values),
|
| 163 | "observed_sum": observed_sum, "complete_total": total,
|
| 164 | "observed_cost_per_success": total / len(successful) if total is not None and successful else None,
|
| 165 | "success_conditioned": {
|
| 166 | "successful_n": len(successful), "measured_n": len(success_values),
|
| 167 | "missing_n": len(successful) - len(success_values),
|
| 168 | "median": statistics.median(success_values) if success_values else None,
|
| 169 | "mean": statistics.fmean(success_values) if success_values else None,
|
| 170 | },
|
| 171 | }
|
| 172 | return resources
|
| 173 |
|
| 174 |
|
| 175 | def _paired(states, bootstrap_samples, confidence, seed):
|
| 176 | by_subject = {}
|
| 177 | for state in states:
|
| 178 | trial = state["trial"]
|
| 179 | by_subject.setdefault(trial["subject"], {})[trial["block_id"]] = state
|
| 180 | comparisons = []
|
| 181 | for reference, candidate in itertools.combinations(sorted(by_subject), 2):
|
| 182 | left, right = by_subject[reference], by_subject[candidate]
|
| 183 | blocks = sorted(set(left) | set(right))
|
| 184 | complete = [block for block in blocks if block in left and block in right
|
| 185 | and left[block]["outcome"] in COMPLETE and right[block]["outcome"] in COMPLETE]
|
| 186 | for block in complete:
|
| 187 | if isinstance(left[block]["row"], dict) and isinstance(right[block]["row"], dict):
|
| 188 | mismatch = comparison_conflicts(comparison_identity(left[block]["row"]), comparison_identity(right[block]["row"]))
|
| 189 | if mismatch:
|
| 190 | raise ValueError("incompatible paired evidence: " + ", ".join(mismatch))
|
| 191 | deltas = [int(right[block]["outcome"] == "success") - int(left[block]["outcome"] == "success")
|
| 192 | for block in complete]
|
| 193 | interval = None
|
| 194 | if len(deltas) >= 2:
|
| 195 | interval = list(bootstrap_ci([100 * delta for delta in deltas], statistics.fmean,
|
| 196 | samples=bootstrap_samples, confidence=confidence, seed=seed))
|
| 197 | comparisons.append({
|
| 198 | "reference": reference, "candidate": candidate, "scheduled_blocks": len(blocks),
|
| 199 | "complete_pairs": len(complete), "incomplete_pairs": len(blocks) - len(complete),
|
| 200 | "success_delta_percentage_points": 100 * statistics.fmean(deltas) if deltas else None,
|
| 201 | "confidence_interval": interval, "confidence": confidence,
|
| 202 | "method": "percentile_bootstrap_recorded_trial_blocks",
|
| 203 | "estimand": "candidate_minus_reference_verified_success_on_complete_pairs",
|
| 204 | "multiplicity_adjusted": False, "claim_eligible": False,
|
| 205 | "success_conditioned_efficiency": _paired_efficiency(left, right, complete, bootstrap_samples, confidence, seed),
|
| 206 | })
|
| 207 | return comparisons
|
| 208 |
|
| 209 |
|
| 210 | def _paired_efficiency(left, right, complete, samples, confidence, seed):
|
| 211 | successes = [block for block in complete if left[block]["outcome"] == right[block]["outcome"] == "success"]
|
| 212 | result = {}
|
| 213 | for metric, source_path in (("agent_active_ms", ("wall_clock_metrics", "measurement_source")),
|
| 214 | ("reported_tokens", ("token_metrics", "token_source"))):
|
| 215 | pairs = []
|
| 216 | missing = incompatible = 0
|
| 217 | conventions = set()
|
| 218 | for block in successes:
|
| 219 | a, b = left[block]["row"], right[block]["row"]
|
| 220 | av, bv = _metric(a, METRICS[metric]), _metric(b, METRICS[metric])
|
| 221 | if av is None or bv is None:
|
| 222 | missing += 1
|
| 223 | continue
|
| 224 | a_source = a.get(source_path[0], {}).get(source_path[1])
|
| 225 | b_source = b.get(source_path[0], {}).get(source_path[1])
|
| 226 | if not isinstance(a_source, str) or not a_source or a_source != b_source:
|
| 227 | incompatible += 1
|
| 228 | continue
|
| 229 | conventions.add(a_source)
|
| 230 | pairs.append((av, bv))
|
| 231 | # Different conventions are not one population even if each pair agrees.
|
| 232 | if len(conventions) > 1:
|
| 233 | incompatible += len(pairs)
|
| 234 | pairs = []
|
| 235 | def difference(values):
|
| 236 | return statistics.fmean(b - a for a, b in values)
|
| 237 | interval = None
|
| 238 | if len(pairs) >= 2:
|
| 239 | interval = list(bootstrap_ci([b - a for a, b in pairs], statistics.fmean,
|
| 240 | samples=samples, confidence=confidence, seed=seed))
|
| 241 | result[metric] = {"jointly_successful_pairs": len(successes), "measured_pairs": len(pairs),
|
| 242 | "missing_metric_pairs": missing, "incompatible_or_unknown_source_pairs": incompatible,
|
| 243 | "measurement_source": next(iter(conventions)) if len(conventions) == 1 else None,
|
| 244 | "candidate_minus_reference_mean_delta": difference(pairs) if pairs else None,
|
| 245 | "confidence_interval": interval, "confidence": confidence,
|
| 246 | "estimand": "paired_mean_difference_conditioned_on_both_subjects_succeeding",
|
| 247 | "lower_is_better": True, "claim_eligible": False}
|
| 248 | return result
|
| 249 |
|
| 250 |
|
| 251 | def report_campaign(plan: dict, events: list[dict], *, bootstrap_samples=2000, confidence=.95, seed=20260910) -> dict:
|
| 252 | validate_interval_settings(bootstrap_samples, confidence)
|
| 253 | states = _trials(plan, events)
|
| 254 | grouped = {}
|
| 255 | for state in states:
|
| 256 | key = tuple(state["trial"][field] for field in CONDITION_FIELDS)
|
| 257 | grouped.setdefault(key, []).append(state)
|
| 258 | groups = []
|
| 259 | for key, condition_states in sorted(grouped.items(), key=lambda item: repr(item[0])):
|
| 260 | subjects = []
|
| 261 | for subject in sorted({state["trial"]["subject"] for state in condition_states}):
|
| 262 | selected = [state for state in condition_states if state["trial"]["subject"] == subject]
|
| 263 | conflicts = population_conflicts([state["row"] for state in selected if isinstance(state["row"], dict)])
|
| 264 | if conflicts:
|
| 265 | raise ValueError("incompatible campaign population: " + ", ".join(conflicts))
|
| 266 | counts = _counts(selected)
|
| 267 | complete = counts["started"] > 0 and not counts["interrupted"] and not counts["skipped"]
|
| 268 | subjects.append({"subject": subject, "counts": counts,
|
| 269 | "verified_success_fraction_of_started": counts["success"] / counts["started"] if counts["started"] else None,
|
| 270 | "success_wilson_interval": _wilson(counts["success"], counts["started"], confidence) if complete else None,
|
| 271 | "success_interval_reason": None if complete else "no_attempts_or_unresolved_started_trials",
|
| 272 | "resources": _resources(selected)})
|
| 273 | groups.append({"condition": dict(zip(CONDITION_FIELDS, key)), "subjects": subjects,
|
| 274 | "paired_comparisons": _paired(condition_states, bootstrap_samples, confidence, seed)})
|
| 275 | counts = _counts(states)
|
| 276 | reasons = ["diagnostic_report_only_no_confirmatory_inference", "independent_durable_evidence_not_certified_by_report"]
|
| 277 | if any(state["trial"]["agent"] == "mock" or
|
| 278 | (isinstance(state["row"], dict) and (state["row"].get("agent") or {}).get("adapter") == "deterministic_mock")
|
| 279 | for state in states):
|
| 280 | reasons.append("mock_agent_measurements_are_instrument_checks")
|
| 281 | if counts["budget_truncated"]:
|
| 282 | reasons.append("recorded_timeout_differs_from_frozen_budget")
|
| 283 | if any(event.get("event") == "journal_recovery" for event in events):
|
| 284 | reasons.append("journal_recovery_contains_uncertain_evidence")
|
| 285 | if counts["interrupted"] or counts["unstarted"] or counts["skipped"]:
|
| 286 | reasons.append("schedule_or_attempt_accounting_incomplete")
|
| 287 | if any(not state["trial"].get("model") for state in states):
|
| 288 | reasons.append("model_identity_unresolved")
|
| 289 | return {"schema_version": 1, "campaign_id": plan.get("campaign_id"), "plan_sha256": plan["plan_sha256"],
|
| 290 | "journal_recoveries": [event for event in events if event.get("event") == "journal_recovery"],
|
| 291 | "evidence_class": "diagnostic_agent_campaign", "claim_eligible": False,
|
| 292 | "claim_ineligibility_reasons": reasons, "counts": counts, "groups": groups,
|
| 293 | "confidence": confidence, "bootstrap_samples": bootstrap_samples, "analysis_seed": seed,
|
| 294 | "notes": ["Agent active time is outer CLI time including tool waits, not isolated model time.",
|
| 295 | "Cost-weighted tokens are a proxy, never USD. Missing usage makes complete totals null.",
|
| 296 | "Paired intervals condition on complete recorded blocks; incomplete pairs remain in denominators.",
|
| 297 | "A nonempty requested model does not establish provider-resolved model identity.",
|
| 298 | "Budget-truncated terminal trials are retained as interruptions and excluded from complete pairs.",
|
| 299 | "Uncertain torn starts are conservative reservations, not observed execution or elapsed time.",
|
| 300 | "Fixed-task repetitions do not establish independent-session or unseen-task generalization."]}
|
| 301 |
|
| 302 |
|
| 303 | def render_markdown(summary: dict) -> str:
|
| 304 | lines = [f"# Agent campaign: {summary['campaign_id']}", "", "Diagnostic evidence only; no public claim is certified.", ""]
|
| 305 | def cell(value):
|
| 306 | return "unmeasured" if value is None else f"{value:.3f}"
|
| 307 | for group in summary["groups"]:
|
| 308 | lines.extend(["Condition: " + ", ".join(f"{key}={value}" for key, value in group["condition"].items()), "",
|
| 309 | "| Subject | Scheduled | Started | Success | Failure | Timeout | Infrastructure | Interrupted | Skipped | Unstarted | Verified / started | Wilson interval |",
|
| 310 | "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"])
|
| 311 | for subject in group["subjects"]:
|
| 312 | counts = subject["counts"]
|
| 313 | lines.append("| " + subject["subject"] + " | " + " | ".join(str(counts[name]) for name in
|
| 314 | ("scheduled", "started", "success", "failure", "timeout", "infrastructure_failure", "interrupted", "skipped", "unstarted")) +
|
| 315 | f" | {cell(subject['verified_success_fraction_of_started'])} | {subject['success_wilson_interval'] or 'unmeasured'} |")
|
| 316 | lines.extend(["", "Efficiency below is conditioned on successful trials; totals include all started attempts.", "",
|
| 317 | "| Subject / metric | Successful median | Measured successes | All-attempt measured / started | Complete total |",
|
| 318 | "| --- | ---: | ---: | --- | ---: |"])
|
| 319 | for subject in group["subjects"]:
|
| 320 | for metric, values in subject["resources"].items():
|
| 321 | success = values["success_conditioned"]
|
| 322 | 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'])} |")
|
| 323 | lines.append("")
|
| 324 | for pair in group["paired_comparisons"]:
|
| 325 | 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.")
|
| 326 | for metric, evidence in pair["success_conditioned_efficiency"].items():
|
| 327 | 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.")
|
| 328 | lines.append("")
|
| 329 | lines.extend(summary["notes"])
|
| 330 | lines.extend(["", "Claim ineligibility: " + "; ".join(summary["claim_ineligibility_reasons"]), ""])
|
| 331 | return "\n".join(lines)
|