Viewing files at commit 5717cc9fc7edCommit detailsView latest

scripts/oakbench/rows.py 439 lines · 16.0 KB · python
1
"""The row contract: canonical accessors and per-lane validation.
2
3
A Row is one JSONL object for one measured operation — the durable source of
4
truth (CONTEXT.md). This module is the single definition of how consumers read
5
the best-available token/tool/output values from any lane's rows, and of what
6
every lane's emitter must include. ResultsStore validates at write time, so a
7
contract violation fails the producing run instead of corrupting a dashboard.
8
9
Null means unmeasured (ADR-0002): validation checks presence and types, and
10
treats null as a legitimate value wherever a signal is probe-dependent.
11
"""
12
13
from __future__ import annotations
14
15
import math
16
from typing import Any, Optional
17
18
LANES = ("core", "workflow", "agent", "contention", "mount", "task-loop", "platform", "robustness")
19
20
# Required top-level keys per lane. Deliberately the intersection that every
21
# row of the lane carries — including diagnostic rows (determinism probes,
22
# skip rows), which is why token fields are not required at this layer.
23
LANE_REQUIRED_KEYS: dict[str, tuple[str, ...]] = {
24
    "core": (
25
        "bench_id",
26
        "profile",
27
        "scenario",
28
        "operation",
29
        "run",
30
        "subject",
31
        "subject_kind",
32
        "elapsed_ms",
33
        "returncode",
34
        "command",
35
    ),
36
    "workflow": (
37
        "bench_id",
38
        "profile",
39
        "scenario",
40
        "workflow",
41
        "phase",
42
        "operation",
43
        "run",
44
        "subject",
45
        "subject_kind",
46
        "elapsed_ms",
47
        "returncode",
48
        "process_returncode",
49
        "command",
50
    ),
51
    "agent": (
52
        "schema_version",
53
        "bench_id",
54
        "scenario",
55
        "operation",
56
        "run",
57
        "subject",
58
        "subject_kind",
59
        "elapsed_ms",
60
        "returncode",
61
        "token_metrics",
62
        "turn_metrics",
63
        "tool_call_metrics",
64
    ),
65
    "contention": (
66
        "bench_id",
67
        "profile",
68
        "scenario",
69
        "contention_mode",
70
        "workers",
71
        "operation",
72
        "run",
73
        "subject",
74
        "subject_kind",
75
        "elapsed_ms",
76
        "returncode",
77
    ),
78
    "mount": (
79
        "bench_id",
80
        "profile",
81
        "scenario",
82
        "operation",
83
        "run",
84
        "subject",
85
        "elapsed_ms",
86
        "returncode",
87
    ),
88
    "task-loop": (
89
        "bench_id",
90
        "profile",
91
        "scenario",
92
        "operation",
93
        "run",
94
        "subject",
95
        "subject_kind",
96
        "elapsed_ms",
97
        "returncode",
98
        "command",
99
    ),
100
    # Platform lane: hosted-workflow rows are only comparable when both sides
101
    # ran the same semantics class under the same protection variant, so that
102
    # fairness context is part of every row — including skip rows. Runner
103
    # identity (ADR-0007) is required because this lane measures network
104
    # services from a specific vantage point.
105
    "platform": (
106
        "bench_id",
107
        "profile",
108
        "scenario",
109
        "operation",
110
        "run",
111
        "platform",
112
        "driver",
113
        "platform_semantics_version",
114
        "platform_semantics_class",
115
        "protection_variant",
116
        "platform_comparison_key",
117
        "semantic_contract_match",
118
        "elapsed_ms",
119
        "returncode",
120
        "command",
121
        "runner_id",
122
        "runner_class",
123
    ),
124
    # Robustness lane (suites/robustness): one row per fault case, judged by
125
    # independent readers. classification is held | violated | unsupported |
126
    # harness_error | fault_not_fired; unsupported and fault_not_fired cases are
127
    # skip rows (returncode 77). See ROBUSTNESS_CLASS_RETURNCODE.
128
    "robustness": (
129
        "bench_id",
130
        "scenario",
131
        "operation",
132
        "run",
133
        "subject",
134
        "subject_kind",
135
        "elapsed_ms",
136
        "returncode",
137
        "classification",
138
        "fault_family",
139
        "fault_point",
140
    ),
141
}
142
143
NUMERIC_KEYS = ("elapsed_ms",)
144
INTEGER_KEYS = ("returncode", "run")
145
SKIP_RETURNCODE = 77
146
147
# Optional metrics with constrained types/ranges when present. None is always
148
# legal (ADR-0002); a present value must be well-formed so consumers never
149
# need defensive parsing of the durable format.
150
OPTIONAL_NON_NEGATIVE_INT_KEYS = (
151
    "peak_rss_bytes",
152
    "tool_call_count",
153
    "probe_output_bytes",
154
    "changed_files_expected",
155
    "changed_files_recovered",
156
    "changed_files_reported",
157
    "changed_files_false_positive",
158
    "first_payload_bytes_server_to_client",
159
    "poll_iterations",
160
    "false_close_count",
161
    "close_eligible_n",
162
    "false_vcs_merge_safe_count",
163
    "vcs_merge_safe_n",
164
    "false_merge_allowed_count",
165
    "merge_allowed_n",
166
    "branches_scored",
167
    "branches_expected",
168
)
169
OPTIONAL_NON_NEGATIVE_NUMBER_KEYS = (
170
    "ttfd_ms",
171
    "observed_wait_ms",
172
    "settle_elapsed_ms",
173
    "poll_interval_s",
174
    "poll_quantization_ms",
175
    "status_post_elapsed_ms",
176
    "pacing_injected_ms",
177
)
178
OPTIONAL_UNIT_INTERVAL_KEYS = ("information_recall", "information_precision", "triage_recall", "triage_precision")
179
OPTIONAL_STRING_KEYS = (
180
    "runner_id",
181
    "runner_class",
182
    "fixture_id",
183
    "fixture_generator",
184
    "fixture_version",
185
    "fixture_seed",
186
    "fixture_manifest_sha256",
187
    "binary_sha256",
188
    "env_isolation_version",
189
    "platform_semantics_version",
190
    "platform_semantics_class",
191
    "protection_variant",
192
    "platform_comparison_key",
193
)
194
OPTIONAL_OBJECT_KEYS = ("runner_profile",)
195
196
197
class RowContractViolation(SystemExit):
198
    """Raised after rows are persisted; fails the producing run loudly."""
