Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

scripts/parallel_contention.py in oak/benchmarks

scripts/parallel_contention.py 2673 lines · 115.5 KB · python
1
#!/usr/bin/env python3
2
"""Measure VCS behavior under N concurrent agents.
3
4
This is the contention lane the parallel-agents thesis needs evidence from.
5
N workers concurrently edit disjoint files and snapshot in a loop, against:
6
7
- shared_checkout: every worker commits in the same checkout. Measures lock
8
  contention (git index.lock and Oak's equivalent), commit serialization
9
  throughput, and lost updates.
10
- workspace_per_task: one isolated workspace per worker on its own branch,
11
  plus a merge phase. Git: worktrees (local disk) merged locally. Oak: one
12
  `oak mount` per worker against the disposable fleet remote (set
13
  OAK_BENCH_FLEET_REPO), each on its auto-created virtual branch, pushed and
14
  merged back into main via an integrator clone. Measures isolation cost,
15
  time-to-Nth-workspace, marginal disk per workspace (visible vs allocated),
16
  and merge throughput. TRANSPORT ASYMMETRY: oak workspaces cross the network,
17
  git worktrees do not; rows carry workspace_transport and reports must state
18
  the asymmetry, never delta across it.
19
20
After the storm, an integrity pass runs: git fsck (or the closest Oak sanity
21
check) plus payload survival — every payload whose snapshot reported success
22
must be intact in the final tree. A "fast" VCS that loses updates under
23
contention is worse than a slow one; this lane makes that visible.
24
25
Fleet-scale modes (additive; existing modes unchanged, ADR-0005):
26
27
- merge_train: N branches built concurrently, landed serially through merge.
28
  Rows record per-worker queue_wait_ms (land requested -> merge started),
29
  merge_ms, and total merges/min.
30
- rebase_storm: workers rebase onto a moving main and race to push; rows
31
  record the attempts-to-land distribution.
32
- mixed_fleet: readers poll status/log on an interval while writers commit;
33
  reader rows carry raw poll-latency samples (zero-thrash evidence).
34
- conflict_storm: workers append sentinels to OVERLAPPING files; after the
35
  storm every sentinel must survive in HEAD — a missing sentinel is a
36
  recorded lost update.
37
- clone_push_storm: N concurrent clone -> commit -> push cycles against one
38
  remote (server write-path stress).
39
- long_divergence: one branch accumulates K commits then merges; scenario
40
  contention_long_divergence_k<K> (K from --divergence-k, not the tier loop).
41
- integration_landing: N careful agents (integrate main, test, land only if
42
  green) land at once, with a designed semantic conflict and a same-line text
43
  conflict (oakbench.landing). The oracle is a fresh clone of main: tests
44
  green, every landed change present, conflicts surfaced not landed. Oak runs
45
  against a private `oak serve` on loopback (no CI gate), git a local bare
46
  remote; compare outcomes, never latency.
47
48
Worker tiers come from --workers (any CSV; fleet campaigns use 16,32,64,128).
49
Completed rows are flushed incrementally to <results>/<ts>.partial.jsonl
50
(ResultsStore flush_partial) so a long campaign killed mid-run keeps its rows;
51
the canonical file finalizes the partial at completion.
52
53
Rows are bench.py-style JSONL plus real parallel metrics: lock_wait_ms,
54
commit_throughput_per_s, lost_updates_detected, integrity_check_passed,
55
workspace disk and inode counts. Unmeasurable values are null, never zero.
56
57
Examples:
58
59
    python3 scripts/parallel_contention.py --subjects git,oak_installed
60
    python3 scripts/parallel_contention.py --subjects git --workers 2,8,32 \
61
        --commits-per-worker 5 --modes shared_checkout,workspace_per_task
62
"""
63
64
from __future__ import annotations
65
66
import argparse
67
import platform
68
import re
69
import shutil
70
import socket
71
import subprocess
72
import tempfile
73
import threading
74
import time
75
from dataclasses import dataclass, field
76
from datetime import datetime, timezone
77
from pathlib import Path
78
from typing import Any
79
80
from oakbench import landing
81
from oakbench.command_semantics import semantics
82
from oakbench.diskprobe import bounded_tree_usage
83
from oakbench.environment import ENV_ISOLATION_VERSION, base_env
84
from oakbench.remotes import (
85
    RemoteRequirement,
86
    attach_git_origin,
87
    disposable_branch,
88
    make_git_bare_remote,
89
    oak_remote_preflight_warnings,
90
    point_git_bare_head,
91
    print_remote_preflight_warnings,
92
    resolve_git_github_remote,
93
    resolve_oak_remote,
94
)
95
from oakbench.reporting import tail_latency_summary
96
from oakbench.results import ResultsStore
97
from oakbench.rows import row_returncode
98
from oakbench.runlock import measurement_lock
99
from oakbench.subjects import (
100
    DEFAULT_OAK_REPO,
101
    Subject,
102
    load_subjects,
103
    source_metadata,
104
    subject_details,
105
    subject_versions,
106
)
107
108
ROOT = Path(__file__).resolve().parents[1]
109
DEFAULT_WORKDIR = Path(tempfile.gettempdir()) / "oak-parallel-contention"
110
# Fleet-scale modes are additive (ADR-0005): the two original modes keep their
111
# exact semantics and row shapes; new modes get new scenario names.
112
FLEET_MODES = (
113
    "merge_train", "rebase_storm", "mixed_fleet", "conflict_storm", "clone_push_storm", "integration_landing",
114
)
115
MODES = ("shared_checkout", "workspace_per_task", *FLEET_MODES, "long_divergence")
116
SKIP_RETURNCODE = 77
117
MAX_SNAPSHOT_ATTEMPTS = 8
118
MAX_LAND_ATTEMPTS = 16
119
RETRY_SLEEP_S = 0.02
120
READER_POLL_INTERVAL_S = 0.05
121
CONFLICT_STORM_FILES = 3
122
LONG_DIVERGENCE_MAIN_COMMITS = 5
123
LOCK_HINT_PATTERN = ("index.lock", "another git process", "lock", "Resource temporarily unavailable")
124
125
126
@dataclass
127
class WorkerResult:
128
    worker: int
129
    elapsed_ms: float = 0.0
130
    commits_attempted: int = 0
131
    commits_succeeded: int = 0
132
    # Payloads recorded by ANOTHER worker's `git add .` sweep ("nothing to
133
    # commit" on our own attempt). The payload survived, but this worker
134
    # performed no snapshot — throughput must distinguish the two.
135
    commits_swept: int = 0
136
    retries: int = 0
137
    lock_failures: int = 0
138
    lock_wait_ms: float = 0.0
139
    # Per-commit end-to-end latency (including retries and backoff sleeps)
140
    # and the attempt count each successful commit needed. Retained raw so
141
    # tail percentiles and retry-depth histograms come from samples, not from
142
    # already-aggregated means.
143
    commit_latency_ms: list[float] = field(default_factory=list)
144
    attempts_to_commit: list[int] = field(default_factory=list)
145
    failed_payloads: list[str] = field(default_factory=list)
146
    succeeded_payloads: list[tuple[str, str]] = field(default_factory=list)
147
    errors: list[str] = field(default_factory=list)
148
    failure_contexts: list[dict[str, Any]] = field(default_factory=list)
149
150
151
def parse_args() -> argparse.Namespace:
152
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
153
    parser.add_argument("--subjects", help="Comma-separated subject names from config/subjects.toml")
154
    parser.add_argument("--config", type=Path, default=ROOT / "config" / "subjects.toml")
155
    parser.add_argument("--git-bin", type=Path)
156
    parser.add_argument("--oak-installed-bin", type=Path)
157
    parser.add_argument("--oak-local-bin", type=Path)
158
    parser.add_argument("--oak-aa-bin", type=Path, help="A/A control: the baseline Oak binary under subject oak_installed_aa.")
159
    parser.add_argument(
160
        "--workers",
161
        default="2,8",
162
        help="Comma-separated concurrency levels (any CSV; fleet tiers: 16,32,64,128).",
163
    )
164
    parser.add_argument("--commits-per-worker", type=int, default=5)
165
    parser.add_argument("--modes", default="shared_checkout,workspace_per_task")
166
    parser.add_argument(
167
        "--divergence-k",
168
        default="10,100",
169
        help=(
170
            "Comma-separated divergence depths for the long_divergence mode "
171
            "(scenario contention_long_divergence_k<K>, ADR-0005). Canonical "
172
            "tiers: 10,100,1000; 1000 is accepted but expensive."
173
        ),
174
    )
175
    parser.add_argument("--runs", type=int, default=1)
176
    parser.add_argument("--workdir", type=Path, default=DEFAULT_WORKDIR)
177
    parser.add_argument("--results", type=Path, default=ROOT / "results" / "parallel-contention")
178
    parser.add_argument(
179
        "--oak-repo",
180
        type=Path,
181
        default=DEFAULT_OAK_REPO,
182
        help="Optional Oak source checkout for provenance metadata.",
183
    )
184
    parser.add_argument("--keep-workdirs", action="store_true")
185
    return parser.parse_args()
186
187
188
def run(command: list[str], cwd: Path, timeout: float = 120.0) -> subprocess.CompletedProcess[str]:
189
    # A step exceeding its timeout is a (terrible) measurement, not a harness
190
    # crash: convert to a synthetic failed process so the row records it and
191
    # the campaign survives. Killing the whole run an hour in loses every row
192
    # (rows flush only at write time).
193
    try:
194
        return subprocess.run(
195
            command,
196
            cwd=cwd,
197
            env=base_env(),
198
            text=True,
199
            stdout=subprocess.PIPE,
200
            stderr=subprocess.PIPE,
201
            timeout=timeout,
202
            check=False,
203
        )
204
    except subprocess.TimeoutExpired as exc:
205
        stdout = exc.stdout.decode("utf-8", "replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
206
        stderr = exc.stderr.decode("utf-8", "replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
207
        return subprocess.CompletedProcess(
208
            command, 124, stdout, stderr + f"\n[harness] step timed out after {timeout:.0f}s"
209
        )
210
211
212
def make_fixture(path: Path) -> None:
213
    if path.exists():
214
        shutil.rmtree(path)
215
    (path / "src").mkdir(parents=True)
216
    for index in range(100):
217
        (path / "src" / f"module-{index:03d}.txt").write_text(f"module {index}\n" * 8)
218
    (path / "README.md").write_text("Parallel contention fixture.\n")
219
220
221
def init_repo(subject: Subject, repo: Path) -> bool:
222
    vcs = str(subject.bin)
223
    if subject.kind == "git":
224
        commands = [
225
            [vcs, "init", "-b", "main"],
226
            [vcs, "add", "."],
227
            [vcs, "commit", "-m", "initial"],
228
        ]
229
    else:
230
        commands = [[vcs, "init", "."], [vcs, "commit", "--no-verify"]]
231
    for command in commands:
232
        if run(command, repo).returncode != 0:
233
            return False
234
    return True
235
236
237
def snapshot_commands(subject: Subject, message: str) -> list[list[str]]:
238
    return semantics().snapshot_commands(str(subject.bin), subject.kind, message)
239
240
241
def looks_like_lock_failure(stderr: str) -> bool:
242
    lowered = stderr.lower()
243
    return any(hint.lower() in lowered for hint in LOCK_HINT_PATTERN)
244
245
246
def excerpt(text: str, limit: int = 400) -> str:
247
    return text.strip()[:limit]
248
249
250
def record_worker_failure(
251
    result: WorkerResult,
252
    reason: str,
253
    *,
254
    command: list[str] | None = None,
255
    proc: subprocess.CompletedProcess[str] | None = None,
256
    workspace: Path | None = None,
257
    affected_path: str | None = None,
258
) -> None:
259
    if len(result.failure_contexts) < 5:
260
        context: dict[str, Any] = {
261
            "worker": result.worker,
262
            "failure_reason": reason,
263
        }
264
        if command is not None:
265
            context["command"] = command
266
        if proc is not None:
267
            context["returncode"] = proc.returncode
268
            context["stdout_excerpt"] = excerpt(proc.stdout)
269
            context["stderr_excerpt"] = excerpt(proc.stderr)
270
        if workspace is not None:
271
            context["workspace"] = str(workspace)
272
        if affected_path is not None:
273
            context["affected_path"] = affected_path
274
        result.failure_contexts.append(context)
275
276
    message = reason
277
    if proc is not None:
278
        detail = excerpt(proc.stderr) or excerpt(proc.stdout)
279
        if detail:
280
            message = f"{reason}: {detail}"
281
    if len(result.errors) < 5 and message not in result.errors:
282
        result.errors.append(message[:200])
283
284
285
TERMINAL_WORKER_FAILURE_REASONS = {
286
    "snapshot_attempts_exhausted",
287
    "workspace_push_failed",
288
    "workspace_switch_failed",
289
    "workspace_merge_failed",
290
    "worktree_merge_failed",
291
    "train_merge_failed",
292
}
293
294
295
def worker_result_failed(result: WorkerResult) -> bool:
296
    if result.commits_succeeded != result.commits_attempted or result.failed_payloads:
297
        return True
298
    for context in result.failure_contexts:
299
        reason = str(context.get("failure_reason") or "")
300
        if reason in TERMINAL_WORKER_FAILURE_REASONS or reason.startswith("worker_exception:"):
301
            return True
302
    return False
303
304
305
def any_worker_result_failed(results: list[WorkerResult]) -> bool:
306
    return any(worker_result_failed(result) for result in results)
307
308
309
def worker_failure_fields(result: WorkerResult, workspace: Path | None = None) -> dict[str, Any]:
310
    fields: dict[str, Any] = {
311
        "worker_id": result.worker,
312
        "error_examples": result.errors,
313
        "failure_contexts": result.failure_contexts,
314
        "failed_payloads": result.failed_payloads,
315
    }
316
    if worker_result_failed(result):
317
        first = result.failure_contexts[0] if result.failure_contexts else {}
318
        reason = str(first.get("failure_reason") or "worker_incomplete")
319
        fields["failure_reason"] = reason
320
        if workspace is not None:
321
            fields["worker_workspace"] = str(workspace)
322
        if result.failed_payloads:
323
            fields["affected_paths"] = result.failed_payloads
324
        if "command" in first:
325
            fields["command"] = first["command"]
326
        stderr = str(first.get("stderr_excerpt") or "")
327
        stdout = str(first.get("stdout_excerpt") or "")
328
        fields["stderr"] = stderr
329
        fields["stdout"] = stdout
330
    return fields
331
332
333
def aggregate_worker_failure_fields(
334
    results: list[WorkerResult],
335
    *,
336
    workspace: Path | None = None,
337
) -> dict[str, Any]:
338
    contexts = [context for result in results for context in result.failure_contexts]
339
    failed_payloads = [path for result in results for path in result.failed_payloads]
340
    fields: dict[str, Any] = {
341
        "worker_failure_contexts": contexts[:10],
342
        "failed_payloads": failed_payloads,
343
    }
344
    if contexts or failed_payloads:
345
        first = contexts[0] if contexts else {}
346
        fields["failure_reason"] = str(first.get("failure_reason") or "worker_incomplete")
347
        if workspace is not None:
348
            fields["worker_workspace"] = str(workspace)
349
        fields["stderr"] = str(first.get("stderr_excerpt") or "")
350
        fields["stdout"] = str(first.get("stdout_excerpt") or "")
351
        if "command" in first:
352
            fields["command"] = first["command"]
353
    return fields
354
355
356
def worker_loop(
357
    subject: Subject,
358
    workspace: Path,
359
    worker_index: int,
360
    commits: int,
361
    result: WorkerResult,
362
    rel_prefix: str = "workers",
363
) -> None:
364
    # Exceptions must not escape the thread: a silently dead worker would leave
365
    # partially-zero metrics that look like a fast clean run.
366
    start = time.perf_counter()
367
    try:
368
        _worker_loop_inner(subject, workspace, worker_index, commits, result, rel_prefix)
369
    except Exception as exc:  # noqa: BLE001 - recorded, not hidden
370
        record_worker_failure(result, f"worker_exception:{type(exc).__name__}", workspace=workspace)
371
        if result.failure_contexts:
372
            result.failure_contexts[-1]["exception"] = str(exc)[:400]
373
    finally:
374
        result.elapsed_ms = (time.perf_counter() - start) * 1000
375
376
377
def _worker_loop_inner(
378
    subject: Subject,
379
    workspace: Path,
380
    worker_index: int,
381
    commits: int,
382
    result: WorkerResult,
383
    rel_prefix: str = "workers",
384
) -> None:
385
    for k in range(commits):
386
        rel_path = f"{rel_prefix}/w{worker_index:03d}/f{k:03d}.txt"
387
        payload = f"payload worker={worker_index} commit={k} nonce={worker_index * 100003 + k}\n"
388
        target = workspace / rel_path
389
        target.parent.mkdir(parents=True, exist_ok=True)
390
        target.write_text(payload)
391
        result.commits_attempted += 1
392
393
        committed = False
394
        swept = False
395
        commit_start = time.perf_counter()
396
        for attempt in range(MAX_SNAPSHOT_ATTEMPTS):
397
            attempt_start = time.perf_counter()
398
            failed = False
399
            stderr_text = ""
400
            last_command: list[str] | None = None
401
            last_proc: subprocess.CompletedProcess[str] | None = None
402
            for command in snapshot_commands(subject, f"w{worker_index} k{k}"):
403
                last_command = command
404
                proc = run(command, workspace)
405
                last_proc = proc
406
                stderr_text = proc.stderr
407
                if proc.returncode != 0:
408
                    # Concurrent `git add .` can commit this worker's file from
409
                    # another worker's snapshot; "nothing to commit" then means
410
                    # the change is already recorded — but by someone else.
411
                    # Payload survival: yes. Snapshot performed by this
412
                    # worker: no. Count it as swept, never as a snapshot.
413
                    if subject.kind == "git" and "nothing to commit" in (proc.stdout + proc.stderr):
414
                        swept = True
415
                        break
416
                    failed = True
417
                    if not looks_like_lock_failure(proc.stderr):
418
                        record_worker_failure(
419
                            result,
420
                            "snapshot_command_failed",
421
                            command=command,
422
                            proc=proc,
423
                            workspace=workspace,
424
                            affected_path=rel_path,
425
                        )
426
                    break
427
            attempt_ms = (time.perf_counter() - attempt_start) * 1000
428
            if not failed:
429
                committed = True
430
                break
431
            result.retries += 1
432
            result.lock_wait_ms += attempt_ms + RETRY_SLEEP_S * 1000
433
            if looks_like_lock_failure(stderr_text):
434
                result.lock_failures += 1
435
            elif len(result.errors) < 5:
436
                result.errors.append(stderr_text.strip()[:200])
437
            time.sleep(RETRY_SLEEP_S)
438
        if committed:
439
            result.commits_succeeded += 1
440
            result.succeeded_payloads.append((rel_path, payload))
441
            if swept:
442
                result.commits_swept += 1
443
            else:
444
                # Latency/attempt samples describe snapshots this worker
445
                # actually performed; a swept "success" took no commit.
446
                result.commit_latency_ms.append(round((time.perf_counter() - commit_start) * 1000, 3))
447
                result.attempts_to_commit.append(attempt + 1)
448
        else:
449
            if not result.failure_contexts or result.failure_contexts[-1].get("affected_path") != rel_path:
450
                record_worker_failure(
451
                    result,
452
                    "snapshot_attempts_exhausted",
453
                    command=last_command,
454
                    proc=last_proc,
455
                    workspace=workspace,
456
                    affected_path=rel_path,
457
                )
458
            result.failed_payloads.append(rel_path)
459
460
461
class CommittedStateUnmeasured(Exception):
462
    """The independent reader could not measure Oak's committed state."""
463
464
465
def unmeasured_returncode(integrity_passed: bool | None, measured_returncode: int) -> int:
466
    """77 (skip, unmeasured) when the integrity oracle could not run; never a pass."""
467
    return 77 if integrity_passed is None else measured_returncode
468
469
470
def tree_payload(subject: Subject, repo: Path, rel_path: str) -> str | None:
471
    if subject.kind == "git":
472
        proc = run([str(subject.bin), "show", f"HEAD:{rel_path}"], repo)
473
        return proc.stdout if proc.returncode == 0 else None
474
    if subject.kind == "oak":
475
        # Committed HEAD through the independent reader, never the worktree.
476
        from oakbench import oak_sqlite_reader as reader
477
        try:
478
            payloads, _ = reader.committed_payloads(repo, [rel_path])
479
        except reader.Invalid:
480
            return None
481
        except (reader.Unavailable, OSError, ValueError) as exc:
482
            # Never fall back to the worktree: the check is unmeasured.
483
            raise CommittedStateUnmeasured(f"independent_oak_reader_unavailable:{exc}") from exc
484
        data = payloads.get(rel_path)
485
        return data.decode("utf-8", "replace") if data is not None else None
486
    return _worktree_payload(repo, rel_path)
487
488
489
def _worktree_payload(repo: Path, rel_path: str) -> str | None:
490
    try:
491
        return (repo / rel_path).read_text()
492
    except OSError:
493
        return None
494
495
496
def oak_committed_integrity(repo: Path) -> tuple[bool | None, str]:
497
    """Deep independent read: every committed object and ancestor re-hashed."""
498
    from oakbench import oak_sqlite_reader as reader
499
    try:
500
        reader.read_committed_tree(repo, None, deep=True)
501
        return True, "independent_oak_reader_deep_verify"
502
    except reader.Invalid as exc:
503
        return False, f"independent_oak_reader_invalid:{exc}"
504
    except (reader.Unavailable, OSError, ValueError) as exc:
505
        return None, f"independent_oak_reader_unavailable:{exc}"
506
507
508
def integrity_check(
509
    subject: Subject,
510
    repo: Path,
511
    results: list[WorkerResult],
512
) -> tuple[bool | None, int | None, str]:
513
    """Returns (integrity_passed, lost_updates, method)."""
514
    # Sweep any straggler files into a final snapshot so HEAD reflects the run.
515
    for command in snapshot_commands(subject, "contention sweep"):
516
        run(command, repo)
517
518
    lost = 0
519
    try:
520
        for result in results:
521
            for rel_path, payload in result.succeeded_payloads:
522
                recorded = tree_payload(subject, repo, rel_path)
523
                if recorded is None or payload not in recorded:
524
                    lost += 1
525
    except CommittedStateUnmeasured as exc:
526
        return None, None, f"unmeasured:{exc}"
527
528
    if subject.kind == "git":
529
        fsck = run([str(subject.bin), "fsck", "--no-progress"], repo)
530
        passed = fsck.returncode == 0 and lost == 0
531
        return passed, lost, "git_fsck_plus_payload_survival"
532
    sanity = run([str(subject.bin), "log", "-n", "1"], repo)
533
    status = run([str(subject.bin), "status"], repo)
534
    passed = sanity.returncode == 0 and status.returncode == 0 and lost == 0
535
    if subject.kind == "oak":
536
        verified, how = oak_committed_integrity(repo)
537
        if verified is False:
538
            passed = False
539
        elif verified is None and passed:
540
            passed = None  # payloads read, but the full-store verify could not run
541
        return passed, lost, ("oak_log_status_sanity_plus_committed_payload_survival(independent_reader); "
542
                              + how)
543
    return passed, lost, "oak_log_status_sanity_plus_payload_survival; oak has no fsck equivalent yet"
544
545
546
def disk_usage(path: Path) -> tuple[int | None, int | None]:
547
    try:
548
        du = subprocess.run(["du", "-sk", str(path)], text=True, stdout=subprocess.PIPE, check=False)
549
        kb = int(du.stdout.split()[0]) if du.returncode == 0 and du.stdout.strip() else None
550
    except Exception:
551
        kb = None
552
    try:
553
        entries = sum(1 for _ in path.rglob("*"))
554
    except OSError:
555
        entries = None
556
    return kb, entries
557
558
559
def base_row(metadata: dict[str, Any], subject: Subject, mode: str, workers: int, run_index: int) -> dict[str, Any]:
560
    return {
561
        **metadata,
562
        "subject": subject.name,
563
        "subject_kind": subject.kind,
564
        "subject_label": subject.label,
565
        "scenario": f"contention_{mode}_w{workers}",
566
        "contention_mode": mode,
567
        "workers": workers,
568
        "run": run_index,
569
    }
570
571
572
def contention_payload_prefix(bench_id: str, subject_name: str, workers: int, run_index: int) -> str:
573
    """File namespace for payloads merged into a long-lived disposable repo."""
574
    return f"workers/{bench_id}/{subject_name}/w{workers}/r{run_index}"
575
576
577
def run_shared_checkout(
578
    subject: Subject,
579
    fixture: Path,
580
    workers: int,
581
    commits: int,
582
    run_root: Path,
583
    run_index: int,
584
    metadata: dict[str, Any],
585
) -> list[dict[str, Any]]:
586
    rows: list[dict[str, Any]] = []
587
    repo = run_root / f"shared-{subject.name}-w{workers}-r{run_index}"
588
    shutil.copytree(fixture, repo)
589
    if not init_repo(subject, repo):
590
        row = base_row(metadata, subject, "shared_checkout", workers, run_index)
591
        row.update({"operation": "parallel.total", "elapsed_ms": 0.0, "returncode": 1, "stderr": "repo init failed"})
592
        return [row]
593
594
    results = [WorkerResult(worker=index) for index in range(workers)]
595
    threads = [
596
        threading.Thread(target=worker_loop, args=(subject, repo, index, commits, results[index]))
597
        for index in range(workers)
598
    ]
599
    wall_start = time.perf_counter()
600
    for thread in threads:
601
        thread.start()
602
    for thread in threads:
603
        thread.join()
604
    wall_ms = (time.perf_counter() - wall_start) * 1000
605
606
    for result in results:
607
        row = base_row(metadata, subject, "shared_checkout", workers, run_index)
608
        row.update(
609
            {
610
                "operation": "parallel.worker",
611
                "worker": result.worker,
612
                "elapsed_ms": round(result.elapsed_ms, 3),
613
                "returncode": 1 if worker_result_failed(result) else 0,
614
                "commits_attempted": result.commits_attempted,
615
                "commits_succeeded": result.commits_succeeded,
616
                "commits_swept": result.commits_swept,
617
                "snapshots_performed": result.commits_succeeded - result.commits_swept,
618
                "retries": result.retries,
619
                "lock_failures": result.lock_failures,
620
                "lock_wait_ms": round(result.lock_wait_ms, 3),
621
                "commit_latency_samples_ms": result.commit_latency_ms,
622
                "attempts_to_commit": result.attempts_to_commit,
623
                **worker_failure_fields(result, repo),
624
            }
625
        )
626
        rows.append(row)
627
628
    integrity_passed, lost_updates, method = integrity_check(subject, repo, results)
629
    disk_kb, entries = disk_usage(repo)
630
    total_succeeded = sum(result.commits_succeeded for result in results)
631
    total_attempted = sum(result.commits_attempted for result in results)
632
    all_latencies = [sample for result in results for sample in result.commit_latency_ms]
633
    retry_depth_histogram: dict[str, int] = {}
634
    for result in results:
635
        for attempts in result.attempts_to_commit:
636
            key = str(attempts)
637
            retry_depth_histogram[key] = retry_depth_histogram.get(key, 0) + 1
638
    row = base_row(metadata, subject, "shared_checkout", workers, run_index)
639
    row.update(
640
        {
641
            "operation": "parallel.total",
642
            "elapsed_ms": round(wall_ms, 3),
643
            "returncode": unmeasured_returncode(integrity_passed, 0 if integrity_passed and total_succeeded == total_attempted and not any_worker_result_failed(results) else 1),
644
            "skip_reason": "oak_committed_state_unmeasured:independent_reader_unavailable" if integrity_passed is None else None,
645
            "parallel_metrics": {
646
                "tasks_total": total_attempted,
647
                "tasks_completed": total_succeeded,
648
                "max_parallel_tasks": workers,
649
                "overlapping_files_count": 0,
650
                "lost_updates_detected": lost_updates,
651
                "lock_wait_ms": round(sum(result.lock_wait_ms for result in results), 3),
652
                # commit_throughput_per_s is PAYLOAD throughput (its historical
653
                # meaning, ADR-0005): payloads safely recorded per second,
654
                # including those swept into another worker's snapshot.
655
                # snapshot_throughput_per_s counts only snapshots a worker
656
                # actually performed — the honest "snapshots/s" number.
657
                "commit_throughput_per_s": round(total_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
658
                "commits_swept_total": sum(result.commits_swept for result in results),
659
                "snapshot_throughput_per_s": (
660
                    round(
661
                        sum(result.commits_succeeded - result.commits_swept for result in results)
662
                        / (wall_ms / 1000.0),
663
                        3,
664
                    )
665
                    if wall_ms
666
                    else None
667
                ),
668
                "integrity_check_passed": integrity_passed,
669
                # Tail of per-commit latency under contention: an agent fleet
670
                # feels the p99 commit (a stuck tool call), not the median.
671
                # Percentiles below their honest sample minimum are null.
672
                "commit_latency_tail": tail_latency_summary(all_latencies),
673
                # attempts -> commits that needed that many attempts; depth >1
674
                # is retry churn an agent pays as extra tool calls and waiting.
675
                "retry_depth_histogram": retry_depth_histogram,
676
                "measurement_source": method,
677
            },
678
            "retries_total": sum(result.retries for result in results),
679
            "lock_failures_total": sum(result.lock_failures for result in results),
680
            "workspace_disk_kb": disk_kb,
681
            "workspace_entries": entries,
682
        }
683
    )
684
    if row["returncode"] != 0:
685
        row.update(aggregate_worker_failure_fields(results, workspace=repo))
686
    rows.append(row)
687
    return rows
688
689
690
VIRTUAL_BRANCH_RE = re.compile(r"virtual branch ([^\s)]+)")
691
692
693
def oak_virtual_branch(subject: Subject, mount_dir: Path) -> str | None:
694
    proc = run([str(subject.bin), "status"], mount_dir)
695
    match = VIRTUAL_BRANCH_RE.search(proc.stdout + proc.stderr)
696
    return match.group(1) if match else None
697
698
699
def ensure_oak_fleet_seed(
700
    subject: Subject, fixture: Path, integrator: Path, remote_repo: str
701
) -> str | None:
702
    """Untimed: clone the disposable fleet repo and make sure main carries the
703
    contention fixture. Returns an error string on failure, None on success.
704
705
    Seeding is idempotent: identical fixture bytes produce a no-op commit on
706
    re-runs, and the disposable repo accumulates bench branches by design.
707
    """
708
    vcs = str(subject.bin)
709
    proc = run([vcs, "clone", remote_repo, str(integrator)], integrator.parent, timeout=300.0)
710
    if proc.returncode != 0:
711
        return f"oak clone failed: {proc.stderr.strip()[:200]}"
712
    marker = integrator / "CONTENTION_FIXTURE.md"
713
    if marker.exists():
714
        return None
715
    for source in fixture.rglob("*"):
716
        if not source.is_file():
717
            continue
718
        target = integrator / source.relative_to(fixture)
719
        target.parent.mkdir(parents=True, exist_ok=True)
720
        shutil.copy2(source, target)
721
    marker.write_text("Parallel contention fixture (seeded by parallel_contention.py).\n")
722
    for command in ([vcs, "commit", "--no-verify"], [vcs, "push"], [vcs, "merge"]):
723
        proc = run(command, integrator, timeout=300.0)
724
        if proc.returncode != 0:
725
            return f"fleet seed `{' '.join(command[1:])}` failed: {proc.stderr.strip()[:200]}"
726
    return None
727
728
729
def error_total_row(
730
    metadata: dict[str, Any],
731
    subject: Subject,
732
    workers: int,
733
    run_index: int,
734
    stderr: str,
735
    extra: dict[str, Any] | None = None,
736
) -> dict[str, Any]:
737
    row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
738
    row.update({"operation": "parallel.total", "elapsed_ms": 0.0, "returncode": 1, "stderr": stderr})
739
    if extra:
740
        row.update(extra)
741
    return row
742
743
744
def run_workspace_per_task_oak(
745
    subject: Subject,
746
    fixture: Path,
747
    workers: int,
748
    commits: int,
749
    run_root: Path,
750
    run_index: int,
751
    metadata: dict[str, Any],
752
) -> list[dict[str, Any]]:
753
    """N oak mounts against the disposable fleet remote — oak's worktree analog.
754
755
    Transport honesty: every mount, push, and merge here crosses the network
756
    to a real oak server, while the git comparator's worktrees are pure local
757
    disk. Rows carry workspace_transport/remote_* so reports state the
758
    asymmetry instead of burying it; deltas across transports are forbidden.
759
    """
760
    remote = resolve_oak_remote("fleet")
761
    if not remote.resolved:
762
        row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
763
        row.update(
764
            {
765
                "operation": "parallel.total",
766
                "elapsed_ms": 0.0,
767
                "returncode": SKIP_RETURNCODE,
768
                "skipped": True,
769
                "skip_reason": remote.skip_reason,
770
            }
771
        )
772
        return [row]
773
774
    vcs = str(subject.bin)
775
    bench_id = str(metadata.get("bench_id", "bench"))
776
    lane_root = run_root / f"wpt-{subject.name}-w{workers}-r{run_index}"
777
    lane_root.mkdir(parents=True, exist_ok=True)
778
    integrator = lane_root / "integrator"
779
    remote_fields = {**remote.row_fields(), "workspace_transport": remote.transport}
780
781
    mounts: list[Path] = []
782
    try:
783
        seed_error = ensure_oak_fleet_seed(subject, fixture, integrator, remote.repo)
784
        if seed_error:
785
            return [error_total_row(metadata, subject, workers, run_index, seed_error, remote_fields)]
786
787
        # Timed, sequential: workspace i usable = `oak mount` returned. The
788
        # cumulative curve is the fleet-spinup headline number.
789
        setup_samples: list[float] = []
790
        time_to_nth: list[float] = []
791
        branches: list[str] = []
792
        setup_start = time.perf_counter()
793
        for index in range(workers):
794
            mount_dir = lane_root / f"wt-{index:03d}"
795
            mount_start = time.perf_counter()
796
            proc = run([vcs, "mount", remote.repo, str(mount_dir)], lane_root, timeout=300.0)
797
            setup_samples.append(round((time.perf_counter() - mount_start) * 1000, 3))
798
            time_to_nth.append(round((time.perf_counter() - setup_start) * 1000, 3))
799
            if proc.returncode != 0:
800
                return [
801
                    error_total_row(
802
                        metadata,
803
                        subject,
804
                        workers,
805
                        run_index,
806
                        f"oak mount failed for workspace {index}: {proc.stderr.strip()[:200]}",
807
                        remote_fields,
808
                    )
809
                ]
810
            mounts.append(mount_dir)
811
        setup_ms = (time.perf_counter() - setup_start) * 1000
812
813
        # Untimed probe: each mount's auto-created virtual branch is the
814
        # workspace branch the merge phase folds back into main.
815
        for mount_dir in mounts:
816
            branch = oak_virtual_branch(subject, mount_dir)
817
            if branch is None:
818
                return [
819
                    error_total_row(
820
                        metadata,
821
                        subject,
822
                        workers,
823
                        run_index,
824
                        f"could not parse virtual branch for {mount_dir.name}",
825
                        remote_fields,
826
                    )
827
                ]
828
            branches.append(branch)
829
830
        # Payload paths carry the bench id: merged results accumulate on the
831
        # disposable repo's main, so runs must stay file-disjoint.
832
        rel_prefix = contention_payload_prefix(bench_id, subject.name, workers, run_index)
833
        results = [WorkerResult(worker=index) for index in range(workers)]
834
        threads = [
835
            threading.Thread(
836
                target=worker_loop,
837
                args=(subject, mounts[index], index, commits, results[index], rel_prefix),
838
            )
839
            for index in range(workers)
840
        ]
841
        wall_start = time.perf_counter()
842
        for thread in threads:
843
            thread.start()
844
        for thread in threads:
845
            thread.join()
846
        wall_ms = (time.perf_counter() - wall_start) * 1000
847
848
        # Timed per workspace: publishing the branch is part of oak's task
849
        # cycle (network), with no git analog in this mode.
850
        publish_samples: list[float] = []
851
        publish_failures = 0
852
        for index, mount_dir in enumerate(mounts):
853
            push_start = time.perf_counter()
854
            proc = run([vcs, "push"], mount_dir, timeout=300.0)
855
            publish_samples.append(round((time.perf_counter() - push_start) * 1000, 3))
856
            if proc.returncode != 0:
857
                publish_failures += 1
858
                record_worker_failure(
859
                    results[index],
860
                    "workspace_push_failed",
861
                    command=[vcs, "push"],
862
                    proc=proc,
863
                    workspace=mount_dir,
864
                )
865
866
        # Disk before teardown: visible vs allocated is the lazy-hydration
867
        # claim — a mount can show the whole tree while allocating ~nothing.
868
        usage_samples = [bounded_tree_usage(mount_dir) for mount_dir in mounts]
869
        marginal_alloc_kb: int | None = None
870
        marginal_visible_kb: int | None = None
871
        if usage_samples:
872
            marginal_alloc_kb = round(
873
                sum(sample["allocated_tree_bytes"] for sample in usage_samples) / len(usage_samples) / 1024
874
            )
875
            marginal_visible_kb = round(
876
                sum(sample["visible_tree_bytes"] for sample in usage_samples) / len(usage_samples) / 1024
877
            )
878
879
        # Timed merge phase: pull each workspace branch into the integrator
880
        # and fold it into main (server-side), oak's merge-throughput analog.
881
        merge_samples: list[float] = []
882
        conflicts = 0
883
        merged = 0
884
        merge_start = time.perf_counter()
885
        for index, branch in enumerate(branches):
886
            branch_start = time.perf_counter()
887
            switch = run([vcs, "switch", branch], integrator, timeout=300.0)
888
            if switch.returncode != 0:
889
                conflicts += 1
890
                record_worker_failure(
891
                    results[index],
892
                    "workspace_switch_failed",
893
                    command=[vcs, "switch", branch],
894
                    proc=switch,
895
                    workspace=integrator,
896
                )
897
                merge_samples.append(round((time.perf_counter() - branch_start) * 1000, 3))
898
                continue
899
            proc = run([vcs, "merge"], integrator, timeout=300.0)
900
            merge_samples.append(round((time.perf_counter() - branch_start) * 1000, 3))
901
            if proc.returncode != 0:
902
                conflicts += 1
903
                run([vcs, "merge", "--abort"], integrator)
904
                record_worker_failure(
905
                    results[index],
906
                    "workspace_merge_failed",
907
                    command=[vcs, "merge"],
908
                    proc=proc,
909
                    workspace=integrator,
910
                )
911
            else:
912
                merged += 1
913
        merge_ms = (time.perf_counter() - merge_start) * 1000
914
915
        # Integrity: payload survival in the merged tree plus oak's closest
916
        # fsck analog (log/status sanity); the integrator sits on a fresh
917
        # branch parented onto the merged main, so files are on disk.
918
        lost: int | None = 0
919
        try:
920
            for result in results:
921
                for rel_path, payload in result.succeeded_payloads:
922
                    recorded = tree_payload(subject, integrator, rel_path)
923
                    if recorded is None or payload not in recorded:
924
                        lost += 1
925
        except CommittedStateUnmeasured:
926
            lost = None
927
        sanity = run([vcs, "log", "-n", "1"], integrator)
928
        status = run([vcs, "status"], integrator)
929
        integrity_passed = None if lost is None else (
930
            sanity.returncode == 0
931
            and status.returncode == 0
932
            and lost == 0
933
            and conflicts == 0
934
            and publish_failures == 0
935
        )
936
937
        base_kb, base_entries = disk_usage(integrator)
938
        rows: list[dict[str, Any]] = []
939
        for result in results:
940
            row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
941
            row.update(
942
                {
943
                    "operation": "parallel.worker",
944
                    "worker": result.worker,
945
                    "elapsed_ms": round(result.elapsed_ms, 3),
946
                    "returncode": 1 if worker_result_failed(result) else 0,
947
                    "commits_attempted": result.commits_attempted,
948
                    "commits_succeeded": result.commits_succeeded,
949
                    "commits_swept": result.commits_swept,
950
                    "snapshots_performed": result.commits_succeeded - result.commits_swept,
951
                    "retries": result.retries,
952
                    "lock_failures": result.lock_failures,
953
                    "lock_wait_ms": round(result.lock_wait_ms, 3),
954
                    **worker_failure_fields(result, mounts[result.worker] if result.worker < len(mounts) else None),
955
                    **remote_fields,
956
                }
957
            )
958
            rows.append(row)
959
960
        total_succeeded = sum(result.commits_succeeded for result in results)
961
        total_attempted = sum(result.commits_attempted for result in results)
962
        row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
963
        row.update(
964
            {
965
                "operation": "parallel.total",
966
                "elapsed_ms": round(wall_ms, 3),
967
                "setup_ms": round(setup_ms, 3),
968
                "workspace_setup_ms_samples": setup_samples,
969
                "time_to_nth_workspace_ms": time_to_nth,
970
                "workspace_publish_ms_samples": publish_samples,
971
                "publish_failures": publish_failures,
972
                "merge_ms": round(merge_ms, 3),
973
                "merge_branch_ms_samples": merge_samples,
974
                "merges_clean": merged,
975
                "merge_conflicts": conflicts,
976
                "returncode": unmeasured_returncode(integrity_passed, 0 if integrity_passed and total_succeeded == total_attempted and not any_worker_result_failed(results) else 1),
977
                "skip_reason": "oak_committed_state_unmeasured:independent_reader_unavailable" if integrity_passed is None else None,
978
                "parallel_metrics": {
979
                    "tasks_total": total_attempted,
980
                    "tasks_completed": total_succeeded,
981
                    "max_parallel_tasks": workers,
982
                    "overlapping_files_count": 0,
983
                    "lost_updates_detected": lost,
984
                    "lock_wait_ms": round(sum(result.lock_wait_ms for result in results), 3),
985
                    "commit_throughput_per_s": round(total_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
986
                    "integrity_check_passed": integrity_passed,
987
                    "measurement_source": (
988
                        "oak_log_status_sanity_plus_payload_survival_after_merge; oak has no fsck equivalent yet"
989
                    ),
990
                },
991
                "workspace_disk_kb": base_kb,
992
                "workspace_entries": base_entries,
993
                "marginal_workspace_disk_kb": marginal_alloc_kb,
994
                "marginal_workspace_visible_kb": marginal_visible_kb,
995
                "workspace_disk_measurement": "allocated_bytes_mean_across_mounts (visible vs allocated: lazy hydration)",
996
                **remote_fields,
997
            }
998
        )
999
        if row["returncode"] != 0:
1000
            row.update(aggregate_worker_failure_fields(results, workspace=integrator))
1001
        rows.append(row)
1002
        return rows
1003
    finally:
1004
        for mount_dir in mounts:
1005
            run([vcs, "mount", "end", str(mount_dir), "-f"], lane_root, timeout=120.0)
1006
1007
1008
def run_workspace_per_task(
1009
    subject: Subject,
1010
    fixture: Path,
1011
    workers: int,
1012
    commits: int,
1013
    run_root: Path,
1014
    run_index: int,
1015
    metadata: dict[str, Any],
1016
) -> list[dict[str, Any]]:
1017
    rows: list[dict[str, Any]] = []
1018
    if subject.kind != "git":
1019
        return run_workspace_per_task_oak(
1020
            subject, fixture, workers, commits, run_root, run_index, metadata
1021
        )
1022
1023
    vcs = str(subject.bin)
1024
    base = run_root / f"wpt-{subject.name}-w{workers}-r{run_index}" / "base"
1025
    base.parent.mkdir(parents=True, exist_ok=True)
1026
    shutil.copytree(fixture, base)
1027
    if not init_repo(subject, base):
1028
        row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
1029
        row.update({"operation": "parallel.total", "elapsed_ms": 0.0, "returncode": 1, "stderr": "repo init failed"})
1030
        return [row]
1031
1032
    base_kb, base_entries = disk_usage(base)
1033
    setup_start = time.perf_counter()
1034
    worktrees: list[Path] = []
1035
    setup_samples: list[float] = []
1036
    time_to_nth: list[float] = []
1037
    for index in range(workers):
1038
        worktree = base.parent / f"wt-{index:03d}"
1039
        worktree_start = time.perf_counter()
1040
        proc = run([vcs, "worktree", "add", str(worktree), "-b", f"task-{index:03d}"], base)
1041
        setup_samples.append(round((time.perf_counter() - worktree_start) * 1000, 3))
1042
        time_to_nth.append(round((time.perf_counter() - setup_start) * 1000, 3))
1043
        if proc.returncode != 0:
1044
            row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
1045
            row.update(
1046
                {
1047
                    "operation": "parallel.total",
1048
                    "elapsed_ms": 0.0,
1049
                    "returncode": 1,
1050
                    "stderr": f"worktree add failed: {proc.stderr.strip()[:200]}",
1051
                }
1052
            )
1053
            return [row]
1054
        worktrees.append(worktree)
1055
    setup_ms = (time.perf_counter() - setup_start) * 1000
1056
1057
    results = [WorkerResult(worker=index) for index in range(workers)]
1058
    threads = [
1059
        threading.Thread(target=worker_loop, args=(subject, worktrees[index], index, commits, results[index]))
1060
        for index in range(workers)
1061
    ]
1062
    wall_start = time.perf_counter()
1063
    for thread in threads:
1064
        thread.start()
1065
    for thread in threads:
1066
        thread.join()
1067
    wall_ms = (time.perf_counter() - wall_start) * 1000
1068
1069
    merge_start = time.perf_counter()
1070
    conflicts = 0
1071
    merged = 0
1072
    for index in range(workers):
1073
        proc = run([vcs, "merge", "--no-edit", f"task-{index:03d}"], base)
1074
        if proc.returncode != 0:
1075
            conflicts += 1
1076
            run([vcs, "merge", "--abort"], base)
1077
            record_worker_failure(
1078
                results[index],
1079
                "worktree_merge_failed",
1080
                command=[vcs, "merge", "--no-edit", f"task-{index:03d}"],
1081
                proc=proc,
1082
                workspace=base,
1083
            )
1084
        else:
1085
            merged += 1
1086
    merge_ms = (time.perf_counter() - merge_start) * 1000
1087
1088
    lost = 0
1089
    for result in results:
1090
        for rel_path, payload in result.succeeded_payloads:
1091
            recorded = tree_payload(subject, base, rel_path)
1092
            if recorded is None or payload not in recorded:
1093
                lost += 1
1094
    fsck = run([vcs, "fsck", "--no-progress"], base)
1095
    integrity_passed = fsck.returncode == 0 and lost == 0 and conflicts == 0
1096
1097
    marginal_kb: int | None = None
1098
    if worktrees and base_kb is not None:
1099
        worktree_kb = [disk_usage(worktree)[0] for worktree in worktrees]
1100
        known = [kb for kb in worktree_kb if kb is not None]
1101
        if known:
1102
            marginal_kb = round(sum(known) / len(known))
1103
1104
    for result in results:
1105
        row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
1106
        row.update(
1107
            {
1108
                "operation": "parallel.worker",
1109
                "worker": result.worker,
1110
                "elapsed_ms": round(result.elapsed_ms, 3),
1111
                "returncode": 1 if worker_result_failed(result) else 0,
1112
                "commits_attempted": result.commits_attempted,
1113
                "commits_succeeded": result.commits_succeeded,
1114
                "commits_swept": result.commits_swept,
1115
                "snapshots_performed": result.commits_succeeded - result.commits_swept,
1116
                "retries": result.retries,
1117
                "lock_failures": result.lock_failures,
1118
                "lock_wait_ms": round(result.lock_wait_ms, 3),
1119
                **worker_failure_fields(result, worktrees[result.worker] if result.worker < len(worktrees) else None),
1120
            }
1121
        )
1122
        rows.append(row)
1123
1124
    total_succeeded = sum(result.commits_succeeded for result in results)
1125
    total_attempted = sum(result.commits_attempted for result in results)
1126
    row = base_row(metadata, subject, "workspace_per_task", workers, run_index)
1127
    row.update(
1128
        {
1129
            "operation": "parallel.total",
1130
            "elapsed_ms": round(wall_ms, 3),
1131
            "setup_ms": round(setup_ms, 3),
1132
            "workspace_setup_ms_samples": setup_samples,
1133
            "time_to_nth_workspace_ms": time_to_nth,
1134
            "workspace_transport": "local_file",
1135
            "merge_ms": round(merge_ms, 3),
1136
            "merges_clean": merged,
1137
            "merge_conflicts": conflicts,
1138
            "returncode": unmeasured_returncode(integrity_passed, 0 if integrity_passed and total_succeeded == total_attempted and not any_worker_result_failed(results) else 1),
1139
            "skip_reason": "oak_committed_state_unmeasured:independent_reader_unavailable" if integrity_passed is None else None,
1140
            "parallel_metrics": {
1141
                "tasks_total": total_attempted,
1142
                "tasks_completed": total_succeeded,
1143
                "max_parallel_tasks": workers,
1144
                "overlapping_files_count": 0,
1145
                "lost_updates_detected": lost,
1146
                "lock_wait_ms": round(sum(result.lock_wait_ms for result in results), 3),
1147
                "commit_throughput_per_s": round(total_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
1148
                "integrity_check_passed": integrity_passed,
1149
                "measurement_source": "git_fsck_plus_payload_survival_after_merge",
1150
            },
1151
            "workspace_disk_kb": base_kb,
1152
            "workspace_entries": base_entries,
1153
            "marginal_workspace_disk_kb": marginal_kb,
1154
        }
1155
    )
1156
    if row["returncode"] != 0:
1157
        row.update(aggregate_worker_failure_fields(results, workspace=base))
1158
    rows.append(row)
1159
    return rows
1160
1161
1162
# --------------------------------------------------------------------------
1163
# Fleet-scale modes (additive; see FLEET_MODES). Scenario names follow the
1164
# established contention_<mode>_w<N> shape via base_row, except long_divergence
1165
# which encodes its variable as contention_long_divergence_k<K> (ADR-0005).
1166
# --------------------------------------------------------------------------
1167
1168
1169
def mode_skip_row(
1170
    metadata: dict[str, Any],
1171
    subject: Subject,
1172
    mode: str,
1173
    workers: int,
1174
    run_index: int,
1175
    reason: str,
1176
    scenario: str | None = None,
1177
) -> dict[str, Any]:
1178
    """Structured skip: a recorded coverage gap, never a silent absence (ADR-0002)."""
1179
    row = base_row(metadata, subject, mode, workers, run_index)
1180
    if scenario is not None:
1181
        row["scenario"] = scenario
1182
    row.update(
1183
        {
1184
            "operation": "parallel.total",
1185
            "elapsed_ms": 0.0,
1186
            "returncode": SKIP_RETURNCODE,
1187
            "skipped": True,
1188
            "skip_reason": reason,
1189
        }
1190
    )
1191
    return row
1192
1193
1194
def fleet_mode_subject_skip(
1195
    metadata: dict[str, Any],
1196
    subject: Subject,
1197
    mode: str,
1198
    workers: int,
1199
    run_index: int,
1200
    scenario: str | None = None,
1201
) -> dict[str, Any]:
1202
    return mode_skip_row(
1203
        metadata,
1204
        subject,
1205
        mode,
1206
        workers,
1207
        run_index,
1208
        reason=(
1209
            f"{mode}_not_implemented_for_kind_{subject.kind}: this fleet mode currently "
1210
            "drives git binaries only; an oak runner (mount/clone orchestration against "
1211
            "OAK_BENCH_FLEET_REPO, see workspace_per_task) is a work item, not an absence"
1212
        ),
1213
        scenario=scenario,
1214
    )
1215
1216
1217
def mode_error_row(
1218
    metadata: dict[str, Any],
1219
    subject: Subject,
1220
    mode: str,
1221
    workers: int,
1222
    run_index: int,
1223
    stderr: str,
1224
) -> dict[str, Any]:
1225
    row = base_row(metadata, subject, mode, workers, run_index)
1226
    row.update({"operation": "parallel.total", "elapsed_ms": 0.0, "returncode": 1, "stderr": stderr})
1227
    return row
1228
1229
1230
def payload_survival(subject: Subject, repo: Path, payloads: list[tuple[str, str]]) -> int:
1231
    """Count payloads a worker recorded as landed that are missing from HEAD."""
1232
    lost = 0
1233
    for rel_path, payload in payloads:
1234
        recorded = tree_payload(subject, repo, rel_path)
1235
        if recorded is None or payload not in recorded:
1236
            lost += 1
1237
    return lost
1238
1239
1240
def run_merge_train(
1241
    subject: Subject,
1242
    fixture: Path,
1243
    workers: int,
1244
    commits: int,
1245
    run_root: Path,
1246
    run_index: int,
1247
    metadata: dict[str, Any],
1248
) -> list[dict[str, Any]]:
1249
    """N branches built concurrently, landed serially through merge — the
1250
    merge-train pattern. Measures per-worker queue_wait_ms (land requested →
1251
    merge started), merge_ms, and total merges/min through the train."""
1252
    mode = "merge_train"
1253
    if subject.kind != "git":
1254
        return [fleet_mode_subject_skip(metadata, subject, mode, workers, run_index)]
1255
    vcs = str(subject.bin)
1256
    base = run_root / f"mt-{subject.name}-w{workers}-r{run_index}" / "base"
1257
    base.parent.mkdir(parents=True, exist_ok=True)
1258
    shutil.copytree(fixture, base)
1259
    if not init_repo(subject, base):
1260
        return [mode_error_row(metadata, subject, mode, workers, run_index, "repo init failed")]
1261
1262
    worktrees: list[Path] = []
1263
    for index in range(workers):
1264
        worktree = base.parent / f"wt-{index:03d}"
1265
        proc = run([vcs, "worktree", "add", str(worktree), "-b", f"train-{index:03d}"], base, timeout=300.0)
1266
        if proc.returncode != 0:
1267
            return [
1268
                mode_error_row(
1269
                    metadata, subject, mode, workers, run_index,
1270
                    f"worktree add failed: {proc.stderr.strip()[:200]}",
1271
                )
1272
            ]
1273
        worktrees.append(worktree)
1274
1275
    results = [WorkerResult(worker=index) for index in range(workers)]
1276
    ready_at: list[float | None] = [None] * workers
1277
1278
    def build(index: int) -> None:
1279
        worker_loop(subject, worktrees[index], index, commits, results[index])
1280
        # The land request: the moment this branch is ready for the train.
1281
        ready_at[index] = time.perf_counter()
1282
1283
    threads = [threading.Thread(target=build, args=(index,)) for index in range(workers)]
1284
    wall_start = time.perf_counter()
1285
    for thread in threads:
1286
        thread.start()
1287
    for thread in threads:
1288
        thread.join()
1289
    build_ms = (time.perf_counter() - wall_start) * 1000
1290
1291
    # Serial landing in arrival order: queue_wait is request->merge-start.
1292
    order = sorted(range(workers), key=lambda index: ready_at[index] if ready_at[index] is not None else float("inf"))
1293
    queue_wait_ms: list[float | None] = [None] * workers
1294
    merge_ms_per_worker: list[float | None] = [None] * workers
1295
    landed: list[bool] = [False] * workers
1296
    land_start = time.perf_counter()
1297
    merged = 0
1298
    conflicts = 0
1299
    for index in order:
1300
        merge_start = time.perf_counter()
1301
        if ready_at[index] is not None:
1302
            queue_wait_ms[index] = round((merge_start - ready_at[index]) * 1000, 3)
1303
        proc = run([vcs, "merge", "--no-edit", f"train-{index:03d}"], base, timeout=300.0)
1304
        merge_ms_per_worker[index] = round((time.perf_counter() - merge_start) * 1000, 3)
1305
        if proc.returncode != 0:
1306
            conflicts += 1
1307
            run([vcs, "merge", "--abort"], base)
1308
            record_worker_failure(
1309
                results[index],
1310
                "train_merge_failed",
1311
                command=[vcs, "merge", "--no-edit", f"train-{index:03d}"],
1312
                proc=proc,
1313
                workspace=base,
1314
            )
1315
        else:
1316
            merged += 1
1317
            landed[index] = True
1318
    land_ms = (time.perf_counter() - land_start) * 1000
1319
    wall_ms = (time.perf_counter() - wall_start) * 1000
1320
    merges_per_min = round(merged / (land_ms / 60000.0), 3) if land_ms > 0 else None
1321
1322
    lost = sum(
1323
        payload_survival(subject, base, result.succeeded_payloads)
1324
        for index, result in enumerate(results)
1325
        if landed[index]
1326
    )
1327
    fsck = run([vcs, "fsck", "--no-progress"], base)
1328
    integrity_passed = fsck.returncode == 0 and lost == 0 and conflicts == 0
1329
1330
    rows: list[dict[str, Any]] = []
1331
    for index, result in enumerate(results):
1332
        row = base_row(metadata, subject, mode, workers, run_index)
1333
        row.update(
1334
            {
1335
                "operation": "parallel.worker",
1336
                "worker": result.worker,
1337
                "elapsed_ms": round(result.elapsed_ms, 3),
1338
                "returncode": 0 if not worker_result_failed(result) and landed[index] else 1,
1339
                "commits_attempted": result.commits_attempted,
1340
                "commits_succeeded": result.commits_succeeded,
1341
                "retries": result.retries,
1342
                "lock_failures": result.lock_failures,
1343
                "queue_wait_ms": queue_wait_ms[index],
1344
                "merge_ms": merge_ms_per_worker[index],
1345
                "landed": landed[index],
1346
                **worker_failure_fields(result, worktrees[index] if index < len(worktrees) else None),
1347
            }
1348
        )
1349
        rows.append(row)
1350
1351
    queue_samples = [value for value in queue_wait_ms if value is not None]
1352
    merge_samples = [value for value in merge_ms_per_worker if value is not None]
1353
    total = base_row(metadata, subject, mode, workers, run_index)
1354
    total.update(
1355
        {
1356
            "operation": "parallel.total",
1357
            "elapsed_ms": round(wall_ms, 3),
1358
            "build_ms": round(build_ms, 3),
1359
            "land_ms": round(land_ms, 3),
1360
            "merges_per_min": merges_per_min,
1361
            "merges_clean": merged,
1362
            "merge_conflicts": conflicts,
1363
            "queue_wait_tail": tail_latency_summary(queue_samples),
1364
            "merge_latency_tail": tail_latency_summary(merge_samples),
1365
            "returncode": 0 if integrity_passed and merged == workers and not any_worker_result_failed(results) else 1,
1366
            "parallel_metrics": {
1367
                "tasks_total": sum(result.commits_attempted for result in results),
1368
                "tasks_completed": sum(result.commits_succeeded for result in results),
1369
                "max_parallel_tasks": workers,
1370
                "overlapping_files_count": 0,
1371
                "lost_updates_detected": lost,
1372
                "lock_wait_ms": round(sum(result.lock_wait_ms for result in results), 3),
1373
                "commit_throughput_per_s": (
1374
                    round(sum(result.commits_succeeded for result in results) / (wall_ms / 1000.0), 3)
1375
                    if wall_ms
1376
                    else None
1377
                ),
1378
                "integrity_check_passed": integrity_passed,
1379
                "measurement_source": "git_fsck_plus_payload_survival_after_merge_train",
1380
            },
1381
            "retries_total": sum(result.retries for result in results),
1382
            "lock_failures_total": sum(result.lock_failures for result in results),
1383
        }
1384
    )
1385
    if total["returncode"] != 0:
1386
        total.update(aggregate_worker_failure_fields(results, workspace=base))
1387
    rows.append(total)
1388
    return rows
1389
1390
1391
def seed_git_bare_remote(
1392
    subject: Subject, fixture: Path, lane_root: Path
1393
) -> tuple[Any, Path] | str:
1394
    """Untimed precondition: bare remote + seeded main. Returns error text on failure."""
1395
    vcs = str(subject.bin)
1396
    seed = lane_root / "seed"
1397
    lane_root.mkdir(parents=True, exist_ok=True)
1398
    shutil.copytree(fixture, seed)
1399
    if not init_repo(subject, seed):
1400
        return "seed repo init failed"
1401
    remote = make_git_bare_remote(vcs, lane_root)
1402
    attach_git_origin(vcs, seed, remote)
1403
    proc = run([vcs, "push", "origin", "main"], seed, timeout=300.0)
1404
    if proc.returncode != 0:
1405
        return f"seed push failed: {proc.stderr.strip()[:200]}"
1406
    point_git_bare_head(vcs, remote, "main")
1407
    return remote, seed
1408
1409
1410
def run_rebase_storm(
1411
    subject: Subject,
1412
    fixture: Path,
1413
    workers: int,
1414
    commits: int,
1415
    run_root: Path,
1416
    run_index: int,
1417
    metadata: dict[str, Any],
1418
) -> list[dict[str, Any]]:
1419
    """Workers race to land on a moving main: rebase onto origin/main, push,
1420
    and on non-fast-forward rejection rebase again. Rows record the
1421
    attempts-to-land distribution — the cost of a moving target."""
1422
    mode = "rebase_storm"
1423
    if subject.kind != "git":
1424
        return [fleet_mode_subject_skip(metadata, subject, mode, workers, run_index)]
1425
    vcs = str(subject.bin)
1426
    lane_root = run_root / f"rs-{subject.name}-w{workers}-r{run_index}"
1427
    seeded = seed_git_bare_remote(subject, fixture, lane_root)
1428
    if isinstance(seeded, str):
1429
        return [mode_error_row(metadata, subject, mode, workers, run_index, seeded)]
1430
    remote, _seed = seeded
1431
    remote_fields = remote.row_fields()
1432
1433
    states: list[dict[str, Any]] = [
1434
        {
1435
            "worker": index,
1436
            "elapsed_ms": 0.0,
1437
            "lands_attempted": 0,
1438
            "lands_succeeded": 0,
1439
            "attempts_to_land": [],
1440
            "land_latency_ms": [],
1441
            "payloads": [],
1442
            "errors": [],
1443
        }
1444
        for index in range(workers)
1445
    ]
1446
1447
    def storm(index: int) -> None:
1448
        state = states[index]
1449
        start = time.perf_counter()
1450
        try:
1451
            wdir = lane_root / f"w{index:03d}"
1452
            proc = run([vcs, "clone", remote.repo, str(wdir)], lane_root, timeout=300.0)
1453
            if proc.returncode != 0:
1454
                state["errors"].append(f"clone failed: {proc.stderr.strip()[:200]}")
1455
                return
1456
            for k in range(commits):
1457
                rel_path = f"storm/w{index:03d}/f{k:03d}.txt"
1458
                payload = f"payload worker={index} commit={k} nonce={index * 100003 + k}\n"
1459
                target = wdir / rel_path
1460
                target.parent.mkdir(parents=True, exist_ok=True)
1461
                target.write_text(payload)
1462
                state["lands_attempted"] += 1
1463
                committed = True
1464
                for command in snapshot_commands(subject, f"storm w{index} k{k}"):
1465
                    proc = run(command, wdir)
1466
                    if proc.returncode != 0:
1467
                        state["errors"].append(f"local commit failed: {proc.stderr.strip()[:200]}")
1468
                        committed = False
1469
                        break
1470
                if not committed:
1471
                    continue
1472
                land_start = time.perf_counter()
1473
                attempts = 0
1474
                landed = False
1475
                while attempts < MAX_LAND_ATTEMPTS:
1476
                    attempts += 1
1477
                    run([vcs, "fetch", "origin", "main"], wdir, timeout=300.0)
1478
                    rebase = run([vcs, "rebase", "origin/main"], wdir, timeout=300.0)
1479
                    if rebase.returncode != 0:
1480
                        run([vcs, "rebase", "--abort"], wdir)
1481
                        state["errors"].append(f"rebase failed: {rebase.stderr.strip()[:200]}")
1482
                        break
1483
                    push = run([vcs, "push", "origin", "HEAD:main"], wdir, timeout=300.0)
1484
                    if push.returncode == 0:
1485
                        landed = True
1486
                        break
1487
                state["attempts_to_land"].append(attempts)
1488
                state["land_latency_ms"].append(round((time.perf_counter() - land_start) * 1000, 3))
1489
                if landed:
1490
                    state["lands_succeeded"] += 1
1491
                    state["payloads"].append((rel_path, payload))
1492
        except Exception as exc:  # noqa: BLE001 - recorded, not hidden
1493
            state["errors"].append(f"worker exception: {type(exc).__name__}: {exc}"[:200])
1494
        finally:
1495
            state["elapsed_ms"] = (time.perf_counter() - start) * 1000
1496
1497
    threads = [threading.Thread(target=storm, args=(index,)) for index in range(workers)]
1498
    wall_start = time.perf_counter()
1499
    for thread in threads:
1500
        thread.start()
1501
    for thread in threads:
1502
        thread.join()
1503
    wall_ms = (time.perf_counter() - wall_start) * 1000
1504
1505
    # Integrity: a fresh clone of the remote must contain every landed payload.
1506
    verify = lane_root / "verify"
1507
    clone = run([vcs, "clone", remote.repo, str(verify)], lane_root, timeout=300.0)
1508
    lost: int | None = None
1509
    fsck_ok: bool | None = None
1510
    if clone.returncode == 0:
1511
        lost = sum(payload_survival(subject, verify, state["payloads"]) for state in states)
1512
        fsck_ok = run([vcs, "fsck", "--no-progress"], verify).returncode == 0
1513
    total_landed = sum(state["lands_succeeded"] for state in states)
1514
    total_attempted = sum(state["lands_attempted"] for state in states)
1515
    integrity_passed = fsck_ok is True and lost == 0
1516
1517
    rows: list[dict[str, Any]] = []
1518
    for state in states:
1519
        row = base_row(metadata, subject, mode, workers, run_index)
1520
        row.update(
1521
            {
1522
                "operation": "parallel.worker",
1523
                "worker": state["worker"],
1524
                "elapsed_ms": round(state["elapsed_ms"], 3),
1525
                "returncode": 0 if state["lands_succeeded"] == state["lands_attempted"] else 1,
1526
                "lands_attempted": state["lands_attempted"],
1527
                "lands_succeeded": state["lands_succeeded"],
1528
                "attempts_to_land": state["attempts_to_land"],
1529
                "land_latency_samples_ms": state["land_latency_ms"],
1530
                "error_examples": state["errors"][:5],
1531
                **remote_fields,
1532
            }
1533
        )
1534
        rows.append(row)
1535
1536
    attempts_histogram: dict[str, int] = {}
1537
    for state in states:
1538
        for attempts in state["attempts_to_land"]:
1539
            key = str(attempts)
1540
            attempts_histogram[key] = attempts_histogram.get(key, 0) + 1
1541
    all_land_latencies = [sample for state in states for sample in state["land_latency_ms"]]
1542
    total = base_row(metadata, subject, mode, workers, run_index)
1543
    total.update(
1544
        {
1545
            "operation": "parallel.total",
1546
            "elapsed_ms": round(wall_ms, 3),
1547
            "returncode": 0 if integrity_passed and total_landed == total_attempted else 1,
1548
            "attempts_to_land_histogram": attempts_histogram,
1549
            "land_latency_tail": tail_latency_summary(all_land_latencies),
1550
            "lands_per_min": round(total_landed / (wall_ms / 60000.0), 3) if wall_ms > 0 else None,
1551
            "parallel_metrics": {
1552
                "tasks_total": total_attempted,
1553
                "tasks_completed": total_landed,
1554
                "max_parallel_tasks": workers,
1555
                "overlapping_files_count": 0,
1556
                "lost_updates_detected": lost,
1557
                "lock_wait_ms": None,
1558
                "commit_throughput_per_s": round(total_landed / (wall_ms / 1000.0), 3) if wall_ms else None,
1559
                "integrity_check_passed": integrity_passed,
1560
                "measurement_source": "git_fsck_plus_payload_survival_in_fresh_clone",
1561
            },
1562
            **remote_fields,
1563
        }
1564
    )
1565
    rows.append(total)
1566
    return rows
1567
1568
1569
def run_mixed_fleet(
1570
    subject: Subject,
1571
    fixture: Path,
1572
    workers: int,
1573
    commits: int,
1574
    run_root: Path,
1575
    run_index: int,
1576
    metadata: dict[str, Any],
1577
) -> list[dict[str, Any]]:
1578
    """Readers poll status/log while writers commit in the same checkout —
1579
    direct evidence for (or against) read-path thrash under write load.
1580
    Reader rows carry raw poll-latency samples; zero failed polls plus a flat
1581
    tail is the zero-thrash claim."""
1582
    mode = "mixed_fleet"
1583
    if subject.kind != "git":
1584
        return [fleet_mode_subject_skip(metadata, subject, mode, workers, run_index)]
1585
    vcs = str(subject.bin)
1586
    repo = run_root / f"mf-{subject.name}-w{workers}-r{run_index}"
1587
    shutil.copytree(fixture, repo)
1588
    if not init_repo(subject, repo):
1589
        return [mode_error_row(metadata, subject, mode, workers, run_index, "repo init failed")]
1590
1591
    writer_count = max(1, workers // 2)
1592
    reader_count = workers - writer_count
1593
    writer_results = [WorkerResult(worker=index) for index in range(writer_count)]
1594
    reader_states: list[dict[str, Any]] = [
1595
        {
1596
            "worker": writer_count + index,
1597
            "elapsed_ms": 0.0,
1598
            "polls_total": 0,
1599
            "poll_failures": 0,
1600
            "poll_latency_ms": [],
1601
            "errors": [],
1602
        }
1603
        for index in range(reader_count)
1604
    ]
1605
    stop = threading.Event()
1606
1607
    def reader_loop(state: dict[str, Any]) -> None:
1608
        start = time.perf_counter()
1609
        try:
1610
            while not stop.is_set():
1611
                poll_start = time.perf_counter()
1612
                status = run([vcs, "status", "--porcelain"], repo)
1613
                log = run([vcs, "log", "-n", "5", "--oneline"], repo)
1614
                state["poll_latency_ms"].append(round((time.perf_counter() - poll_start) * 1000, 3))
1615
                state["polls_total"] += 1
1616
                if status.returncode != 0 or log.returncode != 0:
1617
                    state["poll_failures"] += 1
1618
                    if len(state["errors"]) < 5:
1619
                        state["errors"].append((status.stderr or log.stderr).strip()[:200])
1620
                stop.wait(READER_POLL_INTERVAL_S)
1621
        except Exception as exc:  # noqa: BLE001 - recorded, not hidden
1622
            state["errors"].append(f"reader exception: {type(exc).__name__}: {exc}"[:200])
1623
        finally:
1624
            state["elapsed_ms"] = (time.perf_counter() - start) * 1000
1625
1626
    writer_threads = [
1627
        threading.Thread(target=worker_loop, args=(subject, repo, index, commits, writer_results[index]))
1628
        for index in range(writer_count)
1629
    ]
1630
    reader_threads = [threading.Thread(target=reader_loop, args=(state,)) for state in reader_states]
1631
    wall_start = time.perf_counter()
1632
    for thread in reader_threads + writer_threads:
1633
        thread.start()
1634
    for thread in writer_threads:
1635
        thread.join()
1636
    stop.set()
1637
    for thread in reader_threads:
1638
        thread.join()
1639
    wall_ms = (time.perf_counter() - wall_start) * 1000
1640
1641
    integrity_passed, lost_updates, method = integrity_check(subject, repo, writer_results)
1642
1643
    rows: list[dict[str, Any]] = []
1644
    for result in writer_results:
1645
        row = base_row(metadata, subject, mode, workers, run_index)
1646
        row.update(
1647
            {
1648
                "operation": "parallel.worker",
1649
                "role": "writer",
1650
                "worker": result.worker,
1651
                "elapsed_ms": round(result.elapsed_ms, 3),
1652
                "returncode": 1 if worker_result_failed(result) else 0,
1653
                "commits_attempted": result.commits_attempted,
1654
                "commits_succeeded": result.commits_succeeded,
1655
                "commits_swept": result.commits_swept,
1656
                "retries": result.retries,
1657
                "lock_failures": result.lock_failures,
1658
                "lock_wait_ms": round(result.lock_wait_ms, 3),
1659
                **worker_failure_fields(result, repo),
1660
            }
1661
        )
1662
        rows.append(row)
1663
    for state in reader_states:
1664
        row = base_row(metadata, subject, mode, workers, run_index)
1665
        row.update(
1666
            {
1667
                "operation": "parallel.reader",
1668
                "role": "reader",
1669
                "worker": state["worker"],
1670
                "elapsed_ms": round(state["elapsed_ms"], 3),
1671
                "returncode": 0 if state["poll_failures"] == 0 else 1,
1672
                "polls_total": state["polls_total"],
1673
                "poll_failures": state["poll_failures"],
1674
                "poll_latency_samples_ms": state["poll_latency_ms"],
1675
                "poll_latency_tail": tail_latency_summary(state["poll_latency_ms"]),
1676
                "error_examples": state["errors"],
1677
            }
1678
        )
1679
        rows.append(row)
1680
1681
    all_polls = [sample for state in reader_states for sample in state["poll_latency_ms"]]
1682
    total_succeeded = sum(result.commits_succeeded for result in writer_results)
1683
    total_attempted = sum(result.commits_attempted for result in writer_results)
1684
    poll_failures_total = sum(state["poll_failures"] for state in reader_states)
1685
    total = base_row(metadata, subject, mode, workers, run_index)
1686
    total.update(
1687
        {
1688
            "operation": "parallel.total",
1689
            "elapsed_ms": round(wall_ms, 3),
1690
            "writers": writer_count,
1691
            "readers": reader_count,
1692
            "polls_total": sum(state["polls_total"] for state in reader_states),
1693
            "poll_failures_total": poll_failures_total,
1694
            "poll_latency_tail": tail_latency_summary(all_polls),
1695
            "returncode": unmeasured_returncode(integrity_passed, 0 if integrity_passed and total_succeeded == total_attempted and poll_failures_total == 0 and not any_worker_result_failed(writer_results) else 1),
1696
            "skip_reason": "oak_committed_state_unmeasured:independent_reader_unavailable" if integrity_passed is None else None,
1697
            "parallel_metrics": {
1698
                "tasks_total": total_attempted,
1699
                "tasks_completed": total_succeeded,
1700
                "max_parallel_tasks": workers,
1701
                "overlapping_files_count": 0,
1702
                "lost_updates_detected": lost_updates,
1703
                "lock_wait_ms": round(sum(result.lock_wait_ms for result in writer_results), 3),
1704
                "commit_throughput_per_s": round(total_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
1705
                "integrity_check_passed": integrity_passed,
1706
                "measurement_source": method,
1707
            },
1708
            "retries_total": sum(result.retries for result in writer_results),
1709
            "lock_failures_total": sum(result.lock_failures for result in writer_results),
1710
        }
1711
    )
1712
    if total["returncode"] != 0:
1713
        total.update(aggregate_worker_failure_fields(writer_results, workspace=repo))
1714
    rows.append(total)
1715
    return rows
1716
1717
1718
def run_conflict_storm(
1719
    subject: Subject,
1720
    fixture: Path,
1721
    workers: int,
1722
    commits: int,
1723
    run_root: Path,
1724
    run_index: int,
1725
    metadata: dict[str, Any],
1726
) -> list[dict[str, Any]]:
1727
    """Workers append sentinel lines to OVERLAPPING files and snapshot.
1728
    Appends are serialized in-process (serial-safe content), so any sentinel
1729
    missing from HEAD afterwards is a VCS-level lost update, not a harness
1730
    write race. Every worker's surviving sentinels are verified explicitly."""
1731
    mode = "conflict_storm"
1732
    if subject.kind != "git":
1733
        return [fleet_mode_subject_skip(metadata, subject, mode, workers, run_index)]
1734
    vcs = str(subject.bin)
1735
    repo = run_root / f"cs-{subject.name}-w{workers}-r{run_index}"
1736
    shutil.copytree(fixture, repo)
1737
    shared_files = [f"conflict/shared-{index}.txt" for index in range(CONFLICT_STORM_FILES)]
1738
    for rel_path in shared_files:
1739
        target = repo / rel_path
1740
        target.parent.mkdir(parents=True, exist_ok=True)
1741
        target.write_text("conflict storm seed\n")
1742
    if not init_repo(subject, repo):
1743
        return [mode_error_row(metadata, subject, mode, workers, run_index, "repo init failed")]
1744
1745
    file_locks = [threading.Lock() for _ in shared_files]
1746
    states: list[dict[str, Any]] = [
1747
        {
1748
            "worker": index,
1749
            "elapsed_ms": 0.0,
1750
            "commits_attempted": 0,
1751
            "commits_succeeded": 0,
1752
            "commits_swept": 0,
1753
            "retries": 0,
1754
            "lock_failures": 0,
1755
            "sentinels": [],  # (rel_path, line) for every append this worker made
1756
            "errors": [],
1757
        }
1758
        for index in range(workers)
1759
    ]
1760
1761
    def storm(index: int) -> None:
1762
        state = states[index]
1763
        start = time.perf_counter()
1764
        try:
1765
            for k in range(commits):
1766
                file_index = (index + k) % len(shared_files)
1767
                rel_path = shared_files[file_index]
1768
                line = f"sentinel worker={index} commit={k} nonce={index * 100003 + k}\n"
1769
                with file_locks[file_index]:
1770
                    with (repo / rel_path).open("a") as fh:
1771
                        fh.write(line)
1772
                state["sentinels"].append((rel_path, line))
1773
                state["commits_attempted"] += 1
1774
                committed = False
1775
                swept = False
1776
                for _attempt in range(MAX_SNAPSHOT_ATTEMPTS):
1777
                    failed = False
1778
                    stderr_text = ""
1779
                    for command in snapshot_commands(subject, f"storm w{index} k{k}"):
1780
                        proc = run(command, repo)
1781
                        stderr_text = proc.stderr
1782
                        if proc.returncode != 0:
1783
                            if "nothing to commit" in (proc.stdout + proc.stderr):
1784
                                swept = True
1785
                                break
1786
                            failed = True
1787
                            break
1788
                    if not failed:
1789
                        committed = True
1790
                        break
1791
                    state["retries"] += 1
1792
                    if looks_like_lock_failure(stderr_text):
1793
                        state["lock_failures"] += 1
1794
                    elif len(state["errors"]) < 5:
1795
                        state["errors"].append(stderr_text.strip()[:200])
1796
                    time.sleep(RETRY_SLEEP_S)
1797
                if committed:
1798
                    state["commits_succeeded"] += 1
1799
                    if swept:
1800
                        state["commits_swept"] += 1
1801
        except Exception as exc:  # noqa: BLE001 - recorded, not hidden
1802
            state["errors"].append(f"worker exception: {type(exc).__name__}: {exc}"[:200])
1803
        finally:
1804
            state["elapsed_ms"] = (time.perf_counter() - start) * 1000
1805
1806
    threads = [threading.Thread(target=storm, args=(index,)) for index in range(workers)]
1807
    wall_start = time.perf_counter()
1808
    for thread in threads:
1809
        thread.start()
1810
    for thread in threads:
1811
        thread.join()
1812
    wall_ms = (time.perf_counter() - wall_start) * 1000
1813
1814
    # Lost-update detection: sweep stragglers, then every appended sentinel
1815
    # line must survive in HEAD. A missing sentinel is a lost update.
1816
    for command in snapshot_commands(subject, "conflict storm sweep"):
1817
        run(command, repo)
1818
    lost_by_worker: dict[str, int] = {}
1819
    lost_total = 0
1820
    surviving_total = 0
1821
    head_cache: dict[str, str | None] = {}
1822
    for state in states:
1823
        worker_lost = 0
1824
        for rel_path, line in state["sentinels"]:
1825
            if rel_path not in head_cache:
1826
                head_cache[rel_path] = tree_payload(subject, repo, rel_path)
1827
            content = head_cache[rel_path]
1828
            if content is None or line not in content:
1829
                worker_lost += 1
1830
            else:
1831
                surviving_total += 1
1832
        if worker_lost:
1833
            lost_by_worker[str(state["worker"])] = worker_lost
1834
        lost_total += worker_lost
1835
    fsck = run([vcs, "fsck", "--no-progress"], repo)
1836
    integrity_passed = fsck.returncode == 0 and lost_total == 0
1837
1838
    rows: list[dict[str, Any]] = []
1839
    for state in states:
1840
        row = base_row(metadata, subject, mode, workers, run_index)
1841
        row.update(
1842
            {
1843
                "operation": "parallel.worker",
1844
                "worker": state["worker"],
1845
                "elapsed_ms": round(state["elapsed_ms"], 3),
1846
                "returncode": 0
1847
                if state["commits_succeeded"] == state["commits_attempted"]
1848
                and str(state["worker"]) not in lost_by_worker
1849
                else 1,
1850
                "commits_attempted": state["commits_attempted"],
1851
                "commits_succeeded": state["commits_succeeded"],
1852
                "commits_swept": state["commits_swept"],
1853
                "retries": state["retries"],
1854
                "lock_failures": state["lock_failures"],
1855
                "sentinels_expected": len(state["sentinels"]),
1856
                "sentinels_lost": lost_by_worker.get(str(state["worker"]), 0),
1857
                "error_examples": state["errors"],
1858
            }
1859
        )
1860
        rows.append(row)
1861
1862
    sentinels_expected = sum(len(state["sentinels"]) for state in states)
1863
    total_succeeded = sum(state["commits_succeeded"] for state in states)
1864
    total_attempted = sum(state["commits_attempted"] for state in states)
1865
    total = base_row(metadata, subject, mode, workers, run_index)
1866
    total.update(
1867
        {
1868
            "operation": "parallel.total",
1869
            "elapsed_ms": round(wall_ms, 3),
1870
            "returncode": 0 if integrity_passed and total_succeeded == total_attempted else 1,
1871
            "sentinel_accounting": {
1872
                "sentinels_expected": sentinels_expected,
1873
                "sentinels_surviving": surviving_total,
1874
                "lost_updates_detected": lost_total,
1875
                "lost_updates_by_worker": lost_by_worker,
1876
                "append_serialization": "in_process_file_lock (serial-safe content; losses are VCS-level)",
1877
            },
1878
            "parallel_metrics": {
1879
                "tasks_total": total_attempted,
1880
                "tasks_completed": total_succeeded,
1881
                "max_parallel_tasks": workers,
1882
                "overlapping_files_count": len(shared_files),
1883
                "lost_updates_detected": lost_total,
1884
                "lock_wait_ms": None,
1885
                "commit_throughput_per_s": round(total_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
1886
                "integrity_check_passed": integrity_passed,
1887
                "measurement_source": "git_fsck_plus_sentinel_survival_in_overlapping_files",
1888
            },
1889
            "retries_total": sum(state["retries"] for state in states),
1890
            "lock_failures_total": sum(state["lock_failures"] for state in states),
1891
        }
1892
    )
1893
    rows.append(total)
1894
    return rows
1895
1896
1897
def run_clone_push_storm(
1898
    subject: Subject,
1899
    fixture: Path,
1900
    workers: int,
1901
    commits: int,
1902
    run_root: Path,
1903
    run_index: int,
1904
    metadata: dict[str, Any],
1905
) -> list[dict[str, Any]]:
1906
    """N concurrent clone -> commit -> push cycles against ONE remote: the
1907
    server write-path stress test. Git uses GIT_BENCH_REMOTE when configured
1908
    (network track) and otherwise a local bare remote (core-equivalent track);
1909
    oak uses the disposable fleet remote or emits a skip row. Transport is
1910
    recorded on every row; never delta across transports."""
1911
    mode = "clone_push_storm"
1912
    bench_id = str(metadata.get("bench_id", "bench"))
1913
    vcs = str(subject.bin)
1914
    lane_root = run_root / f"cp-{subject.name}-w{workers}-r{run_index}"
1915
    lane_root.mkdir(parents=True, exist_ok=True)
1916
1917
    if subject.kind == "git":
1918
        network = resolve_git_github_remote()
1919
        if network.resolved:
1920
            remote = network
1921
        else:
1922
            seeded = seed_git_bare_remote(subject, fixture, lane_root)
1923
            if isinstance(seeded, str):
1924
                return [mode_error_row(metadata, subject, mode, workers, run_index, seeded)]
1925
            remote, _seed = seeded
1926
    else:
1927
        remote = resolve_oak_remote("fleet")
1928
        if not remote.resolved:
1929
            return [
1930
                mode_skip_row(metadata, subject, mode, workers, run_index, reason=remote.skip_reason)
1931
            ]
1932
    remote_fields = {**remote.row_fields(), "workspace_transport": remote.transport}
1933
    scenario_name = f"contention_{mode}_w{workers}"
1934
    branch_prefix = disposable_branch(bench_id, scenario_name, subject.name, run_index)
1935
1936
    states: list[dict[str, Any]] = [
1937
        {
1938
            "worker": index,
1939
            "elapsed_ms": 0.0,
1940
            "clone_ms": None,
1941
            "commit_ms": None,
1942
            "push_ms": None,
1943
            "clone_ok": False,
1944
            "commit_ok": False,
1945
            "push_ok": False,
1946
            "stderr": "",
1947
            "stdout": "",
1948
            "failure_reason": None,
1949
            "failed_command": None,
1950
            "errors": [],
1951
        }
1952
        for index in range(workers)
1953
    ]
1954
1955
    def storm(index: int) -> None:
1956
        state = states[index]
1957
        start = time.perf_counter()
1958
        try:
1959
            wdir = lane_root / f"w{index:03d}"
1960
            clone_start = time.perf_counter()
1961
            proc = run([vcs, "clone", str(remote.repo), str(wdir)], lane_root, timeout=600.0)
1962
            state["clone_ms"] = round((time.perf_counter() - clone_start) * 1000, 3)
1963
            if proc.returncode != 0:
1964
                state["stderr"] = proc.stderr.strip()[:400]
1965
                state["stdout"] = proc.stdout.strip()[:400]
1966
                state["failure_reason"] = "clone_failed"
1967
                state["failed_command"] = [vcs, "clone", str(remote.repo), str(wdir)]
1968
                state["errors"].append(f"clone failed: {proc.stderr.strip()[:200]}")
1969
                return
1970
            state["clone_ok"] = True
1971
            rel_path = (
1972
                f"workers/{bench_id}/clone-push/{subject.name}/w{workers}/r{run_index}/w{index:03d}.txt"
1973
            )
1974
            payload = f"clone-push worker={index} nonce={index * 100003}\n"
1975
            target = wdir / rel_path
1976
            target.parent.mkdir(parents=True, exist_ok=True)
1977
            target.write_text(payload)
1978
            commit_start = time.perf_counter()
1979
            committed = True
1980
            for command in snapshot_commands(subject, f"clone-push w{index}"):
1981
                proc = run(command, wdir, timeout=300.0)
1982
                if proc.returncode != 0:
1983
                    state["stderr"] = proc.stderr.strip()[:400]
1984
                    state["stdout"] = proc.stdout.strip()[:400]
1985
                    state["failure_reason"] = "commit_failed"
1986
                    state["failed_command"] = command
1987
                    state["errors"].append(f"commit failed: {proc.stderr.strip()[:200]}")
1988
                    committed = False
1989
                    break
1990
            state["commit_ms"] = round((time.perf_counter() - commit_start) * 1000, 3)
1991
            if not committed:
1992
                return
1993
            state["commit_ok"] = True
1994
            if subject.kind == "git":
1995
                push_command = [vcs, "push", "origin", f"HEAD:refs/heads/{branch_prefix}-w{index:03d}"]
1996
            else:
1997
                push_command = [vcs, "push"]
1998
            push_start = time.perf_counter()
1999
            proc = run(push_command, wdir, timeout=600.0)
2000
            state["push_ms"] = round((time.perf_counter() - push_start) * 1000, 3)
2001
            if proc.returncode != 0:
2002
                state["stderr"] = proc.stderr.strip()[:400]
2003
                state["stdout"] = proc.stdout.strip()[:400]
2004
                state["failure_reason"] = "push_failed"
2005
                state["failed_command"] = push_command
2006
                state["errors"].append(f"push failed: {proc.stderr.strip()[:200]}")
2007
                return
2008
            state["push_ok"] = True
2009
        except Exception as exc:  # noqa: BLE001 - recorded, not hidden
2010
            state["errors"].append(f"worker exception: {type(exc).__name__}: {exc}"[:200])
2011
        finally:
2012
            state["elapsed_ms"] = (time.perf_counter() - start) * 1000
2013
2014
    threads = [threading.Thread(target=storm, args=(index,)) for index in range(workers)]
2015
    wall_start = time.perf_counter()
2016
    for thread in threads:
2017
        thread.start()
2018
    for thread in threads:
2019
        thread.join()
2020
    wall_ms = (time.perf_counter() - wall_start) * 1000
2021
2022
    rows: list[dict[str, Any]] = []
2023
    for state in states:
2024
        row = base_row(metadata, subject, mode, workers, run_index)
2025
        row.update(
2026
            {
2027
                "operation": "parallel.worker",
2028
                "worker": state["worker"],
2029
                "elapsed_ms": round(state["elapsed_ms"], 3),
2030
                "returncode": 0 if state["push_ok"] else 1,
2031
                "clone_ms": state["clone_ms"],
2032
                "commit_ms": state["commit_ms"],
2033
                "push_ms": state["push_ms"],
2034
                # Measured completed-op counts, per ADR-0002 observed zeros
2035
                # (never null): a worker that completed no push is STARVED in
2036
                # fleet_report's completed-op accounting, not unmeasured.
2037
                "clones_succeeded": 1 if state["clone_ok"] else 0,
2038
                "pushes_succeeded": 1 if state["push_ok"] else 0,
2039
                "stderr": state["stderr"],
2040
                "stdout": state["stdout"],
2041
                "failure_reason": state["failure_reason"],
2042
                "command": state["failed_command"],
2043
                "error_examples": state["errors"],
2044
                **remote_fields,
2045
            }
2046
        )
2047
        rows.append(row)
2048
2049
    pushes_succeeded = sum(1 for state in states if state["push_ok"])
2050
    clones_succeeded = sum(1 for state in states if state["clone_ok"])
2051
    clone_samples = [state["clone_ms"] for state in states if state["clone_ms"] is not None]
2052
    push_samples = [state["push_ms"] for state in states if state["push_ms"] is not None]
2053
    total = base_row(metadata, subject, mode, workers, run_index)
2054
    total.update(
2055
        {
2056
            "operation": "parallel.total",
2057
            "elapsed_ms": round(wall_ms, 3),
2058
            "returncode": 0 if pushes_succeeded == workers else 1,
2059
            "clones_succeeded": clones_succeeded,
2060
            "pushes_succeeded": pushes_succeeded,
2061
            "clone_latency_tail": tail_latency_summary(clone_samples),
2062
            "push_latency_tail": tail_latency_summary(push_samples),
2063
            "parallel_metrics": {
2064
                "tasks_total": workers,
2065
                "tasks_completed": pushes_succeeded,
2066
                "max_parallel_tasks": workers,
2067
                "overlapping_files_count": 0,
2068
                "lost_updates_detected": None,
2069
                "lock_wait_ms": None,
2070
                "commit_throughput_per_s": round(pushes_succeeded / (wall_ms / 1000.0), 3) if wall_ms else None,
2071
                "integrity_check_passed": pushes_succeeded == workers,
2072
                "measurement_source": "push_success_count_against_single_remote",
2073
            },
2074
            **remote_fields,
2075
        }
2076
    )
2077
    rows.append(total)
2078
    return rows
2079
2080
2081
def run_long_divergence(
2082
    subject: Subject,
2083
    fixture: Path,
2084
    divergence_k: int,
2085
    run_root: Path,
2086
    run_index: int,
2087
    metadata: dict[str, Any],
2088
) -> list[dict[str, Any]]:
2089
    """One branch accumulates K commits while main advances, then merges:
2090
    a single point on the merge-cost-vs-divergence curve. K is part of the
2091
    scenario name (contention_long_divergence_k<K>, ADR-0005); the workers
2092
    field is 1 (one diverging branch), never the tier loop."""
2093
    mode = "long_divergence"
2094
    scenario = f"contention_long_divergence_k{divergence_k}"
2095
    if subject.kind != "git":
2096
        return [fleet_mode_subject_skip(metadata, subject, mode, 1, run_index, scenario=scenario)]
2097
    vcs = str(subject.bin)
2098
    repo = run_root / f"ld-{subject.name}-k{divergence_k}-r{run_index}"
2099
    shutil.copytree(fixture, repo)
2100
    if not init_repo(subject, repo):
2101
        row = mode_error_row(metadata, subject, mode, 1, run_index, "repo init failed")
2102
        row["scenario"] = scenario
2103
        row["divergence_k"] = divergence_k
2104
        return [row]
2105
2106
    wall_start = time.perf_counter()
2107
    proc = run([vcs, "switch", "-c", "diverge"], repo)
2108
    if proc.returncode != 0:
2109
        row = mode_error_row(metadata, subject, mode, 1, run_index, f"branch create failed: {proc.stderr.strip()[:200]}")
2110
        row["scenario"] = scenario
2111
        row["divergence_k"] = divergence_k
2112
        return [row]
2113
2114
    build_start = time.perf_counter()
2115
    commit_ms_samples: list[float] = []
2116
    build_failures = 0
2117
    for k in range(divergence_k):
2118
        target = repo / "divergence" / f"d{k:05d}.txt"
2119
        target.parent.mkdir(parents=True, exist_ok=True)
2120
        target.write_text(f"divergence commit {k}\n")
2121
        commit_start = time.perf_counter()
2122
        for command in snapshot_commands(subject, f"diverge {k}"):
2123
            if run(command, repo).returncode != 0:
2124
                build_failures += 1
2125
                break
2126
        commit_ms_samples.append(round((time.perf_counter() - commit_start) * 1000, 3))
2127
    build_ms = (time.perf_counter() - build_start) * 1000
2128
2129
    run([vcs, "switch", "main"], repo)
2130
    for j in range(LONG_DIVERGENCE_MAIN_COMMITS):
2131
        target = repo / "mainline" / f"m{j:03d}.txt"
2132
        target.parent.mkdir(parents=True, exist_ok=True)
2133
        target.write_text(f"mainline commit {j}\n")
2134
        for command in snapshot_commands(subject, f"mainline {j}"):
2135
            run(command, repo)
2136
2137
    merge_start = time.perf_counter()
2138
    merge = run([vcs, "merge", "--no-edit", "diverge"], repo, timeout=600.0)
2139
    merge_ms = (time.perf_counter() - merge_start) * 1000
2140
    merge_conflict = merge.returncode != 0
2141
    if merge_conflict:
2142
        run([vcs, "merge", "--abort"], repo)
2143
    wall_ms = (time.perf_counter() - wall_start) * 1000
2144
2145
    fsck = run([vcs, "fsck", "--no-progress"], repo)
2146
    integrity_passed = fsck.returncode == 0 and not merge_conflict and build_failures == 0
2147
2148
    row = base_row(metadata, subject, mode, 1, run_index)
2149
    row.update(
2150
        {
2151
            "scenario": scenario,
2152
            "operation": "parallel.total",
2153
            "elapsed_ms": round(wall_ms, 3),
2154
            "returncode": 0 if integrity_passed else 1,
2155
            "divergence_k": divergence_k,
2156
            "main_side_commits": LONG_DIVERGENCE_MAIN_COMMITS,
2157
            "branch_build_ms": round(build_ms, 3),
2158
            "branch_commit_ms_mean": (
2159
                round(sum(commit_ms_samples) / len(commit_ms_samples), 3) if commit_ms_samples else None
2160
            ),
2161
            "build_failures": build_failures,
2162
            "merge_ms": round(merge_ms, 3),
2163
            "merge_conflict": merge_conflict,
2164
            "merge_cost_ms_per_commit": round(merge_ms / divergence_k, 3) if divergence_k else None,
2165
            "parallel_metrics": {
2166
                "tasks_total": divergence_k,
2167
                "tasks_completed": divergence_k - build_failures,
2168
                "max_parallel_tasks": 1,
2169
                "overlapping_files_count": 0,
2170
                "lost_updates_detected": None,
2171
                "lock_wait_ms": None,
2172
                "commit_throughput_per_s": None,
2173
                "integrity_check_passed": integrity_passed,
2174
                "measurement_source": "git_fsck_after_divergent_merge",
2175
            },
2176
        }
2177
    )
2178
    return [row]
2179
2180
2181
# ---------------------------------------------------------------------------
2182
# integration_landing (oakbench.landing): does what lands on main work?
2183
2184
def _free_port() -> int:
2185
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
2186
        sock.bind(("127.0.0.1", 0))
2187
        return sock.getsockname()[1]
2188
2189
2190
def _start_oak_serve(subject: Subject, data_dir: Path, log_path: Path) -> tuple[subprocess.Popen, str] | str:
2191
    """Untimed: a private `oak serve` on loopback (no accounts, no CI)."""
2192
    port = _free_port()  # small bind race; a stray listener would fail the seed push loudly
2193
    with log_path.open("w") as log:
2194
        proc = subprocess.Popen([str(subject.bin), "serve", "-d", str(data_dir), "-p", str(port)],
2195
                                env=base_env(), stdout=log, stderr=subprocess.STDOUT)
2196
    deadline = time.monotonic() + 30
2197
    while time.monotonic() < deadline:
2198
        if proc.poll() is not None:
2199
            return f"oak serve exited {proc.returncode} (see {log_path})"
2200
        try:
2201
            with socket.create_connection(("127.0.0.1", port), timeout=0.5):
2202
                return proc, f"http://127.0.0.1:{port}"
2203
        except OSError:
2204
            time.sleep(0.1)
2205
    proc.terminate()
2206
    try:
2207
        proc.wait(timeout=10)
2208
    except subprocess.TimeoutExpired:
2209
        proc.kill()
2210
    return f"oak serve did not listen within 30s (see {log_path})"
2211
2212
2213
def _looks_like_conflict(proc: subprocess.CompletedProcess[str]) -> bool:
2214
    text = (proc.stdout + proc.stderr).lower()
2215
    return "conflict" in text
2216
2217
2218
def _land_attempt_cap(workers: int) -> int:
2219
    # Each rejection means another agent landed, so a fair agent may need up
2220
    # to `workers` attempts; the cap is generous so it never decides a run.
2221
    return max(MAX_LAND_ATTEMPTS, 2 * workers + 4)
2222
2223
2224
def _looks_like_stale_main(proc: subprocess.CompletedProcess[str]) -> bool:
2225
    """A rejection because another agent landed first (retrying is fair)."""
2226
    text = (proc.stdout + proc.stderr).lower()
2227
    return any(hint in text for hint in ("rejected", "fetch first", "non-fast-forward", "cannot lock ref",
2228
                                         "out of date", "stale", "has moved", "not up to date"))
2229
2230
2231
def _git_land(vcs: str, wdir: Path, state: dict[str, Any], cap: int) -> None:
2232
    """Careful agent on git: rebase onto main, test, fast-forward push."""
2233
    while state["land_attempts"] < cap:
2234
        state["land_attempts"] += 1
2235
        run([vcs, "fetch", "origin", "main"], wdir, timeout=300.0)
2236
        rebase = run([vcs, "rebase", "origin/main"], wdir, timeout=300.0)
2237
        if rebase.returncode != 0:
2238
            run([vcs, "rebase", "--abort"], wdir)
2239
            state["outcome"] = landing.CONFLICT_REPORTED if _looks_like_conflict(rebase) else landing.LAND_FAILED
2240
            state["errors"].append(f"rebase: {(rebase.stdout + rebase.stderr).strip()[:200]}")
2241
            return
2242
        tests = landing.run_tests(wdir)
2243
        state["tests_run"] += 1
2244
        if tests is not True:
2245
            state["outcome"] = landing.REFUSED_TESTS if tests is False else landing.LAND_FAILED
2246
            return
2247
        push = run([vcs, "push", "origin", "HEAD:main"], wdir, timeout=300.0)
2248
        if push.returncode == 0:
2249
            state["outcome"] = landing.LANDED
2250
            return
2251
        state["errors"].append(f"push: {push.stderr.strip()[:200]}")
2252
        if not _looks_like_stale_main(push):
2253
            state["outcome"] = landing.LAND_FAILED  # not contention: do not retry a broken push
2254
            return
2255
    state["outcome"] = landing.ATTEMPT_CAP
2256
2257
2258
def _oak_land(vcs: str, wdir: Path, state: dict[str, Any], cap: int) -> None:
2259
    """Careful agent on oak: pull main into the branch, test, `oak merge`."""
2260
    while state["land_attempts"] < cap:
2261
        state["land_attempts"] += 1
2262
        pull = run([vcs, "pull"], wdir, timeout=300.0)
2263
        if pull.returncode != 0 or _looks_like_conflict(pull):
2264
            run([vcs, "pull", "--abort"], wdir)
2265
            state["outcome"] = landing.CONFLICT_REPORTED if _looks_like_conflict(pull) else landing.LAND_FAILED
2266
            state["errors"].append(f"pull: {(pull.stdout + pull.stderr).strip()[:200]}")
2267
            return
2268
        commit = run([vcs, "commit", "--no-verify"], wdir)  # record any merge result
2269
        if commit.returncode != 0 and "nothing to commit" not in (commit.stdout + commit.stderr).lower():
2270
            # Tests would run on a tree that `oak merge` does not push.
2271
            state["outcome"] = landing.LAND_FAILED
2272
            state["errors"].append(f"commit after pull: {(commit.stdout + commit.stderr).strip()[:200]}")
2273
            return
2274
        tests = landing.run_tests(wdir)
2275
        state["tests_run"] += 1
2276
        if tests is not True:
2277
            state["outcome"] = landing.REFUSED_TESTS if tests is False else landing.LAND_FAILED
2278
            return
2279
        merge = run([vcs, "merge", "--json"], wdir, timeout=300.0)
2280
        if merge.returncode == 0:
2281
            state["outcome"] = landing.LANDED
2282
            return
2283
        if _looks_like_conflict(merge):
2284
            state["outcome"] = landing.CONFLICT_REPORTED
2285
            state["errors"].append(f"merge: {(merge.stdout + merge.stderr).strip()[:200]}")
2286
            return
2287
        state["errors"].append(f"merge: {(merge.stdout + merge.stderr).strip()[:200]}")
2288
        if not _looks_like_stale_main(merge):
2289
            state["outcome"] = landing.LAND_FAILED  # not contention: do not retry a broken merge
2290
            return
2291
    state["outcome"] = landing.ATTEMPT_CAP
2292
2293
2294
def run_integration_landing(
2295
    subject: Subject,
2296
    fixture: Path,
2297
    workers: int,
2298
    commits: int,
2299
    run_root: Path,
2300
    run_index: int,
2301
    metadata: dict[str, Any],
2302
) -> list[dict[str, Any]]:
2303
    """N careful agents land on one main at once (oakbench.landing). The
2304
    oracle is the final main: every landed change present, tests green, and
2305
    the designed semantic and text conflicts surfaced rather than landed."""
2306
    mode = "integration_landing"
2307
    if workers < landing.MIN_WORKERS:
2308
        return [mode_skip_row(metadata, subject, mode, workers, run_index,
2309
                              reason=f"integration_landing_needs_{landing.MIN_WORKERS}_workers")]
2310
    vcs = str(subject.bin)
2311
    lane_root = run_root / f"il-{subject.name}-w{workers}-r{run_index}"
2312
    lane_root.mkdir(parents=True, exist_ok=True)
2313
    base = lane_root / "base"
2314
    landing.make_landing_fixture(base)
2315
    server: subprocess.Popen | None = None
2316
    try:
2317
        if subject.kind == "git":
2318
            seeded = seed_git_bare_remote(subject, base, lane_root)
2319
            if isinstance(seeded, str):
2320
                return [mode_error_row(metadata, subject, mode, workers, run_index, seeded)]
2321
            remote, _seed = seeded
2322
            clone_source = remote.repo
2323
            remote_fields = remote.row_fields()
2324
        else:
2325
            started = _start_oak_serve(subject, lane_root / "oak-serve-data", lane_root / "oak-serve.log")
2326
            if isinstance(started, str):
2327
                return [mode_error_row(metadata, subject, mode, workers, run_index, started)]
2328
            server, url = started
2329
            seed = lane_root / "seed"
2330
            shutil.copytree(base, seed)
2331
            for command in ([vcs, "init", "."], [vcs, "commit", "--no-verify"],
2332
                            [vcs, "push", "-r", url, "--repo", "bench/landing"], [vcs, "merge"]):
2333
                proc = run(command, seed, timeout=300.0)
2334
                if proc.returncode != 0:
2335
                    return [mode_error_row(metadata, subject, mode, workers, run_index,
2336
                                           f"oak seed `{' '.join(command[1:])}` failed: {proc.stderr.strip()[:200]}")]
2337
            clone_source = f"{url}/bench/landing"
2338
            remote_fields = {"remote_repo": "bench/landing", "remote_transport": "network",
2339
                             "remote_server": "oak-serve-loopback"}
2340
2341
        states: list[dict[str, Any]] = [
2342
            {"worker": index, "role": landing.role_for(index), "outcome": None, "markers": [],
2343
             "land_attempts": 0, "tests_run": 0, "land_ms": None, "elapsed_ms": 0.0, "errors": []}
2344
            for index in range(workers)
2345
        ]
2346
        barrier = threading.Barrier(workers)
2347
2348
        def agent(index: int) -> None:
2349
            state = states[index]
2350
            start = time.perf_counter()
2351
            ready = False
2352
            try:
2353
                wdir = lane_root / f"w{index:03d}"
2354
                proc = run([vcs, "clone", clone_source, str(wdir)], lane_root, timeout=300.0)
2355
                if proc.returncode != 0:
2356
                    state["errors"].append(f"clone: {proc.stderr.strip()[:200]}")
2357
                elif subject.kind != "git" and run([vcs, "start", f"landing worker {index}", "--no-watch"],
2358
                                                   wdir, timeout=300.0).returncode != 0:
2359
                    state["errors"].append("oak start failed")
2360
                else:
2361
                    state["markers"] = landing.apply_role(index, wdir)
2362
                    if landing.run_tests(wdir) is not True:
2363
                        state["outcome"] = landing.PRE_TEST_FAILED
2364
                    else:
2365
                        commands = (snapshot_commands(subject, f"landing worker {index}") if subject.kind == "git"
2366
                                    else [[vcs, "commit", "--no-verify"]])
2367
                        ready = all(run(command, wdir).returncode == 0 for command in commands)
2368
                        if not ready:
2369
                            state["errors"].append("local commit failed")
2370
            except Exception as exc:  # noqa: BLE001 - recorded, not hidden
2371
                state["errors"].append(f"worker exception: {type(exc).__name__}: {exc}"[:200])
2372
            try:
2373
                barrier.wait(timeout=900)  # every agent starts landing at once
2374
            except threading.BrokenBarrierError:
2375
                state["errors"].append("barrier broken")
2376
            if ready:
2377
                land_start = time.perf_counter()
2378
                try:
2379
                    (_git_land if subject.kind == "git" else _oak_land)(vcs, lane_root / f"w{index:03d}", state,
2380
                                                                       _land_attempt_cap(workers))
2381
                except Exception as exc:  # noqa: BLE001
2382
                    state["outcome"] = landing.LAND_FAILED
2383
                    state["errors"].append(f"land exception: {type(exc).__name__}: {exc}"[:200])
2384
                state["land_ms"] = round((time.perf_counter() - land_start) * 1000, 3)
2385
            elif state["outcome"] is None:
2386
                state["outcome"] = landing.LAND_FAILED
2387
            state["elapsed_ms"] = (time.perf_counter() - start) * 1000
2388
2389
        threads = [threading.Thread(target=agent, args=(index,)) for index in range(workers)]
2390
        wall_start = time.perf_counter()
2391
        for thread in threads:
2392
            thread.start()
2393
        for thread in threads:
2394
            thread.join()
2395
        wall_ms = (time.perf_counter() - wall_start) * 1000
2396
2397
        # Oracle: a fresh clone of main. Markers through the committed-state
2398
        # reader (independent for oak); tests and markers on the checkout.
2399
        verify = lane_root / "verify"
2400
        clone = run([vcs, "clone", clone_source, str(verify)], lane_root, timeout=300.0)
2401
        present: dict[int, bool | None] = {}
2402
        main_tests: bool | None = None
2403
        markers_on_main: bool | None = None
2404
        verify_error = None
2405
        if clone.returncode == 0:
2406
            main_tests = landing.run_tests(verify)
2407
            markers_on_main = landing.has_conflict_markers(verify)
2408
            for state in states:
2409
                try:
2410
                    present[state["worker"]] = all(
2411
                        (content := tree_payload(subject, verify, rel)) is not None and marker in content
2412
                        for rel, marker in state["markers"]) if state["markers"] else None
2413
                except CommittedStateUnmeasured as exc:
2414
                    present[state["worker"]] = None
2415
                    verify_error = str(exc)[:200]
2416
        else:
2417
            verify_error = f"verify clone failed: {clone.stderr.strip()[:200]}"
2418
        verdict = landing.classify(states, main_tests, markers_on_main, present)
2419
        # oak serve has no CI; hosted Oak gates merges on CI (not measured here).
2420
        verdict["server_ci_gate"] = False if subject.kind != "git" else None
2421
    finally:
2422
        if server is not None:
2423
            server.terminate()
2424
            try:
2425
                server.wait(timeout=10)
2426
            except subprocess.TimeoutExpired:
2427
                server.kill()
2428
2429
    integration = ("fast-forward-only push: the landed tree is the tree the agent tested" if subject.kind == "git"
2430
                   else "server squash-merge (oak serve: no CI gate): main may move between the agent's test and the merge")
2431
    rows: list[dict[str, Any]] = []
2432
    for state in states:
2433
        row = base_row(metadata, subject, mode, workers, run_index)
2434
        row.update({
2435
            "operation": "parallel.worker",
2436
            "worker": state["worker"],
2437
            "role": state["role"],
2438
            "elapsed_ms": round(state["elapsed_ms"], 3),
2439
            "returncode": 0 if state["outcome"] in (landing.LANDED, landing.REFUSED_TESTS,
2440
                                                    landing.CONFLICT_REPORTED) else 1,
2441
            # Clone, edit, pre-test and barrier wait included; land_latency_ms is the land itself.
2442
            "elapsed_scope": "worker_setup_plus_barrier_plus_land",
2443
            "land_outcome": state["outcome"],
2444
            "land_attempts": state["land_attempts"],
2445
            "tests_run_before_land": state["tests_run"],
2446
            "land_latency_ms": state["land_ms"],
2447
            "markers_on_main": present.get(state["worker"]),
2448
            "error_examples": state["errors"][:5],
2449
            **remote_fields,
2450
        })
2451
        rows.append(row)
2452
    total = base_row(metadata, subject, mode, workers, run_index)
2453
    clean = (verdict["silent_failures"] == 0 and verdict["final_main_tests_pass"] is True
2454
             and not any(state["outcome"] in (landing.LAND_FAILED, landing.PRE_TEST_FAILED, landing.ATTEMPT_CAP)
2455
                         for state in states))
2456
    total.update({
2457
        "operation": "parallel.total",
2458
        "elapsed_ms": round(wall_ms, 3),
2459
        # 1 = main ended wrong or a land failed; 77 = the oracle could not run.
2460
        "returncode": SKIP_RETURNCODE if verdict["silent_failures"] is None else (0 if clean else 1),
2461
        "integration_model": integration,
2462
        "land_protocol": "integrate latest main, run tests, land only if green; retry on rejection",
2463
        "landing": verdict,
2464
        "oracle_error": verify_error,
2465
        # Rejected-and-retried lands: the cost git pays to keep main tested.
2466
        "retries_total": sum(max(0, state["land_attempts"] - 1) for state in states),
2467
        "parallel_metrics": {
2468
            "tasks_total": workers,
2469
            # Not a completion rate: refusing to land a broken combination is correct.
2470
            "tasks_landed": verdict["workers_landed"],
2471
            "measurement_source": "fresh_clone_of_main_tests_plus_committed_markers",
2472
        },
2473
        **remote_fields,
2474
    })
2475
    rows.append(total)
2476
    return rows
2477
2478
2479
MODE_RUNNERS = {
2480
    "shared_checkout": run_shared_checkout,
2481
    "workspace_per_task": run_workspace_per_task,
2482
    "merge_train": run_merge_train,
2483
    "rebase_storm": run_rebase_storm,
2484
    "mixed_fleet": run_mixed_fleet,
2485
    "conflict_storm": run_conflict_storm,
2486
    "clone_push_storm": run_clone_push_storm,
2487
    "integration_landing": run_integration_landing,
2488
}
2489
2490
2491
def remote_preflight_requirements(
2492
    subjects: list[Subject],
2493
    modes: list[str],
2494
    worker_levels: list[int],
2495
) -> list[RemoteRequirement]:
2496
    if not any(subject.kind == "oak" for subject in subjects):
2497
        return []
2498
    operations: list[str] = []
2499
    if "workspace_per_task" in modes:
2500
        operations.extend(f"contention_workspace_per_task_w{workers}/parallel.total" for workers in worker_levels)
2501
    if "clone_push_storm" in modes:
2502
        operations.extend(f"contention_clone_push_storm_w{workers}/parallel.total" for workers in worker_levels)
2503
    if not operations:
2504
        return []
2505
    return [
2506
        RemoteRequirement(
2507
            purpose="fleet",
2508
            lane="contention",
2509
            operations=tuple(operations),
2510
        )
2511
    ]
2512
2513
2514
def summary_text(rows: list[dict[str, Any]]) -> str:
2515
    totals = [row for row in rows if row.get("operation") == "parallel.total"]
2516
    lines = [
2517
        "# Parallel Contention Summary",
2518
        "",
2519
        "Throughput is successful snapshots per second across all workers. Lock wait is the",
2520
        "summed time workers spent in failed snapshot attempts and retry sleeps.",
2521
        "A skip row (returncode 77) means the mode is not yet runnable for that subject.",
2522
        "",
2523
        "workspace_per_task transport asymmetry: oak workspaces are network-backed mounts",
2524
        "(setup/publish/merge cross a real server), git worktrees are local disk. Same-table",
2525
        "rows are presented side by side but are different transports — never compute a",
2526
        "git-vs-oak delta on setup/merge timings here. Oak marginal disk is allocated bytes",
2527
        "(lazy hydration); git marginal disk is a full worktree checkout.",
2528
        "",
2529
        "| Scenario | Subject | Workers | Wall ms | Throughput/s | Lock wait ms | Retries | Lost updates | Integrity | Marginal ws KB |",
2530
        "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | ---: |",
2531
    ]
2532
    landing_rows = [row for row in totals if row.get("contention_mode") == "integration_landing"]
2533
    for row in totals:
2534
        if row.get("contention_mode") == "integration_landing":
2535
            continue  # its own table below; wall clock is not its measurement
2536
        if row.get("skipped"):
2537
            lines.append(
2538
                f"| `{row['scenario']}` | `{row['subject']}` | {row['workers']} | skipped | | | | | {row['skip_reason'][:60]}… | |"
2539
            )
2540
            continue
2541
        metrics = row.get("parallel_metrics", {})
2542
        integrity = metrics.get("integrity_check_passed")
2543
        lines.append(
2544
            f"| `{row['scenario']}` | `{row['subject']}` | {row['workers']} | "
2545
            f"{row['elapsed_ms']:.0f} | "
2546
            f"{metrics.get('commit_throughput_per_s') if metrics.get('commit_throughput_per_s') is not None else 'unmeasured'} | "
2547
            f"{metrics.get('lock_wait_ms', 'unmeasured')} | "
2548
            f"{row.get('retries_total', 0)} | "
2549
            f"{metrics.get('lost_updates_detected') if metrics.get('lost_updates_detected') is not None else 'unmeasured'} | "
2550
            f"{'pass' if integrity else ('FAIL' if integrity is False else 'unmeasured')} | "
2551
            f"{row.get('marginal_workspace_disk_kb', '')} |"
2552
        )
2553
    if landing_rows:
2554
        lines += [
2555
            "",
2556
            "## Integration landing",
2557
            "",
2558
            "Careful agents (integrate main, test, land only if green) land at once. The",
2559
            "measurement is whether main ends correct, not speed. Oak here is `oak serve`",
2560
            "(no CI gate); git is a local bare remote. Never compare wall clock across them.",
2561
            "",
2562
            "| Scenario | Subject | Run | Main tests | Silent failures | Semantic conflict | Text conflict | Landed | Land retries |",
2563
            "| --- | --- | ---: | --- | ---: | --- | --- | ---: | ---: |",
2564
        ]
2565
        for row in landing_rows:
2566
            if row.get("skipped"):
2567
                lines.append(f"| `{row['scenario']}` | `{row['subject']}` | {row['run']} | skipped: "
2568
                             f"{row.get('skip_reason', '')[:50]} | | | | | |")
2569
                continue
2570
            verdict = row.get("landing") or {}
2571
            tests = verdict.get("final_main_tests_pass")
2572
2573
            def shown(value):
2574
                return "unmeasured" if value is None else value
2575
            lines.append(
2576
                f"| `{row['scenario']}` | `{row['subject']}` | {row['run']} | "
2577
                f"{'pass' if tests else ('FAIL' if tests is False else 'unmeasured')} | "
2578
                f"{shown(verdict.get('silent_failures'))} | {shown(verdict.get('semantic_conflict_outcome'))} | "
2579
                f"{shown(verdict.get('text_conflict_outcome'))} | {shown(verdict.get('workers_landed'))} | "
2580
                f"{shown(row.get('retries_total'))} |")
2581
    return "\n".join(lines) + "\n"
2582
2583
2584
def main() -> int:
2585
    args = parse_args()
2586
    subjects = load_subjects(args)
2587
    worker_levels = [int(item) for item in args.workers.split(",") if item.strip()]
2588
    modes = [item.strip() for item in args.modes.split(",") if item.strip()]
2589
    unknown_modes = [mode for mode in modes if mode not in MODES]
2590
    if unknown_modes:
2591
        raise SystemExit("Unknown modes: " + ", ".join(unknown_modes) + f". Valid: {', '.join(MODES)}")
2592
    divergence_ks = [int(item) for item in args.divergence_k.split(",") if item.strip()]
2593
    if any(k <= 0 for k in divergence_ks):
2594
        raise SystemExit("--divergence-k values must be positive integers")
2595
    print_remote_preflight_warnings(
2596
        oak_remote_preflight_warnings(
2597
            remote_preflight_requirements(subjects, modes, worker_levels)
2598
        )
2599
    )
2600
2601
    timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
2602
    args.results.mkdir(parents=True, exist_ok=True)
2603
    args.workdir.mkdir(parents=True, exist_ok=True)
2604
    run_root = args.workdir / "runs" / timestamp
2605
    run_root.mkdir(parents=True, exist_ok=True)
2606
    fixture = args.workdir / "fixtures" / "contention"
2607
    make_fixture(fixture)
2608
2609
    metadata = {
2610
        "bench_id": timestamp,
2611
        "profile": "parallel-contention",
2612
        "timestamp_utc": timestamp,
2613
        "host": platform.node(),
2614
        "platform": platform.platform(),
2615
        "machine": platform.machine(),
2616
        "python": platform.python_version(),
2617
        "env_isolation_version": ENV_ISOLATION_VERSION,
2618
        "subject_versions": subject_versions(subjects),
2619
        "subject_details": subject_details(subjects),
2620
        "source": source_metadata(args.oak_repo),
2621
        "commits_per_worker": args.commits_per_worker,
2622
    }
2623
2624
    rows: list[dict[str, Any]] = []
2625
    # Crash insurance: every completed combo flushes to a .partial.jsonl so a
2626
    # campaign killed an hour in keeps its finished rows. The canonical file
2627
    # is still the validated ResultsStore write; the partial is finalized
2628
    # (removed) by store.write() only after the canonical write succeeds.
2629
    store = ResultsStore(args.results, lane="contention", flush_partial=True)
2630
    with measurement_lock("parallel_contention") as lock_info:
2631
        metadata["measurement_lock_wait_ms"] = lock_info.wait_ms
2632
        metadata["measurement_lock"] = "held" if lock_info.enabled else "disabled"
2633
        for run_index in range(args.runs):
2634
            for workers in worker_levels:
2635
                for mode in modes:
2636
                    if mode == "long_divergence":
2637
                        continue  # tiered by K, not workers; handled below
2638
                    for subject in subjects:
2639
                        print(f"[run] mode={mode} workers={workers} subject={subject.name} run={run_index}", flush=True)
2640
                        runner = MODE_RUNNERS[mode]
2641
                        combo_rows = runner(
2642
                            subject, fixture, workers, args.commits_per_worker, run_root, run_index, metadata
2643
                        )
2644
                        rows.extend(combo_rows)
2645
                        store.append_partial(timestamp, combo_rows)
2646
            if "long_divergence" in modes:
2647
                for divergence_k in divergence_ks:
2648
                    for subject in subjects:
2649
                        print(f"[run] mode=long_divergence k={divergence_k} subject={subject.name} run={run_index}", flush=True)
2650
                        combo_rows = run_long_divergence(
2651
                            subject, fixture, divergence_k, run_root, run_index, metadata
2652
                        )
2653
                        rows.extend(combo_rows)
2654
                        store.append_partial(timestamp, combo_rows)
2655
2656
    raw_path, summary_path = store.write(timestamp, rows, summary_text(rows))
2657
2658
    if not args.keep_workdirs:
2659
        shutil.rmtree(run_root, ignore_errors=True)
2660
2661
    print(f"[result] {raw_path}")
2662
    print(f"[summary] {summary_path}")
2663
    failures = [
2664
        row
2665
        for row in rows
2666
        if row.get("operation") == "parallel.total"
2667
        and row_returncode(row) not in (0, SKIP_RETURNCODE)
2668
    ]
2669
    return 1 if failures else 0
2670
2671
2672
if __name__ == "__main__":
2673
    raise SystemExit(main())