199
200
201
# Robustness lane: every classification and the returncode it must carry.
202
ROBUSTNESS_CLASS_RETURNCODE = {
203
    "held": 0,
204
    "violated": 1,
205
    "harness_error": 2,
206
    "unsupported": SKIP_RETURNCODE,
207
    "fault_not_fired": SKIP_RETURNCODE,
208
}
209
210
211
def _robustness_row_errors(index: int, row: dict[str, Any]) -> list[str]:
212
    op = row.get("operation", "?")
213
    classification = row.get("classification")
214
    if classification not in ROBUSTNESS_CLASS_RETURNCODE:
215
        return [f"row {index} ({op}): unknown robustness classification {classification!r}; "
216
                f"known: {', '.join(ROBUSTNESS_CLASS_RETURNCODE)}"]
217
    errors: list[str] = []
218
    expected = ROBUSTNESS_CLASS_RETURNCODE[classification]
219
    if row.get("returncode") != expected:
220
        errors.append(f"row {index} ({op}): classification {classification!r} requires returncode {expected}, "
221
                      f"got {row.get('returncode')!r}")
222
    if classification in ("held", "violated") and row.get("fault_fired") is False:
223
        errors.append(f"row {index} ({op}): a case whose fault did not fire cannot be {classification!r} "
224
                      "(use fault_not_fired)")
225
    violations = row.get("violations")
226
    if classification == "held" and violations:
227
        errors.append(f"row {index} ({op}): held row lists violations {violations!r}")
228
    if classification == "violated" and "violations" in row and not violations:
229
        errors.append(f"row {index} ({op}): violated row lists no violations")
230
    return errors
231
232
233
def validate_rows(rows: list[dict[str, Any]], lane: str) -> list[str]:
234
    if lane not in LANE_REQUIRED_KEYS:
235
        return [f"unknown lane {lane!r}; known: {', '.join(LANES)}"]
236
    required = LANE_REQUIRED_KEYS[lane]
237
    errors: list[str] = []
238
    for index, row in enumerate(rows, 1):
239
        if not isinstance(row, dict):
240
            errors.append(f"row {index}: expected object, got {type(row).__name__}")
241
            continue
242
        for key in required:
243
            if key not in row:
244
                errors.append(f"row {index} ({row.get('operation', '?')}): missing required key {key!r}")
245
        for key in NUMERIC_KEYS:
246
            value = row.get(key)
247
            diagnostic_timing = (lane == "core" and key == "elapsed_ms" and value is None
248
                and row.get("measurement_phase") == "output_diagnostic"
249
                and row.get("operation") in {
250
                    f"{operation}.{probe}" for operation in ("status.clean", "status.dirty", "diff.dirty", "diff.full")
251
                    for probe in ("inforecall", "determinism")})
252
            if diagnostic_timing:
253
                continue
254
            if key in row and (
255
                isinstance(value, bool)
256
                or not isinstance(value, (int, float))
257
                or not math.isfinite(float(value))
258
                or float(value) < 0
259
            ):
260
                errors.append(f"row {index}: {key} must be numeric, got {type(value).__name__}")
261
        for key in INTEGER_KEYS:
262
            value = row.get(key)
263
            if key in row and (isinstance(value, bool) or not isinstance(value, int)):
264
                errors.append(f"row {index}: {key} must be an integer, got {type(value).__name__}")
265
        for key in OPTIONAL_NON_NEGATIVE_INT_KEYS:
266
            value = row.get(key)
267
            if key in row and value is not None:
268
                if isinstance(value, bool) or not isinstance(value, int) or value < 0:
269
                    errors.append(f"row {index}: {key} must be a non-negative integer or null, got {value!r}")
270
        for key in OPTIONAL_NON_NEGATIVE_NUMBER_KEYS:
271
            value = row.get(key)
272
            if key in row and value is not None:
273
                if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
274
                    errors.append(f"row {index}: {key} must be a non-negative finite number or null, got {value!r}")
275
        for key in OPTIONAL_UNIT_INTERVAL_KEYS:
276
            value = row.get(key)
277
            if key in row and value is not None:
278
                if not isinstance(value, (int, float)) or isinstance(value, bool) or not 0.0 <= float(value) <= 1.0:
279
                    errors.append(f"row {index}: {key} must be in [0, 1] or null, got {value!r}")
280
        for key in OPTIONAL_STRING_KEYS:
281
            value = row.get(key)
282
            if key in row and value is not None and not isinstance(value, str):
283
                errors.append(f"row {index}: {key} must be a string or null, got {type(value).__name__}")
284
        for key in OPTIONAL_OBJECT_KEYS:
285
            value = row.get(key)
286
            if key in row and value is not None and not isinstance(value, dict):
287
                errors.append(f"row {index}: {key} must be an object or null, got {type(value).__name__}")
288
        # Skip-row coherence: a skip is a recorded coverage gap, and consumers
289
        # key off both signals. Half-marked skips silently become failures
290
        # (or worse, successes) downstream.
291
        returncode = row.get("returncode")
292
        if returncode == SKIP_RETURNCODE:
293
            if not row.get("skipped"):
294
                errors.append(f"row {index} ({row.get('operation', '?')}): returncode 77 requires skipped: true")
295
            if not str(row.get("skip_reason") or "").strip():
296
                errors.append(f"row {index} ({row.get('operation', '?')}): skip rows require a non-empty skip_reason")
297
        elif row.get("skipped"):
298
            errors.append(
299
                f"row {index} ({row.get('operation', '?')}): skipped: true requires returncode {SKIP_RETURNCODE}"
300
            )
301
        if lane == "robustness":
302
            errors.extend(_robustness_row_errors(index, row))
303
    return errors
304
305
306
def number_or_none(value: Any) -> Optional[float]:
307
    if value is None or isinstance(value, bool):
308
        return None
309
    try:
310
        parsed = float(value)
311
    except (TypeError, ValueError):
312
        return None
313
    if not math.isfinite(parsed):
314
        return None
315
    return parsed
316
317
318
def row_returncode(row: dict[str, Any]) -> int:
319
    """Row returncode with missing/null treated as failure, never a crash."""
320
    value = row.get("returncode")
321
    if value is None:
322
        return 1
323
    try:
324
        return int(value)
325
    except (TypeError, ValueError):
326
        return 1
327
328
329
def transcript_metrics_complete(row: dict[str, Any]) -> bool:
330
    source = row.get("source")
331
    execution = source.get("agent_execution") if isinstance(source, dict) else None
332
    is_agent = isinstance(row.get("agent"), dict) or str(row.get("operation", "")).startswith("agent.") or isinstance(execution, dict)
333
    return not ((is_agent and row.get("output_truncated") is True) or (isinstance(execution, dict) and
334
        (execution.get("usage_complete") is False or execution.get("transcript_metrics_complete") is False)))
335
336
337
def token_total(row: dict[str, Any]) -> Optional[float]:
338
    """Best-available token total for a row, preferring provider-reported usage."""
339
    if not transcript_metrics_complete(row):
340
        return None
341
    token_metrics = row.get("token_metrics")
342
    if isinstance(token_metrics, dict):
343
        value = number_or_none(token_metrics.get("total_tokens_reported"))
344
        if value is not None:
345
            return value
346
        reported_parts = [
347
            number_or_none(token_metrics.get("input_tokens_reported")),
348
            number_or_none(token_metrics.get("output_tokens_reported")),
349
            number_or_none(token_metrics.get("reasoning_tokens_reported")),
350
        ]
351
        if any(part is not None for part in reported_parts):
352
            return sum(part or 0.0 for part in reported_parts)
353
354
    for key in ("estimated_tokens_total", "token_count", "total_tokens"):
355
        value = number_or_none(row.get(key))
356
        if value is not None:
357
            return value
358
359
    token_estimate = row.get("token_estimate")
360
    if isinstance(token_estimate, dict):
361
        value = number_or_none(token_estimate.get("total"))
362
        if value is not None:
363
            return value
364
365
    tokens = row.get("tokens")
366
    if isinstance(tokens, dict):
367
        for key in ("total", "total_tokens", "provider_total", "estimated_total"):
368
            value = number_or_none(tokens.get(key))
369
            if value is not None:
370
                return value
371
        provider = tokens.get("provider_reported")
372
        if isinstance(provider, dict):
373
            value = number_or_none(provider.get("total"))
374
            if value is not None:
375
                return value
376
377
    if isinstance(token_metrics, dict):
378
        chars = number_or_none(token_metrics.get("transcript_chars"))
379
        if chars is None:
380
            input_chars = number_or_none(token_metrics.get("normalized_input_chars"))
381
            output_chars = number_or_none(token_metrics.get("normalized_output_chars"))
382
            if input_chars is not None or output_chars is not None:
383
                chars = (input_chars or 0.0) + (output_chars or 0.0)
384
        if chars is not None:
385
            return max(1.0, math.ceil(chars / 4.0))
386
    return None
387
388
389
def tool_calls(row: dict[str, Any]) -> Optional[float]:
390
    if not transcript_metrics_complete(row):
391
        return None
392
    for key in ("tool_call_count", "total_tool_calls"):
393
        value = number_or_none(row.get(key))
394
        if value is not None:
395
            return value
396
397
    nested = row.get("tool_calls")
398
    if isinstance(nested, dict):
399
        for key in ("total", "all"):
400
            value = number_or_none(nested.get(key))
401
            if value is not None:
402
                return value
403
404
    tool_call_metrics = row.get("tool_call_metrics")
405
    if isinstance(tool_call_metrics, dict):
406
        value = number_or_none(tool_call_metrics.get("tool_calls_total"))
407
        if value is not None:
408
            return value
409
    return None
410
411
412
def output_bytes(row: dict[str, Any]) -> Optional[float]:
413
    value = number_or_none(row.get("raw_output_bytes"))
414
    if value is not None:
415
        return value
416
417
    stdout = number_or_none(row.get("stdout_bytes"))
418
    stderr = number_or_none(row.get("stderr_bytes"))
419
    if stdout is not None or stderr is not None:
420
        return (stdout or 0.0) + (stderr or 0.0)
421
422
    token_estimate = row.get("token_estimate")
423
    if isinstance(token_estimate, dict):
424
        stdout = number_or_none(token_estimate.get("stdout_bytes"))
425
        stderr = number_or_none(token_estimate.get("stderr_bytes"))
426
        if stdout is not None or stderr is not None:
427
            return (stdout or 0.0) + (stderr or 0.0)
428
    return None
429
430
431
def output_truncated(row: dict[str, Any]) -> bool:
432
    if bool(row.get("output_truncated")):
433
        return True
434
    if bool(row.get("stdout_truncated")) or bool(row.get("stderr_truncated")):
435
        return True
436
    token_estimate = row.get("token_estimate")
437
    if isinstance(token_estimate, dict):
438
        return bool(token_estimate.get("stdout_truncated")) or bool(token_estimate.get("stderr_truncated"))
439
    return False