sidefx 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sidefx/chaos.py ADDED
@@ -0,0 +1,2805 @@
1
+ """Automated chaos fault-injection evaluation harness for sidefx.
2
+
3
+ Exercises real local HTTP mock GitHub servers, real local bare git repositories with
4
+ fault-injecting hooks, real subprocess stdio MCP servers, and multi-process CLI races
5
+ across all 6 critical side-effect failure windows using Python stdlib only.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import contextlib
12
+ import io
13
+ import json
14
+ import os
15
+ import shlex
16
+ import signal
17
+ import stat
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ import textwrap
22
+ import threading
23
+ import time
24
+ import traceback
25
+ from collections.abc import Callable, Iterator, Sequence
26
+ from dataclasses import dataclass
27
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
28
+ from pathlib import Path
29
+ from typing import Any
30
+ from urllib.parse import parse_qs, urlsplit
31
+
32
+ from sidefx.config import (
33
+ PreflightConfig,
34
+ PreflightRule,
35
+ SidefxConfig,
36
+ default_config_dict,
37
+ load_config,
38
+ )
39
+ from sidefx.journal import ActionRecord, ActionStatus, Journal
40
+ from sidefx.mcp_proxy import (
41
+ ERR_OUTCOME_UNKNOWN,
42
+ ERR_PAYLOAD_MISMATCH,
43
+ ERR_PREFLIGHT_DENIED,
44
+ OUTCOME_UNKNOWN_BANNER,
45
+ MCPProxy,
46
+ ReconcileHookResult,
47
+ ReconcileState,
48
+ )
49
+ from sidefx.wrapper import (
50
+ EXIT_OUTCOME_UNKNOWN,
51
+ EXIT_PAYLOAD_MISMATCH,
52
+ EXIT_TIMEOUT,
53
+ wrap_command,
54
+ )
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Public structured result types
58
+ # ---------------------------------------------------------------------------
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class ScenarioResult:
63
+ """Structured result for one chaos fault-injection scenario."""
64
+
65
+ name: str
66
+ title: str
67
+ passed: bool
68
+ duration_ms: float
69
+ duplicate_remote_writes: int
70
+ expected_remote_writes: int
71
+ actual_remote_writes: int
72
+ receipt_accuracy_pct: float | None = None
73
+ details: str = ""
74
+ error: str | None = None
75
+ subchecks: tuple[dict[str, Any], ...] = ()
76
+
77
+ def to_dict(self) -> dict[str, Any]:
78
+ """Serialize scenario result to a JSON-compatible dictionary."""
79
+ data: dict[str, Any] = {
80
+ "name": self.name,
81
+ "title": self.title,
82
+ "passed": self.passed,
83
+ "duration_ms": round(self.duration_ms, 2),
84
+ "duplicate_remote_writes": self.duplicate_remote_writes,
85
+ "expected_remote_writes": self.expected_remote_writes,
86
+ "actual_remote_writes": self.actual_remote_writes,
87
+ "details": self.details,
88
+ "subchecks": list(self.subchecks),
89
+ }
90
+ if self.receipt_accuracy_pct is not None:
91
+ data["receipt_accuracy_pct"] = round(self.receipt_accuracy_pct, 2)
92
+ if self.error is not None:
93
+ data["error"] = self.error
94
+ return data
95
+
96
+
97
+ @dataclass(frozen=True, slots=True)
98
+ class ChaosSuiteReport:
99
+ """Aggregate report returned by ``run_chaos_suite``."""
100
+
101
+ scenarios: tuple[ScenarioResult, ...]
102
+ total_duration_ms: float
103
+
104
+ @property
105
+ def total_scenarios(self) -> int:
106
+ return len(self.scenarios)
107
+
108
+ @property
109
+ def passed_scenarios(self) -> int:
110
+ return sum(1 for s in self.scenarios if s.passed)
111
+
112
+ @property
113
+ def failed_scenarios(self) -> int:
114
+ return self.total_scenarios - self.passed_scenarios
115
+
116
+ @property
117
+ def duplicate_remote_writes(self) -> int:
118
+ return sum(s.duplicate_remote_writes for s in self.scenarios)
119
+
120
+ @property
121
+ def total_expected_remote_writes(self) -> int:
122
+ return sum(s.expected_remote_writes for s in self.scenarios)
123
+
124
+ @property
125
+ def total_actual_remote_writes(self) -> int:
126
+ return sum(s.actual_remote_writes for s in self.scenarios)
127
+
128
+ @property
129
+ def receipt_accuracy_pct(self) -> float | None:
130
+ scores = [
131
+ s.receipt_accuracy_pct for s in self.scenarios if s.receipt_accuracy_pct is not None
132
+ ]
133
+ if not scores:
134
+ return None
135
+ return sum(scores) / len(scores)
136
+
137
+ @property
138
+ def passed(self) -> bool:
139
+ if self.total_scenarios == 0:
140
+ return False
141
+ if self.passed_scenarios != self.total_scenarios:
142
+ return False
143
+ if self.duplicate_remote_writes != 0:
144
+ return False
145
+ accuracy = self.receipt_accuracy_pct
146
+ return accuracy is None or accuracy >= 100.0
147
+
148
+ def to_dict(self) -> dict[str, Any]:
149
+ """Serialize aggregate suite report to a JSON-compatible dictionary."""
150
+ accuracy = self.receipt_accuracy_pct
151
+ return {
152
+ "passed": self.passed,
153
+ "total_scenarios": self.total_scenarios,
154
+ "passed_scenarios": self.passed_scenarios,
155
+ "failed_scenarios": self.failed_scenarios,
156
+ "duplicate_remote_writes": self.duplicate_remote_writes,
157
+ "expected_remote_writes": self.total_expected_remote_writes,
158
+ "actual_remote_writes": self.total_actual_remote_writes,
159
+ "receipt_accuracy_pct": round(accuracy, 2) if accuracy is not None else None,
160
+ "total_duration_ms": round(self.total_duration_ms, 2),
161
+ "scenarios": [s.to_dict() for s in self.scenarios],
162
+ }
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Local mock infrastructure (GitHub HTTP server, bare Git repo, stdio MCP)
167
+ # ---------------------------------------------------------------------------
168
+
169
+ _FAKE_GH_IMPL = textwrap.dedent(
170
+ """\
171
+ import json
172
+ import os
173
+ import sys
174
+ import time
175
+ import urllib.request
176
+
177
+ args = sys.argv[1:]
178
+ api_url = os.environ["FAKE_GH_API_URL"]
179
+ mode = os.environ.get("FAKE_GH_MODE", "normal")
180
+ hold_ms = int(os.environ.get("FAKE_GH_HOLD_MS", "0"))
181
+
182
+ if args[:2] != ["issue", "create"]:
183
+ print(f"unsupported fake gh args: {args}", file=sys.stderr)
184
+ sys.exit(2)
185
+
186
+ title = ""
187
+ body = ""
188
+ repo = "acme/app"
189
+ idx = 2
190
+ while idx < len(args):
191
+ tok = args[idx]
192
+ if tok in ("--title", "-t") and idx + 1 < len(args):
193
+ title = args[idx + 1]
194
+ idx += 2
195
+ elif tok.startswith("--title="):
196
+ title = tok.split("=", 1)[1]
197
+ idx += 1
198
+ elif tok in ("--body", "-b") and idx + 1 < len(args):
199
+ body = args[idx + 1]
200
+ idx += 2
201
+ elif tok.startswith("--body="):
202
+ body = tok.split("=", 1)[1]
203
+ idx += 1
204
+ elif tok in ("--repo", "-R") and idx + 1 < len(args):
205
+ repo = args[idx + 1]
206
+ idx += 2
207
+ elif tok.startswith("--repo="):
208
+ repo = tok.split("=", 1)[1]
209
+ idx += 1
210
+ elif tok.startswith("-R") and len(tok) > 2:
211
+ repo = tok[2:]
212
+ idx += 1
213
+ else:
214
+ idx += 1
215
+
216
+ if mode == "pre_commit_crash":
217
+ print("network unreachable before POST", file=sys.stderr)
218
+ sys.exit(1)
219
+
220
+ if mode == "pre_commit_timeout":
221
+ time.sleep(10.0)
222
+ sys.exit(1)
223
+
224
+ if hold_ms > 0:
225
+ time.sleep(hold_ms / 1000.0)
226
+
227
+ req = urllib.request.Request(
228
+ f"{api_url}/repos/{repo}/issues",
229
+ data=json.dumps({"title": title, "body": body}).encode("utf-8"),
230
+ headers={"Content-Type": "application/json"},
231
+ method="POST",
232
+ )
233
+ with urllib.request.urlopen(req, timeout=5.0) as resp:
234
+ created = json.loads(resp.read().decode("utf-8"))
235
+
236
+ if mode == "post_commit_timeout":
237
+ time.sleep(10.0)
238
+ sys.exit(1)
239
+
240
+ if mode == "post_commit_crash":
241
+ print("connection reset by peer after commit", file=sys.stderr)
242
+ sys.exit(1)
243
+
244
+ print(created["html_url"])
245
+ """
246
+ )
247
+
248
+
249
+ _MOCK_MCP_SERVER_IMPL = textwrap.dedent(
250
+ """\
251
+ import json
252
+ import os
253
+ import sys
254
+ import time
255
+ from pathlib import Path
256
+
257
+ ledger_path = Path(os.environ["CHAOS_MCP_LEDGER"])
258
+ mode_file_raw = os.environ.get("CHAOS_MCP_MODE_FILE", "")
259
+ mode_file = Path(mode_file_raw) if mode_file_raw else None
260
+
261
+
262
+ def current_mode() -> str:
263
+ if mode_file is not None and mode_file.exists():
264
+ val = mode_file.read_text(encoding="utf-8").strip()
265
+ if val:
266
+ return val
267
+ return os.environ.get("CHAOS_MCP_MODE", "normal").strip() or "normal"
268
+
269
+
270
+ def next_seq() -> int:
271
+ if not ledger_path.exists():
272
+ return 1
273
+ lines = [ln for ln in ledger_path.read_text(encoding="utf-8").splitlines() if ln.strip()]
274
+ return len(lines) + 1
275
+
276
+
277
+ def append_ledger(tool: str, arguments: dict) -> dict:
278
+ seq = next_seq()
279
+ url = f"https://tickets.sidefx.test/items/{seq}"
280
+ entry = {
281
+ "seq": seq,
282
+ "tool": tool,
283
+ "arguments": arguments,
284
+ "url": url,
285
+ }
286
+ with ledger_path.open("a", encoding="utf-8") as fh:
287
+ fh.write(json.dumps(entry, sort_keys=True) + "\\n")
288
+ fh.flush()
289
+ os.fsync(fh.fileno())
290
+ return entry
291
+
292
+
293
+ def send(obj: dict) -> None:
294
+ sys.stdout.write(json.dumps(obj, separators=(",", ":"), ensure_ascii=True) + "\\n")
295
+ sys.stdout.flush()
296
+
297
+
298
+ for raw_line in sys.stdin:
299
+ line = raw_line.strip()
300
+ if not line:
301
+ continue
302
+ msg = json.loads(line)
303
+ method = msg.get("method")
304
+ req_id = msg.get("id")
305
+ has_id = "id" in msg
306
+
307
+ if method == "initialize":
308
+ send(
309
+ {
310
+ "jsonrpc": "2.0",
311
+ "id": req_id,
312
+ "result": {
313
+ "protocolVersion": "2024-11-05",
314
+ "serverInfo": {"name": "chaos-mock-mcp"},
315
+ },
316
+ }
317
+ )
318
+ continue
319
+
320
+ if method == "tools/list":
321
+ send(
322
+ {
323
+ "jsonrpc": "2.0",
324
+ "id": req_id,
325
+ "result": {
326
+ "tools": [
327
+ {"name": "get_item"},
328
+ {"name": "create_ticket"},
329
+ {"name": "refund_payment"},
330
+ {"name": "push_branch"},
331
+ {"name": "send_email"},
332
+ ]
333
+ },
334
+ }
335
+ )
336
+ continue
337
+
338
+ if method == "tools/call":
339
+ params = msg.get("params") or {}
340
+ name = params.get("name", "")
341
+ arguments = params.get("arguments") or {}
342
+
343
+ if name == "get_item":
344
+ send(
345
+ {
346
+ "jsonrpc": "2.0",
347
+ "id": req_id,
348
+ "result": {
349
+ "content": [{"type": "text", "text": f"item:{arguments.get('id')}"}],
350
+ "isError": False,
351
+ },
352
+ }
353
+ )
354
+ continue
355
+
356
+ mode = current_mode()
357
+ if mode == "pre_commit_crash":
358
+ os._exit(1)
359
+
360
+ if mode == "validation_error":
361
+ send(
362
+ {
363
+ "jsonrpc": "2.0",
364
+ "id": req_id,
365
+ "result": {
366
+ "content": [
367
+ {
368
+ "type": "text",
369
+ "text": "validation error: invalid ticket priority",
370
+ }
371
+ ],
372
+ "isError": True,
373
+ },
374
+ }
375
+ )
376
+ continue
377
+
378
+ entry = append_ledger(name, arguments)
379
+
380
+ if mode == "post_commit_crash":
381
+ os._exit(1)
382
+
383
+ if mode == "post_commit_timeout":
384
+ time.sleep(2.0)
385
+
386
+ if has_id:
387
+ send(
388
+ {
389
+ "jsonrpc": "2.0",
390
+ "id": req_id,
391
+ "result": {
392
+ "content": [
393
+ {
394
+ "type": "text",
395
+ "text": f"Created {name} #{entry['seq']}: {entry['url']}",
396
+ }
397
+ ],
398
+ "structuredContent": {
399
+ "seq": entry["seq"],
400
+ "url": entry["url"],
401
+ "tool": name,
402
+ },
403
+ "isError": False,
404
+ },
405
+ }
406
+ )
407
+ """
408
+ )
409
+
410
+
411
+ class _ChaosGitHubServer:
412
+ """Thread-safe local HTTP mock GitHub server tracking every remote issue write."""
413
+
414
+ def __init__(self) -> None:
415
+ self.lock = threading.Lock()
416
+ self.issues: list[dict[str, Any]] = []
417
+ self.post_count = 0
418
+ self.get_count = 0
419
+ self.fail_gets_status: int | None = None
420
+ self._server: ThreadingHTTPServer | None = None
421
+ self._thread: threading.Thread | None = None
422
+ self.base_url: str = ""
423
+
424
+ def __enter__(self) -> _ChaosGitHubServer:
425
+ state = self
426
+
427
+ class Handler(BaseHTTPRequestHandler):
428
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
429
+ return
430
+
431
+ def do_POST(self) -> None: # noqa: N802
432
+ length = int(self.headers.get("Content-Length", "0"))
433
+ raw = self.rfile.read(length)
434
+ payload = json.loads(raw.decode("utf-8"))
435
+ parsed = urlsplit(self.path)
436
+ parts = [p for p in parsed.path.split("/") if p]
437
+ owner = parts[1] if len(parts) > 2 else "acme"
438
+ repo = parts[2] if len(parts) > 2 else "app"
439
+ with state.lock:
440
+ state.post_count += 1
441
+ num = len(state.issues) + 1
442
+ item = {
443
+ "id": num * 1000,
444
+ "number": num,
445
+ "url": f"{state.base_url}/repos/{owner}/{repo}/issues/{num}",
446
+ "title": payload.get("title", ""),
447
+ "body": payload.get("body", ""),
448
+ "state": "open",
449
+ "user": {"login": "sidefx-bot"},
450
+ "html_url": f"https://github.com/{owner}/{repo}/issues/{num}",
451
+ }
452
+ state.issues.append(item)
453
+ body_bytes = json.dumps(item).encode("utf-8")
454
+ self.send_response(201)
455
+ self.send_header("Content-Type", "application/json")
456
+ self.send_header("Content-Length", str(len(body_bytes)))
457
+ self.end_headers()
458
+ self.wfile.write(body_bytes)
459
+
460
+ def do_GET(self) -> None: # noqa: N802
461
+ with state.lock:
462
+ state.get_count += 1
463
+ fail_status = state.fail_gets_status
464
+ items = list(reversed(state.issues))
465
+ if fail_status is not None:
466
+ err_bytes = b'{"message":"service unavailable"}'
467
+ self.send_response(fail_status)
468
+ self.send_header("Content-Type", "application/json")
469
+ self.send_header("Content-Length", str(len(err_bytes)))
470
+ self.end_headers()
471
+ self.wfile.write(err_bytes)
472
+ return
473
+
474
+ parsed = urlsplit(self.path)
475
+ query = parse_qs(parsed.query)
476
+ req_state = (query.get("state") or ["open"])[0]
477
+ if req_state != "all":
478
+ items = [i for i in items if i["state"] == req_state]
479
+ out_bytes = json.dumps(items).encode("utf-8")
480
+ self.send_response(200)
481
+ self.send_header("Content-Type", "application/json")
482
+ self.send_header("Content-Length", str(len(out_bytes)))
483
+ self.end_headers()
484
+ self.wfile.write(out_bytes)
485
+
486
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
487
+ self.base_url = f"http://127.0.0.1:{self._server.server_address[1]}"
488
+ self._thread = threading.Thread(
489
+ target=self._server.serve_forever,
490
+ name="sidefx-chaos-github",
491
+ daemon=True,
492
+ )
493
+ self._thread.start()
494
+ return self
495
+
496
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
497
+ if self._server is not None:
498
+ self._server.shutdown()
499
+ self._server.server_close()
500
+ self._server = None
501
+ if self._thread is not None:
502
+ self._thread.join(timeout=2.0)
503
+ self._thread = None
504
+
505
+
506
+ def _create_fake_gh(root: Path) -> Path:
507
+ """Create a portable executable `gh` shim immune to Linux shebang length limits."""
508
+ bin_dir = root / "fake_bin"
509
+ bin_dir.mkdir(parents=True, exist_ok=True)
510
+ impl_py = bin_dir / "_fake_gh_impl.py"
511
+ impl_py.write_text(_FAKE_GH_IMPL, encoding="utf-8")
512
+
513
+ gh_shim = bin_dir / "gh"
514
+ gh_shim.write_text(
515
+ f'#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(impl_py))} "$@"\n',
516
+ encoding="utf-8",
517
+ )
518
+ gh_shim.chmod(gh_shim.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
519
+ return gh_shim
520
+
521
+
522
+ def _create_mock_mcp_server(root: Path) -> tuple[Path, Path, Path]:
523
+ """Create mock stdio MCP server script, ground-truth ledger path, and mode file path."""
524
+ mcp_dir = root / "mock_mcp"
525
+ mcp_dir.mkdir(parents=True, exist_ok=True)
526
+ script_path = mcp_dir / "server.py"
527
+ script_path.write_text(_MOCK_MCP_SERVER_IMPL, encoding="utf-8")
528
+ ledger_path = mcp_dir / "mcp_writes.jsonl"
529
+ mode_file = mcp_dir / "mode.txt"
530
+ return script_path, ledger_path, mode_file
531
+
532
+
533
+ def _read_mcp_ledger(ledger_path: Path) -> list[dict[str, Any]]:
534
+ if not ledger_path.exists():
535
+ return []
536
+ entries: list[dict[str, Any]] = []
537
+ for line in ledger_path.read_text(encoding="utf-8").splitlines():
538
+ stripped = line.strip()
539
+ if stripped:
540
+ entries.append(json.loads(stripped))
541
+ return entries
542
+
543
+
544
+ _AMBIENT_ENV_KEYS_TO_STRIP = (
545
+ "GH_HOST",
546
+ "GH_REPO",
547
+ "http_proxy",
548
+ "https_proxy",
549
+ "all_proxy",
550
+ "HTTP_PROXY",
551
+ "HTTPS_PROXY",
552
+ "ALL_PROXY",
553
+ )
554
+ _AMBIENT_ENV_PREFIXES_TO_STRIP = ("GIT_", "SIDEFX_")
555
+ _HERMETIC_ENV_OVERRIDES = {
556
+ "GIT_TERMINAL_PROMPT": "0",
557
+ "GIT_CONFIG_GLOBAL": os.devnull,
558
+ "GIT_CONFIG_NOSYSTEM": "1",
559
+ "NO_PROXY": "127.0.0.1,localhost",
560
+ "no_proxy": "127.0.0.1,localhost",
561
+ }
562
+ _HERMETIC_ENV_LOCK = threading.RLock()
563
+
564
+
565
+ def _isolated_env(extra: dict[str, str] | None = None) -> dict[str, str]:
566
+ """Build a hermetic subprocess env stripped of ambient proxy/sidefx/gh/git overrides."""
567
+ env = os.environ.copy()
568
+ for key in _AMBIENT_ENV_KEYS_TO_STRIP:
569
+ env.pop(key, None)
570
+ for key in list(env):
571
+ if key.startswith(_AMBIENT_ENV_PREFIXES_TO_STRIP):
572
+ env.pop(key, None)
573
+ env.update(_HERMETIC_ENV_OVERRIDES)
574
+ if extra:
575
+ env.update(extra)
576
+ return env
577
+
578
+
579
+ @contextlib.contextmanager
580
+ def _hermetic_chaos_env() -> Iterator[None]:
581
+ """Temporarily apply hermetic proxy/git/sidefx env to ``os.environ`` for in-process callers."""
582
+ with _HERMETIC_ENV_LOCK:
583
+ saved = os.environ.copy()
584
+ try:
585
+ for key in _AMBIENT_ENV_KEYS_TO_STRIP:
586
+ os.environ.pop(key, None)
587
+ for key in list(os.environ):
588
+ if key.startswith(_AMBIENT_ENV_PREFIXES_TO_STRIP):
589
+ os.environ.pop(key, None)
590
+ os.environ.update(_HERMETIC_ENV_OVERRIDES)
591
+ yield
592
+ finally:
593
+ os.environ.clear()
594
+ os.environ.update(saved)
595
+
596
+
597
+ def _write_default_config(root: Path) -> Path:
598
+ """Write an isolated default `.sidefx.json` so child CLIs never discover ancestor configs."""
599
+ cfg_path = root / "isolated_sidefx.json"
600
+ if not cfg_path.exists():
601
+ cfg_path.write_text(json.dumps(default_config_dict(), indent=2), encoding="utf-8")
602
+ return cfg_path
603
+
604
+
605
+ def _git_env() -> dict[str, str]:
606
+ return _isolated_env()
607
+
608
+
609
+ def _run_git(args: Sequence[str], *, cwd: Path) -> subprocess.CompletedProcess[str]:
610
+ proc = subprocess.run(
611
+ ["git", *args],
612
+ cwd=str(cwd),
613
+ capture_output=True,
614
+ text=True,
615
+ env=_git_env(),
616
+ timeout=15.0,
617
+ check=False,
618
+ )
619
+ if proc.returncode != 0:
620
+ raise RuntimeError(
621
+ f"git {' '.join(args)} failed ({proc.returncode}): {proc.stderr.strip()}"
622
+ )
623
+ return proc
624
+
625
+
626
+ @dataclass(slots=True)
627
+ class _ChaosGitRepo:
628
+ bare_dir: Path
629
+ work_dir: Path
630
+ push_log: Path
631
+ push_attempts_log: Path
632
+ block_pre_flag: Path
633
+ slow_post_flag: Path
634
+
635
+ def create_branch_commit(self, branch: str, filename: str, content: str) -> str:
636
+ _run_git(["checkout", "-B", branch, "main"], cwd=self.work_dir)
637
+ (self.work_dir / filename).write_text(content, encoding="utf-8")
638
+ _run_git(["add", filename], cwd=self.work_dir)
639
+ _run_git(["commit", "-m", f"commit on {branch}"], cwd=self.work_dir)
640
+ return _run_git(["rev-parse", "HEAD"], cwd=self.work_dir).stdout.strip().lower()
641
+
642
+ def push_events_for_ref(self, ref_name: str) -> list[tuple[str, str, str]]:
643
+ if not self.push_log.exists():
644
+ return []
645
+ events: list[tuple[str, str, str]] = []
646
+ for line in self.push_log.read_text(encoding="utf-8").splitlines():
647
+ parts = line.strip().split()
648
+ if len(parts) == 3 and parts[2] == ref_name:
649
+ events.append((parts[0], parts[1], parts[2]))
650
+ return events
651
+
652
+ def push_attempt_count(self) -> int:
653
+ if not self.push_attempts_log.exists():
654
+ return 0
655
+ return sum(
656
+ 1
657
+ for ln in self.push_attempts_log.read_text(encoding="utf-8").splitlines()
658
+ if ln.strip()
659
+ )
660
+
661
+ def remote_ref_sha(self, ref_name: str) -> str | None:
662
+ proc = subprocess.run(
663
+ ["git", "rev-parse", "--verify", ref_name],
664
+ cwd=str(self.bare_dir),
665
+ capture_output=True,
666
+ text=True,
667
+ env=_git_env(),
668
+ timeout=10.0,
669
+ check=False,
670
+ )
671
+ if proc.returncode != 0:
672
+ return None
673
+ return proc.stdout.strip().lower() or None
674
+
675
+
676
+ def _create_chaos_git_repo(root: Path) -> _ChaosGitRepo:
677
+ """Create a real local bare remote + working clone with fault-injecting hooks."""
678
+ bare_dir = root / "remote.git"
679
+ work_dir = root / "work"
680
+ bare_dir.mkdir(parents=True, exist_ok=True)
681
+ work_dir.mkdir(parents=True, exist_ok=True)
682
+ push_log = root / "push_events.log"
683
+ push_attempts_log = root / "push_attempts.log"
684
+ block_pre_flag = root / "block_pre_receive.flag"
685
+ slow_post_flag = root / "slow_post_receive.flag"
686
+
687
+ # Always specify `-b main` and local identity/signing config for Ubuntu CI portability.
688
+ _run_git(["init", "--bare", "-b", "main", str(bare_dir)], cwd=root)
689
+ _run_git(["init", "-b", "main", str(work_dir)], cwd=root)
690
+ _run_git(["config", "user.name", "sidefx Chaos"], cwd=work_dir)
691
+ _run_git(["config", "user.email", "chaos@sidefx.test"], cwd=work_dir)
692
+ _run_git(["config", "commit.gpgsign", "false"], cwd=work_dir)
693
+ _run_git(["remote", "add", "origin", str(bare_dir)], cwd=work_dir)
694
+
695
+ (work_dir / "README.txt").write_text("seed\n", encoding="utf-8")
696
+ _run_git(["add", "README.txt"], cwd=work_dir)
697
+ _run_git(["commit", "-m", "initial commit"], cwd=work_dir)
698
+ _run_git(["push", "-u", "origin", "main"], cwd=work_dir)
699
+
700
+ # Track every real `git push` contacting `receive-pack` (even no-op re-pushes!),
701
+ # while leaving read-only `git ls-remote` (`upload-pack`) untouched.
702
+ receive_pack_wrapper = root / "sidefx-receive-pack"
703
+ receive_pack_wrapper.write_text(
704
+ "#!/bin/sh\n"
705
+ f"printf 'attempt\\n' >> {shlex.quote(str(push_attempts_log))}\n"
706
+ 'exec git receive-pack "$@"\n',
707
+ encoding="utf-8",
708
+ )
709
+ receive_pack_wrapper.chmod(0o755)
710
+ _run_git(
711
+ ["config", "remote.origin.receivepack", shlex.quote(str(receive_pack_wrapper))],
712
+ cwd=work_dir,
713
+ )
714
+
715
+ hooks_dir = bare_dir / "hooks"
716
+ hooks_dir.mkdir(parents=True, exist_ok=True)
717
+
718
+ pre_hook = hooks_dir / "pre-receive"
719
+ pre_hook.write_text(
720
+ f"#!/bin/sh\nif [ -f {shlex.quote(str(block_pre_flag))} ]; then\n"
721
+ f" sleep 10\n exit 1\nfi\n",
722
+ encoding="utf-8",
723
+ )
724
+ pre_hook.chmod(0o755)
725
+
726
+ post_hook = hooks_dir / "post-receive"
727
+ post_hook.write_text(
728
+ "#!/bin/sh\n"
729
+ "while read oldrev newrev refname; do\n"
730
+ f' printf \'%s %s %s\\n\' "$oldrev" "$newrev" "$refname" >> '
731
+ f"{shlex.quote(str(push_log))}\n"
732
+ "done\n"
733
+ f"if [ -f {shlex.quote(str(slow_post_flag))} ]; then\n"
734
+ " sleep 10\n"
735
+ "fi\n",
736
+ encoding="utf-8",
737
+ )
738
+ post_hook.chmod(0o755)
739
+
740
+ return _ChaosGitRepo(
741
+ bare_dir=bare_dir,
742
+ work_dir=work_dir,
743
+ push_log=push_log,
744
+ push_attempts_log=push_attempts_log,
745
+ block_pre_flag=block_pre_flag,
746
+ slow_post_flag=slow_post_flag,
747
+ )
748
+
749
+
750
+ class _MCPSubprocessClient:
751
+ """Context manager driving the real `sidefx mcp-proxy` CLI subprocess over stdio."""
752
+
753
+ def __init__(
754
+ self,
755
+ *,
756
+ db_path: Path,
757
+ server_script: Path,
758
+ ledger_path: Path,
759
+ mode_file: Path,
760
+ session_id: str,
761
+ cwd: Path,
762
+ target: str = "mcp:chaos",
763
+ config_path: Path | None = None,
764
+ timeout_seconds: float = 2.0,
765
+ ) -> None:
766
+ self._db_path = db_path
767
+ self._server_script = server_script
768
+ self._ledger_path = ledger_path
769
+ self._mode_file = mode_file
770
+ self._session_id = session_id
771
+ self._cwd = cwd
772
+ self._target = target
773
+ self._config_path = config_path
774
+ self._timeout_seconds = timeout_seconds
775
+ self._proc: subprocess.Popen[bytes] | None = None
776
+ self._stderr_chunks: list[bytes] = []
777
+ self._stderr_thread: threading.Thread | None = None
778
+ self._active_readers: list[threading.Thread] = []
779
+
780
+ def __enter__(self) -> _MCPSubprocessClient:
781
+ cmd = [
782
+ sys.executable,
783
+ "-m",
784
+ "sidefx",
785
+ "mcp-proxy",
786
+ "--db",
787
+ str(self._db_path),
788
+ "--session-id",
789
+ self._session_id,
790
+ "--target",
791
+ self._target,
792
+ "--timeout",
793
+ str(self._timeout_seconds),
794
+ ]
795
+ effective_cfg = (
796
+ self._config_path if self._config_path is not None else _write_default_config(self._cwd)
797
+ )
798
+ cmd.extend(["--config", str(effective_cfg)])
799
+ cmd.extend(["--", sys.executable, str(self._server_script)])
800
+
801
+ env = _isolated_env(
802
+ {
803
+ "CHAOS_MCP_LEDGER": str(self._ledger_path),
804
+ "CHAOS_MCP_MODE_FILE": str(self._mode_file),
805
+ }
806
+ )
807
+
808
+ popen_extra: dict[str, Any] = {"start_new_session": True} if os.name == "posix" else {}
809
+ self._proc = subprocess.Popen(
810
+ cmd,
811
+ cwd=str(self._cwd),
812
+ stdin=subprocess.PIPE,
813
+ stdout=subprocess.PIPE,
814
+ stderr=subprocess.PIPE,
815
+ env=env,
816
+ **popen_extra,
817
+ )
818
+ assert self._proc.stderr is not None
819
+ self._stderr_chunks = []
820
+
821
+ def _drain_stderr(stream: Any) -> None:
822
+ with contextlib.suppress(OSError, ValueError):
823
+ while True:
824
+ chunk = stream.read(4096)
825
+ if not chunk:
826
+ break
827
+ self._stderr_chunks.append(chunk)
828
+
829
+ self._stderr_thread = threading.Thread(
830
+ target=_drain_stderr,
831
+ args=(self._proc.stderr,),
832
+ name="sidefx-chaos-mcp-stderr",
833
+ daemon=True,
834
+ )
835
+ self._stderr_thread.start()
836
+ return self
837
+
838
+ def request(self, payload: dict[str, Any], *, timeout: float = 8.0) -> dict[str, Any]:
839
+ assert (
840
+ self._proc is not None
841
+ and self._proc.stdin is not None
842
+ and self._proc.stdout is not None
843
+ )
844
+ line = (json.dumps(payload, separators=(",", ":"), ensure_ascii=True) + "\n").encode(
845
+ "ascii"
846
+ )
847
+ self._proc.stdin.write(line)
848
+ self._proc.stdin.flush()
849
+
850
+ result_holder: list[bytes] = []
851
+ stdout_stream = self._proc.stdout
852
+
853
+ def _read_line() -> None:
854
+ with contextlib.suppress(OSError, ValueError):
855
+ result_holder.append(stdout_stream.readline())
856
+
857
+ reader = threading.Thread(target=_read_line, daemon=True)
858
+ self._active_readers.append(reader)
859
+ reader.start()
860
+ reader.join(timeout=timeout)
861
+ if reader.is_alive() or not result_holder or not result_holder[0]:
862
+ stderr_tail = b"".join(self._stderr_chunks).decode("utf-8", errors="replace").strip()
863
+ extra = f" (stderr: {stderr_tail})" if stderr_tail else ""
864
+ raise TimeoutError(
865
+ f"Timed out waiting for MCP proxy reply to {payload.get('id')!r}{extra}"
866
+ )
867
+ return json.loads(result_holder[0].decode("utf-8"))
868
+
869
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
870
+ if self._proc is None:
871
+ return
872
+ if self._proc.stdin is not None:
873
+ with contextlib.suppress(OSError):
874
+ self._proc.stdin.close()
875
+ try:
876
+ self._proc.wait(timeout=5.0)
877
+ except subprocess.TimeoutExpired:
878
+ if os.name == "posix":
879
+ try:
880
+ pgid = os.getpgid(self._proc.pid)
881
+ except OSError:
882
+ pgid = None
883
+ if pgid is not None:
884
+ with contextlib.suppress(OSError):
885
+ os.killpg(pgid, signal.SIGTERM)
886
+ with contextlib.suppress(subprocess.TimeoutExpired):
887
+ self._proc.wait(timeout=2.0)
888
+ # Always SIGKILL the entire process group so SIGTERM-ignoring grandchildren
889
+ # cannot stay alive holding stdout/stderr pipes open.
890
+ with contextlib.suppress(OSError):
891
+ os.killpg(pgid, signal.SIGKILL)
892
+ with contextlib.suppress(subprocess.TimeoutExpired):
893
+ self._proc.wait(timeout=2.0)
894
+ else:
895
+ self._proc.kill()
896
+ self._proc.wait(timeout=2.0)
897
+ else:
898
+ self._proc.terminate()
899
+ try:
900
+ self._proc.wait(timeout=2.0)
901
+ except subprocess.TimeoutExpired:
902
+ self._proc.kill()
903
+ self._proc.wait(timeout=2.0)
904
+ # Child process group has exited, so stdout/stderr hit EOF; join readers BEFORE closing.
905
+ still_reading_stdout = False
906
+ for reader in self._active_readers:
907
+ reader.join(timeout=2.0)
908
+ if reader.is_alive():
909
+ still_reading_stdout = True
910
+ self._active_readers.clear()
911
+ still_reading_stderr = False
912
+ if self._stderr_thread is not None:
913
+ self._stderr_thread.join(timeout=2.0)
914
+ still_reading_stderr = self._stderr_thread.is_alive()
915
+ self._stderr_thread = None
916
+ if self._proc.stdout is not None and not still_reading_stdout:
917
+ with contextlib.suppress(OSError):
918
+ self._proc.stdout.close()
919
+ if self._proc.stderr is not None and not still_reading_stderr:
920
+ with contextlib.suppress(OSError):
921
+ self._proc.stderr.close()
922
+ self._proc = None
923
+
924
+
925
+ class _MCPInProcessClient:
926
+ """Context manager driving `MCPProxy` (with optional `reconciler_hook`) over real pipes."""
927
+
928
+ def __init__(
929
+ self,
930
+ *,
931
+ db_path: Path,
932
+ server_script: Path,
933
+ ledger_path: Path,
934
+ mode_file: Path,
935
+ session_id: str,
936
+ target: str = "mcp:chaos",
937
+ config: SidefxConfig | None = None,
938
+ timeout_seconds: float = 2.0,
939
+ reconciler_hook: Callable[[ActionRecord], Any] | None = None,
940
+ ) -> None:
941
+ self._db_path = db_path
942
+ self._server_script = server_script
943
+ self._ledger_path = ledger_path
944
+ self._mode_file = mode_file
945
+ self._session_id = session_id
946
+ self._target = target
947
+ self._config = config
948
+ self._timeout_seconds = timeout_seconds
949
+ self._reconciler_hook = reconciler_hook
950
+ self._journal: Journal | None = None
951
+ self._thread: threading.Thread | None = None
952
+ self._active_readers: list[threading.Thread] = []
953
+ self._c_in_w: Any = None
954
+ self._c_in_r: Any = None
955
+ self._c_out_r: Any = None
956
+ self._c_out_w: Any = None
957
+
958
+ def __enter__(self) -> _MCPInProcessClient:
959
+ r_in, w_in = os.pipe()
960
+ r_out, w_out = os.pipe()
961
+ self._c_in_r = os.fdopen(r_in, "rb", buffering=0)
962
+ self._c_in_w = os.fdopen(w_in, "wb", buffering=0)
963
+ self._c_out_r = os.fdopen(r_out, "rb")
964
+ self._c_out_w = os.fdopen(w_out, "wb", buffering=0)
965
+
966
+ env = _isolated_env(
967
+ {
968
+ "CHAOS_MCP_LEDGER": str(self._ledger_path),
969
+ "CHAOS_MCP_MODE_FILE": str(self._mode_file),
970
+ }
971
+ )
972
+
973
+ self._journal = Journal(self._db_path)
974
+ proxy = MCPProxy(
975
+ [sys.executable, str(self._server_script)],
976
+ journal=self._journal,
977
+ config=self._config,
978
+ session_id=self._session_id,
979
+ target=self._target,
980
+ timeout_seconds=self._timeout_seconds,
981
+ reconciler_hook=self._reconciler_hook,
982
+ client_in=self._c_in_r,
983
+ client_out=self._c_out_w,
984
+ err_stream=io.BytesIO(),
985
+ upstream_env=env,
986
+ )
987
+ self._thread = threading.Thread(target=proxy.run, name="sidefx-chaos-mcp", daemon=True)
988
+ self._thread.start()
989
+ return self
990
+
991
+ def request(self, payload: dict[str, Any], *, timeout: float = 8.0) -> dict[str, Any]:
992
+ assert self._c_in_w is not None and self._c_out_r is not None
993
+ line = (json.dumps(payload, separators=(",", ":"), ensure_ascii=True) + "\n").encode(
994
+ "ascii"
995
+ )
996
+ self._c_in_w.write(line)
997
+ self._c_in_w.flush()
998
+
999
+ result_holder: list[bytes] = []
1000
+ out_reader = self._c_out_r
1001
+
1002
+ def _read_line() -> None:
1003
+ with contextlib.suppress(OSError, ValueError):
1004
+ result_holder.append(out_reader.readline())
1005
+
1006
+ reader = threading.Thread(target=_read_line, daemon=True)
1007
+ self._active_readers.append(reader)
1008
+ reader.start()
1009
+ reader.join(timeout=timeout)
1010
+ if reader.is_alive() or not result_holder or not result_holder[0]:
1011
+ raise TimeoutError(f"Timed out waiting for MCPProxy reply to {payload.get('id')!r}")
1012
+ return json.loads(result_holder[0].decode("utf-8"))
1013
+
1014
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
1015
+ # 1. Close client->proxy write end so MCPProxy hits EOF and finishes cleanly.
1016
+ if self._c_in_w is not None:
1017
+ with contextlib.suppress(OSError):
1018
+ self._c_in_w.close()
1019
+ if self._thread is not None:
1020
+ self._thread.join(timeout=8.5)
1021
+ # 2. Close proxy->client write end BEFORE joining readers or closing _c_out_r,
1022
+ # so any reader blocked in readline() after a timeout wakes on EOF instead of hanging.
1023
+ if self._c_out_w is not None:
1024
+ with contextlib.suppress(OSError):
1025
+ self._c_out_w.close()
1026
+ for reader in self._active_readers:
1027
+ reader.join(timeout=2.0)
1028
+ self._active_readers.clear()
1029
+ for handle in (self._c_in_r, self._c_out_r):
1030
+ if handle is not None:
1031
+ with contextlib.suppress(OSError):
1032
+ handle.close()
1033
+ if self._journal is not None:
1034
+ self._journal.close()
1035
+ self._journal = None
1036
+
1037
+
1038
+ def _make_mcp_ledger_reconciler(
1039
+ ledger_path: Path, ticket_key_by_action: dict[str, str]
1040
+ ) -> Callable[[ActionRecord], ReconcileHookResult]:
1041
+ """Read-only reconciler hook querying the mock MCP server's durable JSONL ledger."""
1042
+
1043
+ def _reconcile(record: ActionRecord) -> ReconcileHookResult:
1044
+ expected_key = ticket_key_by_action.get(record.action_id)
1045
+ if expected_key is None:
1046
+ return ReconcileHookResult(
1047
+ state=ReconcileState.UNKNOWN,
1048
+ details=f"No lookup key for {record.action_id}",
1049
+ )
1050
+ entries = _read_mcp_ledger(ledger_path)
1051
+ matches = [e for e in entries if e.get("arguments", {}).get("ticket_key") == expected_key]
1052
+ if len(matches) == 1:
1053
+ found = matches[0]
1054
+ return ReconcileHookResult(
1055
+ state=ReconcileState.FOUND,
1056
+ result_ref=str(found["url"]),
1057
+ summary=f"Recovered {found['tool']} #{found['seq']}",
1058
+ details=f"Found exact ticket_key={expected_key} in remote ledger",
1059
+ )
1060
+ if len(matches) == 0:
1061
+ return ReconcileHookResult(
1062
+ state=ReconcileState.NOT_FOUND,
1063
+ details=f"Confirmed 0 remote entries for ticket_key={expected_key}",
1064
+ )
1065
+ return ReconcileHookResult(
1066
+ state=ReconcileState.UNKNOWN,
1067
+ details=f"Ambiguous ledger state: {len(matches)} matches for {expected_key}",
1068
+ )
1069
+
1070
+ return _reconcile
1071
+
1072
+
1073
+ def _count_duplicates(subchecks: Sequence[dict[str, Any]]) -> tuple[int, int, int]:
1074
+ """Return ``(duplicate_writes, expected_writes, actual_writes)`` across subchecks."""
1075
+ dups = 0
1076
+ expected_total = 0
1077
+ actual_total = 0
1078
+ for chk in subchecks:
1079
+ exp = int(chk["expected_writes"])
1080
+ act = int(chk["actual_writes"])
1081
+ expected_total += exp
1082
+ actual_total += act
1083
+ if act > exp:
1084
+ dups += act - exp
1085
+ return dups, expected_total, actual_total
1086
+
1087
+
1088
+ # ---------------------------------------------------------------------------
1089
+ # Chaos Scenario 1: Pre-commit crash / timeout before remote write lands
1090
+ # ---------------------------------------------------------------------------
1091
+
1092
+
1093
+ def _scenario_pre_commit_crash_and_timeout() -> ScenarioResult:
1094
+ name = "pre_commit_crash_and_timeout"
1095
+ title = "Pre-commit crash & timeout recovery"
1096
+ started = time.perf_counter()
1097
+ subchecks: list[dict[str, Any]] = []
1098
+
1099
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s1-") as tmp:
1100
+ root = Path(tmp)
1101
+ db_path = root / "journal.db"
1102
+
1103
+ # 1a. CLI wrap -> Mock GitHub: pre-commit timeout -> NOT_FOUND -> safe retry (1 write)
1104
+ # + uncertain reconciliation (API 503) stays UNKNOWN (0 writes).
1105
+ with _ChaosGitHubServer() as gh_srv:
1106
+ fake_gh = _create_fake_gh(root)
1107
+ env = _isolated_env({"FAKE_GH_API_URL": gh_srv.base_url})
1108
+ cmd_a = [
1109
+ str(fake_gh),
1110
+ "issue",
1111
+ "create",
1112
+ "-R",
1113
+ "acme/app",
1114
+ "--title",
1115
+ "Pre-commit timeout",
1116
+ "--body",
1117
+ "Should retry safely once",
1118
+ ]
1119
+ with Journal(db_path) as journal:
1120
+ env["FAKE_GH_MODE"] = "pre_commit_timeout"
1121
+ r1 = wrap_command(
1122
+ cmd_a,
1123
+ journal=journal,
1124
+ action_id="s1-gh-timeout",
1125
+ session_id="chaos-s1",
1126
+ timeout_seconds=0.35,
1127
+ min_retry_age_seconds=0.0,
1128
+ env=env,
1129
+ github_api_url=gh_srv.base_url,
1130
+ )
1131
+ after_timeout_posts = gh_srv.post_count
1132
+
1133
+ env["FAKE_GH_MODE"] = "normal"
1134
+ r2 = wrap_command(
1135
+ cmd_a,
1136
+ journal=journal,
1137
+ action_id="s1-gh-timeout",
1138
+ session_id="chaos-s1",
1139
+ timeout_seconds=5.0,
1140
+ min_retry_age_seconds=0.0,
1141
+ env=env,
1142
+ github_api_url=gh_srv.base_url,
1143
+ )
1144
+ gh_timeout_ok = (
1145
+ r1.exit_code == EXIT_TIMEOUT
1146
+ and r1.status == ActionStatus.UNKNOWN
1147
+ and after_timeout_posts == 0
1148
+ and r2.exit_code == 0
1149
+ and r2.executed is True
1150
+ and r2.status == ActionStatus.CONFIRMED
1151
+ and r2.result_ref == "https://github.com/acme/app/issues/1"
1152
+ and gh_srv.post_count == 1
1153
+ )
1154
+ subchecks.append(
1155
+ {
1156
+ "check": "cli_github_pre_commit_timeout",
1157
+ "passed": gh_timeout_ok,
1158
+ "expected_writes": 1,
1159
+ "actual_writes": gh_srv.post_count,
1160
+ "detail": (
1161
+ f"timeout_exit={r1.exit_code}, "
1162
+ f"posts_before_retry={after_timeout_posts}, "
1163
+ f"retry_status={r2.status}, posts_after_retry={gh_srv.post_count}"
1164
+ ),
1165
+ }
1166
+ )
1167
+
1168
+ # Uncertain reconciliation when GitHub API returns 503 after pre-commit crash
1169
+ cmd_b = [
1170
+ str(fake_gh),
1171
+ "issue",
1172
+ "create",
1173
+ "-R",
1174
+ "acme/app",
1175
+ "--title",
1176
+ "Uncertain reconcile",
1177
+ "--body",
1178
+ "Must stay blocked on 503",
1179
+ ]
1180
+ posts_before_b = gh_srv.post_count
1181
+ env["FAKE_GH_MODE"] = "pre_commit_crash"
1182
+ r3 = wrap_command(
1183
+ cmd_b,
1184
+ journal=journal,
1185
+ action_id="s1-gh-uncertain",
1186
+ session_id="chaos-s1",
1187
+ timeout_seconds=5.0,
1188
+ min_retry_age_seconds=0.0,
1189
+ env=env,
1190
+ github_api_url=gh_srv.base_url,
1191
+ )
1192
+ gh_srv.fail_gets_status = 503
1193
+ env["FAKE_GH_MODE"] = "normal"
1194
+ r4 = wrap_command(
1195
+ cmd_b,
1196
+ journal=journal,
1197
+ action_id="s1-gh-uncertain",
1198
+ session_id="chaos-s1",
1199
+ timeout_seconds=5.0,
1200
+ min_retry_age_seconds=0.0,
1201
+ env=env,
1202
+ github_api_url=gh_srv.base_url,
1203
+ )
1204
+ gh_srv.fail_gets_status = None
1205
+ writes_b = gh_srv.post_count - posts_before_b
1206
+ gh_uncertain_ok = (
1207
+ r3.status == ActionStatus.UNKNOWN
1208
+ and r4.exit_code == EXIT_OUTCOME_UNKNOWN
1209
+ and r4.executed is False
1210
+ and r4.status == ActionStatus.UNKNOWN
1211
+ and writes_b == 0
1212
+ )
1213
+ subchecks.append(
1214
+ {
1215
+ "check": "cli_github_uncertain_stays_blocked",
1216
+ "passed": gh_uncertain_ok,
1217
+ "expected_writes": 0,
1218
+ "actual_writes": writes_b,
1219
+ "detail": (
1220
+ f"retry_exit={r4.exit_code}, status={r4.status}, writes={writes_b}"
1221
+ ),
1222
+ }
1223
+ )
1224
+
1225
+ # 1b. CLI wrap -> Local bare git repo: pre-receive timeout -> NOT_FOUND -> safe retry once
1226
+ git_repo = _create_chaos_git_repo(root / "git_s1")
1227
+ expected_sha = git_repo.create_branch_commit("feat-pre", "pre.txt", "pre-commit test\n")
1228
+ git_repo.block_pre_flag.write_text("1", encoding="utf-8")
1229
+
1230
+ with Journal(db_path) as journal:
1231
+ git_env = _git_env()
1232
+ g1 = wrap_command(
1233
+ ["git", "push", "origin", "feat-pre"],
1234
+ journal=journal,
1235
+ action_id="s1-git-pre",
1236
+ session_id="chaos-s1",
1237
+ timeout_seconds=0.4,
1238
+ min_retry_age_seconds=0.0,
1239
+ cwd=git_repo.work_dir,
1240
+ env=git_env,
1241
+ )
1242
+ events_after_timeout = git_repo.push_events_for_ref("refs/heads/feat-pre")
1243
+ git_repo.block_pre_flag.unlink(missing_ok=True)
1244
+
1245
+ g2 = wrap_command(
1246
+ ["git", "push", "origin", "feat-pre"],
1247
+ journal=journal,
1248
+ action_id="s1-git-pre",
1249
+ session_id="chaos-s1",
1250
+ timeout_seconds=5.0,
1251
+ min_retry_age_seconds=0.0,
1252
+ cwd=git_repo.work_dir,
1253
+ env=git_env,
1254
+ )
1255
+ events_after_retry = git_repo.push_events_for_ref("refs/heads/feat-pre")
1256
+ git_pre_ok = (
1257
+ g1.exit_code == EXIT_TIMEOUT
1258
+ and g1.status == ActionStatus.UNKNOWN
1259
+ and len(events_after_timeout) == 0
1260
+ and g2.exit_code == 0
1261
+ and g2.executed is True
1262
+ and g2.status == ActionStatus.CONFIRMED
1263
+ and len(events_after_retry) == 1
1264
+ and events_after_retry[0][1] == expected_sha
1265
+ )
1266
+ subchecks.append(
1267
+ {
1268
+ "check": "cli_git_push_pre_commit_timeout",
1269
+ "passed": git_pre_ok,
1270
+ "expected_writes": 1,
1271
+ "actual_writes": len(events_after_retry),
1272
+ "detail": (
1273
+ f"events_before={len(events_after_timeout)}, "
1274
+ f"events_after={len(events_after_retry)}, status={g2.status}"
1275
+ ),
1276
+ }
1277
+ )
1278
+
1279
+ # 1c. MCP proxy -> Mock stdio MCP server: pre-commit crash -> blocked without hook,
1280
+ # then safely retried once when reconciler_hook proves NOT_FOUND.
1281
+ server_script, ledger_path, mode_file = _create_mock_mcp_server(root / "mcp_s1")
1282
+ call_payload = {
1283
+ "jsonrpc": "2.0",
1284
+ "id": 1,
1285
+ "method": "tools/call",
1286
+ "params": {
1287
+ "name": "create_ticket",
1288
+ "arguments": {
1289
+ "_sidefx_action_id": "s1-mcp-pre",
1290
+ "ticket_key": "T-PRE-1",
1291
+ "title": "Pre-commit MCP test",
1292
+ },
1293
+ },
1294
+ }
1295
+ mode_file.write_text("pre_commit_crash", encoding="utf-8")
1296
+ with _MCPInProcessClient(
1297
+ db_path=db_path,
1298
+ server_script=server_script,
1299
+ ledger_path=ledger_path,
1300
+ mode_file=mode_file,
1301
+ session_id="chaos-s1",
1302
+ target="mcp:s1",
1303
+ ) as client1:
1304
+ resp_crash = client1.request(call_payload)
1305
+
1306
+ writes_after_crash = len(_read_mcp_ledger(ledger_path))
1307
+
1308
+ # Retry WITHOUT reconciler hook -> must stay blocked!
1309
+ mode_file.write_text("normal", encoding="utf-8")
1310
+ with _MCPInProcessClient(
1311
+ db_path=db_path,
1312
+ server_script=server_script,
1313
+ ledger_path=ledger_path,
1314
+ mode_file=mode_file,
1315
+ session_id="chaos-s1",
1316
+ target="mcp:s1",
1317
+ ) as client2:
1318
+ resp_blocked = client2.request({**call_payload, "id": 2})
1319
+
1320
+ writes_after_blocked = len(_read_mcp_ledger(ledger_path))
1321
+
1322
+ # Retry WITH read-only reconciler hook proving NOT_FOUND -> safe single retry!
1323
+ hook = _make_mcp_ledger_reconciler(ledger_path, {"s1-mcp-pre": "T-PRE-1"})
1324
+ with _MCPInProcessClient(
1325
+ db_path=db_path,
1326
+ server_script=server_script,
1327
+ ledger_path=ledger_path,
1328
+ mode_file=mode_file,
1329
+ session_id="chaos-s1",
1330
+ target="mcp:s1",
1331
+ reconciler_hook=hook,
1332
+ ) as client3:
1333
+ resp_retried = client3.request({**call_payload, "id": 3})
1334
+
1335
+ writes_final = len(_read_mcp_ledger(ledger_path))
1336
+ mcp_pre_ok = (
1337
+ resp_crash.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1338
+ and writes_after_crash == 0
1339
+ and resp_blocked.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1340
+ and writes_after_blocked == 0
1341
+ and "result" in resp_retried
1342
+ and resp_retried["result"].get("isError") is False
1343
+ and writes_final == 1
1344
+ )
1345
+ subchecks.append(
1346
+ {
1347
+ "check": "mcp_proxy_pre_commit_crash",
1348
+ "passed": mcp_pre_ok,
1349
+ "expected_writes": 1,
1350
+ "actual_writes": writes_final,
1351
+ "detail": (
1352
+ f"crash_err={resp_crash.get('error', {}).get('code')}, "
1353
+ f"blocked_err={resp_blocked.get('error', {}).get('code')}, "
1354
+ f"final_writes={writes_final}"
1355
+ ),
1356
+ }
1357
+ )
1358
+
1359
+ dups, exp_w, act_w = _count_duplicates(subchecks)
1360
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0
1361
+ return ScenarioResult(
1362
+ name=name,
1363
+ title=title,
1364
+ passed=all_passed,
1365
+ duration_ms=(time.perf_counter() - started) * 1000.0,
1366
+ duplicate_remote_writes=dups,
1367
+ expected_remote_writes=exp_w,
1368
+ actual_remote_writes=act_w,
1369
+ details=f"{sum(1 for c in subchecks if c['passed'])}/{len(subchecks)} surfaces verified",
1370
+ error=None if all_passed else "One or more pre-commit recovery checks failed",
1371
+ subchecks=tuple(subchecks),
1372
+ )
1373
+
1374
+
1375
+ # ---------------------------------------------------------------------------
1376
+ # Chaos Scenario 2: Post-commit response-loss crash / timeout (all 3 surfaces)
1377
+ # ---------------------------------------------------------------------------
1378
+
1379
+
1380
+ def _scenario_post_commit_response_loss() -> ScenarioResult:
1381
+ name = "post_commit_response_loss"
1382
+ title = "Post-commit response-loss reconciliation"
1383
+ started = time.perf_counter()
1384
+ subchecks: list[dict[str, Any]] = []
1385
+
1386
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s2-") as tmp:
1387
+ root = Path(tmp)
1388
+ db_path = root / "journal.db"
1389
+
1390
+ # 2a. CLI wrap -> Mock GitHub: post-commit timeout + post-commit crash -> 0 duplicate writes
1391
+ with _ChaosGitHubServer() as gh_srv:
1392
+ fake_gh = _create_fake_gh(root)
1393
+ env = _isolated_env({"FAKE_GH_API_URL": gh_srv.base_url})
1394
+
1395
+ cmd_timeout = [
1396
+ str(fake_gh),
1397
+ "issue",
1398
+ "create",
1399
+ "-R",
1400
+ "acme/app",
1401
+ "--title",
1402
+ "Lost after timeout",
1403
+ "--body",
1404
+ "Post-commit timeout test",
1405
+ ]
1406
+ cmd_crash = [
1407
+ str(fake_gh),
1408
+ "issue",
1409
+ "create",
1410
+ "-R",
1411
+ "acme/app",
1412
+ "--title",
1413
+ "Lost after crash",
1414
+ "--body",
1415
+ "Post-commit crash test",
1416
+ ]
1417
+
1418
+ with Journal(db_path) as journal:
1419
+ env["FAKE_GH_MODE"] = "post_commit_timeout"
1420
+ t1 = wrap_command(
1421
+ cmd_timeout,
1422
+ journal=journal,
1423
+ action_id="s2-gh-timeout",
1424
+ session_id="chaos-s2",
1425
+ timeout_seconds=1.0,
1426
+ env=env,
1427
+ github_api_url=gh_srv.base_url,
1428
+ )
1429
+ env["FAKE_GH_MODE"] = "normal"
1430
+ t2 = wrap_command(
1431
+ cmd_timeout,
1432
+ journal=journal,
1433
+ action_id="s2-gh-timeout",
1434
+ session_id="chaos-s2",
1435
+ timeout_seconds=5.0,
1436
+ env=env,
1437
+ github_api_url=gh_srv.base_url,
1438
+ )
1439
+ posts_after_t = gh_srv.post_count
1440
+ gh_timeout_ok = (
1441
+ t1.exit_code == EXIT_TIMEOUT
1442
+ and t1.status == ActionStatus.UNKNOWN
1443
+ and t2.exit_code == 0
1444
+ and t2.executed is False
1445
+ and t2.reconciled is True
1446
+ and t2.status == ActionStatus.RECONCILED
1447
+ and t2.result_ref == "https://github.com/acme/app/issues/1"
1448
+ and posts_after_t == 1
1449
+ )
1450
+ subchecks.append(
1451
+ {
1452
+ "check": "cli_github_post_commit_timeout",
1453
+ "passed": gh_timeout_ok,
1454
+ "expected_writes": 1,
1455
+ "actual_writes": posts_after_t,
1456
+ "detail": (
1457
+ f"recovered={t2.result_ref}, executed_on_retry={t2.executed}, "
1458
+ f"posts={posts_after_t}"
1459
+ ),
1460
+ }
1461
+ )
1462
+
1463
+ env["FAKE_GH_MODE"] = "post_commit_crash"
1464
+ c1 = wrap_command(
1465
+ cmd_crash,
1466
+ journal=journal,
1467
+ action_id="s2-gh-crash",
1468
+ session_id="chaos-s2",
1469
+ timeout_seconds=5.0,
1470
+ env=env,
1471
+ github_api_url=gh_srv.base_url,
1472
+ )
1473
+ env["FAKE_GH_MODE"] = "normal"
1474
+ c2 = wrap_command(
1475
+ cmd_crash,
1476
+ journal=journal,
1477
+ action_id="s2-gh-crash",
1478
+ session_id="chaos-s2",
1479
+ timeout_seconds=5.0,
1480
+ env=env,
1481
+ github_api_url=gh_srv.base_url,
1482
+ )
1483
+ crash_posts = gh_srv.post_count - posts_after_t
1484
+ gh_crash_ok = (
1485
+ c1.exit_code != 0
1486
+ and c1.status == ActionStatus.UNKNOWN
1487
+ and c2.exit_code == 0
1488
+ and c2.executed is False
1489
+ and c2.reconciled is True
1490
+ and c2.status == ActionStatus.RECONCILED
1491
+ and c2.result_ref == "https://github.com/acme/app/issues/2"
1492
+ and crash_posts == 1
1493
+ )
1494
+ subchecks.append(
1495
+ {
1496
+ "check": "cli_github_post_commit_crash",
1497
+ "passed": gh_crash_ok,
1498
+ "expected_writes": 1,
1499
+ "actual_writes": crash_posts,
1500
+ "detail": (
1501
+ f"recovered={c2.result_ref}, executed_on_retry={c2.executed}, "
1502
+ f"posts={crash_posts}"
1503
+ ),
1504
+ }
1505
+ )
1506
+
1507
+ # 2b. CLI wrap -> Local bare git repo: slow post-receive hook timeout -> ls-remote reconcile
1508
+ git_repo = _create_chaos_git_repo(root / "git_s2")
1509
+ expected_sha = git_repo.create_branch_commit("feat-post", "post.txt", "post-commit push\n")
1510
+ git_repo.slow_post_flag.write_text("1", encoding="utf-8")
1511
+
1512
+ with Journal(db_path) as journal:
1513
+ git_env = _git_env()
1514
+ p1 = wrap_command(
1515
+ ["git", "push", "origin", "feat-post"],
1516
+ journal=journal,
1517
+ action_id="s2-git-post",
1518
+ session_id="chaos-s2",
1519
+ timeout_seconds=1.0,
1520
+ cwd=git_repo.work_dir,
1521
+ env=git_env,
1522
+ )
1523
+ git_repo.slow_post_flag.unlink(missing_ok=True)
1524
+ p2 = wrap_command(
1525
+ ["git", "push", "origin", "feat-post"],
1526
+ journal=journal,
1527
+ action_id="s2-git-post",
1528
+ session_id="chaos-s2",
1529
+ timeout_seconds=5.0,
1530
+ cwd=git_repo.work_dir,
1531
+ env=git_env,
1532
+ )
1533
+ events = git_repo.push_events_for_ref("refs/heads/feat-post")
1534
+ push_attempts = git_repo.push_attempt_count()
1535
+ remote_sha = git_repo.remote_ref_sha("refs/heads/feat-post")
1536
+ expected_ref = f"origin refs/heads/feat-post@{expected_sha[:12]}"
1537
+ git_post_ok = (
1538
+ p1.exit_code == EXIT_TIMEOUT
1539
+ and p1.status == ActionStatus.UNKNOWN
1540
+ and p2.exit_code == 0
1541
+ and p2.executed is False
1542
+ and p2.reconciled is True
1543
+ and p2.status == ActionStatus.RECONCILED
1544
+ and p2.result_ref == expected_ref
1545
+ and len(events) == 1
1546
+ and push_attempts == 1
1547
+ and remote_sha == expected_sha
1548
+ )
1549
+ subchecks.append(
1550
+ {
1551
+ "check": "cli_git_push_post_commit_timeout",
1552
+ "passed": git_post_ok,
1553
+ "expected_writes": 1,
1554
+ "actual_writes": max(len(events), push_attempts),
1555
+ "detail": (
1556
+ f"recovered={p2.result_ref}, executed_on_retry={p2.executed}, "
1557
+ f"remote_pushes={len(events)}, receive_pack_contacts={push_attempts}"
1558
+ ),
1559
+ }
1560
+ )
1561
+
1562
+ # 2c. MCP proxy -> Mock stdio MCP server: post-commit crash & timeout -> 0 duplicate writes
1563
+ server_script, ledger_path, mode_file = _create_mock_mcp_server(root / "mcp_s2")
1564
+ crash_call = {
1565
+ "jsonrpc": "2.0",
1566
+ "id": 10,
1567
+ "method": "tools/call",
1568
+ "params": {
1569
+ "name": "create_ticket",
1570
+ "arguments": {
1571
+ "_sidefx_action_id": "s2-mcp-crash",
1572
+ "ticket_key": "T-POST-CRASH",
1573
+ "title": "Crash after commit",
1574
+ },
1575
+ },
1576
+ }
1577
+ mode_file.write_text("post_commit_crash", encoding="utf-8")
1578
+ with _MCPInProcessClient(
1579
+ db_path=db_path,
1580
+ server_script=server_script,
1581
+ ledger_path=ledger_path,
1582
+ mode_file=mode_file,
1583
+ session_id="chaos-s2",
1584
+ target="mcp:s2",
1585
+ ) as c_crash:
1586
+ resp_c1 = c_crash.request(crash_call)
1587
+
1588
+ # Retry WITHOUT hook -> blocked with OUTCOME UNKNOWN, 0 duplicate writes
1589
+ mode_file.write_text("normal", encoding="utf-8")
1590
+ with _MCPInProcessClient(
1591
+ db_path=db_path,
1592
+ server_script=server_script,
1593
+ ledger_path=ledger_path,
1594
+ mode_file=mode_file,
1595
+ session_id="chaos-s2",
1596
+ target="mcp:s2",
1597
+ ) as c_block:
1598
+ resp_c2 = c_block.request({**crash_call, "id": 11})
1599
+
1600
+ # Retry WITH reconciler hook -> recovers exact remote URL with 0 duplicate writes
1601
+ hook = _make_mcp_ledger_reconciler(ledger_path, {"s2-mcp-crash": "T-POST-CRASH"})
1602
+ with _MCPInProcessClient(
1603
+ db_path=db_path,
1604
+ server_script=server_script,
1605
+ ledger_path=ledger_path,
1606
+ mode_file=mode_file,
1607
+ session_id="chaos-s2",
1608
+ target="mcp:s2",
1609
+ reconciler_hook=hook,
1610
+ ) as c_rec:
1611
+ resp_c3 = c_rec.request({**crash_call, "id": 12})
1612
+
1613
+ crash_entries = [
1614
+ e
1615
+ for e in _read_mcp_ledger(ledger_path)
1616
+ if e.get("arguments", {}).get("ticket_key") == "T-POST-CRASH"
1617
+ ]
1618
+ sidefx_meta = resp_c3.get("result", {}).get("_sidefx", {})
1619
+ mcp_crash_ok = (
1620
+ resp_c1.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1621
+ and OUTCOME_UNKNOWN_BANNER in resp_c1.get("error", {}).get("message", "")
1622
+ and resp_c2.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1623
+ and sidefx_meta.get("replayed") is True
1624
+ and sidefx_meta.get("status") == "reconciled"
1625
+ and sidefx_meta.get("result_ref") == "https://tickets.sidefx.test/items/1"
1626
+ and len(crash_entries) == 1
1627
+ )
1628
+ subchecks.append(
1629
+ {
1630
+ "check": "mcp_proxy_post_commit_crash",
1631
+ "passed": mcp_crash_ok,
1632
+ "expected_writes": 1,
1633
+ "actual_writes": len(crash_entries),
1634
+ "detail": (
1635
+ f"blocked_without_hook={resp_c2.get('error', {}).get('code')}, "
1636
+ f"reconciled_ref={sidefx_meta.get('result_ref')}, writes={len(crash_entries)}"
1637
+ ),
1638
+ }
1639
+ )
1640
+
1641
+ # Also test MCP post-commit timeout -> retry blocked while in-flight, 0 duplicate writes
1642
+ timeout_call = {
1643
+ "jsonrpc": "2.0",
1644
+ "id": 20,
1645
+ "method": "tools/call",
1646
+ "params": {
1647
+ "name": "create_ticket",
1648
+ "arguments": {
1649
+ "_sidefx_action_id": "s2-mcp-timeout",
1650
+ "ticket_key": "T-POST-TIMEOUT",
1651
+ "title": "Timeout after commit",
1652
+ },
1653
+ },
1654
+ }
1655
+ mode_file.write_text("post_commit_timeout", encoding="utf-8")
1656
+ with _MCPInProcessClient(
1657
+ db_path=db_path,
1658
+ server_script=server_script,
1659
+ ledger_path=ledger_path,
1660
+ mode_file=mode_file,
1661
+ session_id="chaos-s2",
1662
+ target="mcp:s2",
1663
+ timeout_seconds=0.5,
1664
+ ) as c_to:
1665
+ # Warm up upstream interpreter so cold start does not eat the timeout window.
1666
+ _ = c_to.request({"jsonrpc": "2.0", "id": 19, "method": "initialize", "params": {}})
1667
+ resp_t1 = c_to.request(timeout_call)
1668
+ # Immediate retry on the live proxy must be blocked (never double-executes!)
1669
+ resp_t2 = c_to.request({**timeout_call, "id": 21})
1670
+
1671
+ timeout_entries = [
1672
+ e
1673
+ for e in _read_mcp_ledger(ledger_path)
1674
+ if e.get("arguments", {}).get("ticket_key") == "T-POST-TIMEOUT"
1675
+ ]
1676
+ mcp_timeout_ok = (
1677
+ resp_t1.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1678
+ and resp_t2.get("error", {}).get("code") == ERR_OUTCOME_UNKNOWN
1679
+ and len(timeout_entries) == 1
1680
+ )
1681
+ subchecks.append(
1682
+ {
1683
+ "check": "mcp_proxy_post_commit_timeout",
1684
+ "passed": mcp_timeout_ok,
1685
+ "expected_writes": 1,
1686
+ "actual_writes": len(timeout_entries),
1687
+ "detail": (
1688
+ f"timeout_err={resp_t1.get('error', {}).get('code')}, "
1689
+ f"retry_err={resp_t2.get('error', {}).get('code')}, "
1690
+ f"writes={len(timeout_entries)}"
1691
+ ),
1692
+ }
1693
+ )
1694
+
1695
+ dups, exp_w, act_w = _count_duplicates(subchecks)
1696
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0
1697
+ return ScenarioResult(
1698
+ name=name,
1699
+ title=title,
1700
+ passed=all_passed,
1701
+ duration_ms=(time.perf_counter() - started) * 1000.0,
1702
+ duplicate_remote_writes=dups,
1703
+ expected_remote_writes=exp_w,
1704
+ actual_remote_writes=act_w,
1705
+ details=f"{sum(1 for c in subchecks if c['passed'])}/{len(subchecks)} surfaces verified",
1706
+ error=None if all_passed else "One or more post-commit reconciliation checks failed",
1707
+ subchecks=tuple(subchecks),
1708
+ )
1709
+
1710
+
1711
+ # ---------------------------------------------------------------------------
1712
+ # Chaos Scenario 3: Concurrent duplicate dispatch from multiple workers
1713
+ # ---------------------------------------------------------------------------
1714
+
1715
+
1716
+ def _scenario_concurrent_duplicate_dispatch() -> ScenarioResult:
1717
+ name = "concurrent_duplicate_dispatch"
1718
+ title = "Concurrent multi-worker duplicate dispatch"
1719
+ started = time.perf_counter()
1720
+ subchecks: list[dict[str, Any]] = []
1721
+ worker_count = 4
1722
+
1723
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s3-") as tmp:
1724
+ root = Path(tmp)
1725
+ db_path = root / "journal.db"
1726
+
1727
+ with _ChaosGitHubServer() as gh_srv:
1728
+ fake_gh = _create_fake_gh(root)
1729
+ env = _isolated_env({"FAKE_GH_API_URL": gh_srv.base_url})
1730
+ env["FAKE_GH_MODE"] = "normal"
1731
+ env["FAKE_GH_HOLD_MS"] = "350"
1732
+
1733
+ cfg_path = _write_default_config(root)
1734
+ wrap_cmd = [
1735
+ sys.executable,
1736
+ "-m",
1737
+ "sidefx",
1738
+ "wrap",
1739
+ "--config",
1740
+ str(cfg_path),
1741
+ "--db",
1742
+ str(db_path),
1743
+ "--session-id",
1744
+ "chaos-s3",
1745
+ "--action-id",
1746
+ "s3-race-issue",
1747
+ "--github-api-url",
1748
+ gh_srv.base_url,
1749
+ "--",
1750
+ str(fake_gh),
1751
+ "issue",
1752
+ "create",
1753
+ "-R",
1754
+ "acme/app",
1755
+ "--title",
1756
+ "Concurrent Race",
1757
+ "--body",
1758
+ "Exactly one remote write",
1759
+ ]
1760
+
1761
+ popen_extra: dict[str, Any] = {"start_new_session": True} if os.name == "posix" else {}
1762
+ procs = [
1763
+ subprocess.Popen(
1764
+ wrap_cmd,
1765
+ cwd=str(root),
1766
+ stdout=subprocess.PIPE,
1767
+ stderr=subprocess.PIPE,
1768
+ text=True,
1769
+ env=env,
1770
+ **popen_extra,
1771
+ )
1772
+ for _ in range(worker_count)
1773
+ ]
1774
+ exit_codes: list[int] = []
1775
+ outputs: list[tuple[str, str]] = []
1776
+ try:
1777
+ for proc in procs:
1778
+ out, err = proc.communicate(timeout=15.0)
1779
+ exit_codes.append(proc.returncode)
1780
+ outputs.append((out.strip(), err.strip()))
1781
+ finally:
1782
+ for proc in procs:
1783
+ if proc.poll() is None:
1784
+ if os.name == "posix":
1785
+ with contextlib.suppress(OSError):
1786
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
1787
+ else:
1788
+ with contextlib.suppress(OSError):
1789
+ proc.kill()
1790
+ with contextlib.suppress(subprocess.TimeoutExpired):
1791
+ proc.wait(timeout=2.0)
1792
+ for stream in (proc.stdout, proc.stderr):
1793
+ if stream is not None:
1794
+ with contextlib.suppress(OSError):
1795
+ stream.close()
1796
+
1797
+ # Follow-up call must replay cleanly with 0 additional POSTs
1798
+ env["FAKE_GH_HOLD_MS"] = "0"
1799
+ replay_proc = subprocess.run(
1800
+ wrap_cmd,
1801
+ cwd=str(root),
1802
+ capture_output=True,
1803
+ text=True,
1804
+ env=env,
1805
+ timeout=10.0,
1806
+ check=False,
1807
+ )
1808
+
1809
+ with Journal.open_readonly(db_path) as journal:
1810
+ rows = journal.list_actions(session_id="chaos-s3")
1811
+
1812
+ valid_codes = all(code in (0, EXIT_OUTCOME_UNKNOWN) for code in exit_codes)
1813
+ at_least_one_ok = any(code == 0 for code in exit_codes)
1814
+ race_ok = (
1815
+ gh_srv.post_count == 1
1816
+ and valid_codes
1817
+ and at_least_one_ok
1818
+ and replay_proc.returncode == 0
1819
+ and "https://github.com/acme/app/issues/1" in replay_proc.stdout
1820
+ and len(rows) == 1
1821
+ and rows[0].status in (ActionStatus.CONFIRMED, ActionStatus.RECONCILED)
1822
+ and rows[0].result_ref == "https://github.com/acme/app/issues/1"
1823
+ )
1824
+ subchecks.append(
1825
+ {
1826
+ "check": "multiprocess_wrap_race",
1827
+ "passed": race_ok,
1828
+ "expected_writes": 1,
1829
+ "actual_writes": gh_srv.post_count,
1830
+ "detail": (
1831
+ f"workers={worker_count}, exit_codes={exit_codes}, "
1832
+ f"remote_posts={gh_srv.post_count}, journal_rows={len(rows)}"
1833
+ ),
1834
+ }
1835
+ )
1836
+
1837
+ dups, exp_w, act_w = _count_duplicates(subchecks)
1838
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0
1839
+ return ScenarioResult(
1840
+ name=name,
1841
+ title=title,
1842
+ passed=all_passed,
1843
+ duration_ms=(time.perf_counter() - started) * 1000.0,
1844
+ duplicate_remote_writes=dups,
1845
+ expected_remote_writes=exp_w,
1846
+ actual_remote_writes=act_w,
1847
+ details=f"{worker_count} concurrent OS workers -> {act_w} remote write",
1848
+ error=None if all_passed else "Concurrent dispatch race allowed duplicate or invalid state",
1849
+ subchecks=tuple(subchecks),
1850
+ )
1851
+
1852
+
1853
+ # ---------------------------------------------------------------------------
1854
+ # Chaos Scenario 4: Payload mutation under reused action_id (CLI + MCP)
1855
+ # ---------------------------------------------------------------------------
1856
+
1857
+
1858
+ def _scenario_payload_mutation_reused_id() -> ScenarioResult:
1859
+ name = "payload_mutation_reused_id"
1860
+ title = "Payload mutation under reused action_id"
1861
+ started = time.perf_counter()
1862
+ subchecks: list[dict[str, Any]] = []
1863
+
1864
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s4-") as tmp:
1865
+ root = Path(tmp)
1866
+ db_path = root / "journal.db"
1867
+
1868
+ # 4a. CLI wrap: mutated args under both confirmed AND unknown action_id rejected
1869
+ with _ChaosGitHubServer() as gh_srv:
1870
+ fake_gh = _create_fake_gh(root)
1871
+ env = _isolated_env({"FAKE_GH_API_URL": gh_srv.base_url})
1872
+
1873
+ with Journal(db_path) as journal:
1874
+ env["FAKE_GH_MODE"] = "normal"
1875
+ r1 = wrap_command(
1876
+ [
1877
+ str(fake_gh),
1878
+ "issue",
1879
+ "create",
1880
+ "-R",
1881
+ "acme/app",
1882
+ "--title",
1883
+ "Original",
1884
+ "--body",
1885
+ "Original body",
1886
+ ],
1887
+ journal=journal,
1888
+ action_id="s4-cli-confirmed",
1889
+ session_id="chaos-s4",
1890
+ env=env,
1891
+ github_api_url=gh_srv.base_url,
1892
+ )
1893
+ r2 = wrap_command(
1894
+ [
1895
+ str(fake_gh),
1896
+ "issue",
1897
+ "create",
1898
+ "-R",
1899
+ "acme/app",
1900
+ "--title",
1901
+ "Tampered",
1902
+ "--body",
1903
+ "Original body",
1904
+ ],
1905
+ journal=journal,
1906
+ action_id="s4-cli-confirmed",
1907
+ session_id="chaos-s4",
1908
+ env=env,
1909
+ github_api_url=gh_srv.base_url,
1910
+ )
1911
+
1912
+ # Also verify payload mutation against an UNKNOWN row is rejected before dispatch
1913
+ env["FAKE_GH_MODE"] = "post_commit_crash"
1914
+ r3 = wrap_command(
1915
+ [
1916
+ str(fake_gh),
1917
+ "issue",
1918
+ "create",
1919
+ "-R",
1920
+ "acme/app",
1921
+ "--title",
1922
+ "Unknown original",
1923
+ "--body",
1924
+ "Crash body",
1925
+ ],
1926
+ journal=journal,
1927
+ action_id="s4-cli-unknown",
1928
+ session_id="chaos-s4",
1929
+ env=env,
1930
+ github_api_url=gh_srv.base_url,
1931
+ )
1932
+ env["FAKE_GH_MODE"] = "normal"
1933
+ r4 = wrap_command(
1934
+ [
1935
+ str(fake_gh),
1936
+ "issue",
1937
+ "create",
1938
+ "-R",
1939
+ "acme/app",
1940
+ "--title",
1941
+ "Unknown tampered",
1942
+ "--body",
1943
+ "Crash body",
1944
+ ],
1945
+ journal=journal,
1946
+ action_id="s4-cli-unknown",
1947
+ session_id="chaos-s4",
1948
+ env=env,
1949
+ github_api_url=gh_srv.base_url,
1950
+ )
1951
+
1952
+ cli_mut_ok = (
1953
+ r1.exit_code == 0
1954
+ and r2.exit_code == EXIT_PAYLOAD_MISMATCH
1955
+ and r2.executed is False
1956
+ and r3.status == ActionStatus.UNKNOWN
1957
+ and r4.exit_code == EXIT_PAYLOAD_MISMATCH
1958
+ and r4.executed is False
1959
+ and gh_srv.post_count == 2
1960
+ )
1961
+ subchecks.append(
1962
+ {
1963
+ "check": "cli_wrap_payload_mutation",
1964
+ "passed": cli_mut_ok,
1965
+ "expected_writes": 2,
1966
+ "actual_writes": gh_srv.post_count,
1967
+ "detail": (
1968
+ f"confirmed_tamper_exit={r2.exit_code}, "
1969
+ f"unknown_tamper_exit={r4.exit_code}, posts={gh_srv.post_count}"
1970
+ ),
1971
+ }
1972
+ )
1973
+
1974
+ # 4b. MCP proxy subprocess: mutated arguments under reused _sidefx_action_id rejected
1975
+ server_script, ledger_path, mode_file = _create_mock_mcp_server(root / "mcp_s4")
1976
+ mode_file.write_text("normal", encoding="utf-8")
1977
+ with _MCPSubprocessClient(
1978
+ db_path=db_path,
1979
+ server_script=server_script,
1980
+ ledger_path=ledger_path,
1981
+ mode_file=mode_file,
1982
+ session_id="chaos-s4",
1983
+ cwd=root,
1984
+ target="mcp:s4",
1985
+ ) as mcp_cli:
1986
+ m1 = mcp_cli.request(
1987
+ {
1988
+ "jsonrpc": "2.0",
1989
+ "id": 1,
1990
+ "method": "tools/call",
1991
+ "params": {
1992
+ "name": "create_ticket",
1993
+ "arguments": {
1994
+ "_sidefx_action_id": "s4-mcp-1",
1995
+ "title": "Original ticket",
1996
+ },
1997
+ },
1998
+ }
1999
+ )
2000
+ m2 = mcp_cli.request(
2001
+ {
2002
+ "jsonrpc": "2.0",
2003
+ "id": 2,
2004
+ "method": "tools/call",
2005
+ "params": {
2006
+ "name": "create_ticket",
2007
+ "arguments": {
2008
+ "_sidefx_action_id": "s4-mcp-1",
2009
+ "title": "Tampered ticket",
2010
+ },
2011
+ },
2012
+ }
2013
+ )
2014
+
2015
+ mcp_writes = len(_read_mcp_ledger(ledger_path))
2016
+ mcp_mut_ok = (
2017
+ "result" in m1
2018
+ and m2.get("error", {}).get("code") == ERR_PAYLOAD_MISMATCH
2019
+ and m2.get("error", {}).get("data", {}).get("kind") == "payload_mismatch"
2020
+ and mcp_writes == 1
2021
+ )
2022
+ subchecks.append(
2023
+ {
2024
+ "check": "mcp_proxy_payload_mutation",
2025
+ "passed": mcp_mut_ok,
2026
+ "expected_writes": 1,
2027
+ "actual_writes": mcp_writes,
2028
+ "detail": (
2029
+ f"tamper_err={m2.get('error', {}).get('code')}, ledger_writes={mcp_writes}"
2030
+ ),
2031
+ }
2032
+ )
2033
+
2034
+ dups, exp_w, act_w = _count_duplicates(subchecks)
2035
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0
2036
+ return ScenarioResult(
2037
+ name=name,
2038
+ title=title,
2039
+ passed=all_passed,
2040
+ duration_ms=(time.perf_counter() - started) * 1000.0,
2041
+ duplicate_remote_writes=dups,
2042
+ expected_remote_writes=exp_w,
2043
+ actual_remote_writes=act_w,
2044
+ details="CLI & MCP reused-ID mutations rejected pre-dispatch",
2045
+ error=None if all_passed else "Payload mutation check failed",
2046
+ subchecks=tuple(subchecks),
2047
+ )
2048
+
2049
+
2050
+ # ---------------------------------------------------------------------------
2051
+ # Chaos Scenario 5: Preflight numeric cap & string/domain denylist violations
2052
+ # ---------------------------------------------------------------------------
2053
+
2054
+
2055
+ def _scenario_preflight_policy_enforcement() -> ScenarioResult:
2056
+ name = "preflight_policy_enforcement"
2057
+ title = "Preflight caps & denylist enforcement"
2058
+ started = time.perf_counter()
2059
+ subchecks: list[dict[str, Any]] = []
2060
+
2061
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s5-") as tmp:
2062
+ root = Path(tmp)
2063
+ db_path = root / "journal.db"
2064
+ cfg_path = root / ".sidefx.json"
2065
+ cfg = SidefxConfig(
2066
+ preflight=PreflightConfig(
2067
+ rules=(
2068
+ PreflightRule(
2069
+ tool="refund_payment",
2070
+ arg="amount",
2071
+ max_value=50,
2072
+ reason="Refund cap is $50",
2073
+ ),
2074
+ PreflightRule(
2075
+ tool="push_branch",
2076
+ arg="branch",
2077
+ deny=("main", "master", "release/*"),
2078
+ reason="Protected branch",
2079
+ ),
2080
+ PreflightRule(
2081
+ tool="send_email",
2082
+ arg="to",
2083
+ allow_domains=("acme.test",),
2084
+ deny_domains=("evil.test",),
2085
+ reason="Internal recipients only",
2086
+ ),
2087
+ )
2088
+ )
2089
+ )
2090
+ cfg_path.write_text(json.dumps(cfg.to_dict(), indent=2), encoding="utf-8")
2091
+ # Validate config parses cleanly via load_config
2092
+ _ = load_config(cfg_path)
2093
+
2094
+ server_script, ledger_path, mode_file = _create_mock_mcp_server(root / "mcp_s5")
2095
+ mode_file.write_text("normal", encoding="utf-8")
2096
+
2097
+ with _MCPSubprocessClient(
2098
+ db_path=db_path,
2099
+ server_script=server_script,
2100
+ ledger_path=ledger_path,
2101
+ mode_file=mode_file,
2102
+ session_id="chaos-s5",
2103
+ cwd=root,
2104
+ target="mcp:s5",
2105
+ config_path=cfg_path,
2106
+ ) as mcp_cli:
2107
+ # Blocked calls (0 remote writes expected)
2108
+ r_cap = mcp_cli.request(
2109
+ {
2110
+ "jsonrpc": "2.0",
2111
+ "id": 1,
2112
+ "method": "tools/call",
2113
+ "params": {
2114
+ "name": "refund_payment",
2115
+ "arguments": {"_sidefx_action_id": "s5-cap-bad", "amount": 250},
2116
+ },
2117
+ }
2118
+ )
2119
+ r_branch = mcp_cli.request(
2120
+ {
2121
+ "jsonrpc": "2.0",
2122
+ "id": 2,
2123
+ "method": "tools/call",
2124
+ "params": {
2125
+ "name": "push_branch",
2126
+ "arguments": {"_sidefx_action_id": "s5-branch-bad", "branch": "main"},
2127
+ },
2128
+ }
2129
+ )
2130
+ r_deny_dom = mcp_cli.request(
2131
+ {
2132
+ "jsonrpc": "2.0",
2133
+ "id": 3,
2134
+ "method": "tools/call",
2135
+ "params": {
2136
+ "name": "send_email",
2137
+ "arguments": {
2138
+ "_sidefx_action_id": "s5-email-deny",
2139
+ "to": "attacker@evil.test",
2140
+ },
2141
+ },
2142
+ }
2143
+ )
2144
+ r_outside_dom = mcp_cli.request(
2145
+ {
2146
+ "jsonrpc": "2.0",
2147
+ "id": 4,
2148
+ "method": "tools/call",
2149
+ "params": {
2150
+ "name": "send_email",
2151
+ "arguments": {
2152
+ "_sidefx_action_id": "s5-email-outside",
2153
+ "to": "user@other.org",
2154
+ },
2155
+ },
2156
+ }
2157
+ )
2158
+
2159
+ writes_after_blocks = len(_read_mcp_ledger(ledger_path))
2160
+
2161
+ # Allowed calls (2 remote writes expected — proves rules are selective)
2162
+ r_cap_ok = mcp_cli.request(
2163
+ {
2164
+ "jsonrpc": "2.0",
2165
+ "id": 5,
2166
+ "method": "tools/call",
2167
+ "params": {
2168
+ "name": "refund_payment",
2169
+ "arguments": {"_sidefx_action_id": "s5-cap-ok", "amount": 25},
2170
+ },
2171
+ }
2172
+ )
2173
+ r_email_ok = mcp_cli.request(
2174
+ {
2175
+ "jsonrpc": "2.0",
2176
+ "id": 6,
2177
+ "method": "tools/call",
2178
+ "params": {
2179
+ "name": "send_email",
2180
+ "arguments": {
2181
+ "_sidefx_action_id": "s5-email-ok",
2182
+ "to": "ops@acme.test",
2183
+ },
2184
+ },
2185
+ }
2186
+ )
2187
+
2188
+ ledger_entries = _read_mcp_ledger(ledger_path)
2189
+ with Journal.open_readonly(db_path) as journal:
2190
+ recorded_ids = {rec.action_id for rec in journal.list_actions(session_id="chaos-s5")}
2191
+
2192
+ blocked_resps = (r_cap, r_branch, r_deny_dom, r_outside_dom)
2193
+ all_blocked = all(
2194
+ resp.get("error", {}).get("code") == ERR_PREFLIGHT_DENIED
2195
+ and resp.get("error", {}).get("data", {}).get("kind") == "preflight_denied"
2196
+ for resp in blocked_resps
2197
+ )
2198
+ subchecks.append(
2199
+ {
2200
+ "check": "preflight_blocked_violations",
2201
+ "passed": all_blocked and writes_after_blocks == 0,
2202
+ "expected_writes": 0,
2203
+ "actual_writes": writes_after_blocks,
2204
+ "detail": (
2205
+ f"blocked_calls={len(blocked_resps)}, writes_on_blocked={writes_after_blocks}"
2206
+ ),
2207
+ }
2208
+ )
2209
+
2210
+ allowed_writes = len(ledger_entries) - writes_after_blocks
2211
+ allowed_ok = (
2212
+ "result" in r_cap_ok
2213
+ and "result" in r_email_ok
2214
+ and allowed_writes == 2
2215
+ and recorded_ids == {"s5-cap-ok", "s5-email-ok"}
2216
+ )
2217
+ subchecks.append(
2218
+ {
2219
+ "check": "preflight_allowed_control_calls",
2220
+ "passed": allowed_ok,
2221
+ "expected_writes": 2,
2222
+ "actual_writes": allowed_writes,
2223
+ "detail": f"allowed_writes={allowed_writes}, journal_ids={sorted(recorded_ids)}",
2224
+ }
2225
+ )
2226
+
2227
+ dups, exp_w, act_w = _count_duplicates(subchecks)
2228
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0
2229
+ return ScenarioResult(
2230
+ name=name,
2231
+ title=title,
2232
+ passed=all_passed,
2233
+ duration_ms=(time.perf_counter() - started) * 1000.0,
2234
+ duplicate_remote_writes=dups,
2235
+ expected_remote_writes=exp_w,
2236
+ actual_remote_writes=act_w,
2237
+ details="4 policy violations blocked (0 writes); 2 valid calls allowed",
2238
+ error=None if all_passed else "Preflight policy enforcement check failed",
2239
+ subchecks=tuple(subchecks),
2240
+ )
2241
+
2242
+
2243
+ # ---------------------------------------------------------------------------
2244
+ # Chaos Scenario 6: Session-end receipt ground-truth completeness
2245
+ # ---------------------------------------------------------------------------
2246
+
2247
+
2248
+ def _scenario_session_receipt_ground_truth() -> ScenarioResult:
2249
+ name = "session_receipt_ground_truth"
2250
+ title = "Session-end receipt ground-truth accuracy"
2251
+ started = time.perf_counter()
2252
+ subchecks: list[dict[str, Any]] = []
2253
+ session_id = "chaos-receipt-session"
2254
+
2255
+ with tempfile.TemporaryDirectory(prefix="sidefx-chaos-s6-") as tmp:
2256
+ root = Path(tmp)
2257
+ db_path = root / "journal.db"
2258
+
2259
+ with _ChaosGitHubServer() as gh_srv:
2260
+ fake_gh = _create_fake_gh(root)
2261
+ git_repo = _create_chaos_git_repo(root / "git_s6")
2262
+ server_script, ledger_path, mode_file = _create_mock_mcp_server(root / "mcp_s6")
2263
+
2264
+ env = _isolated_env({"FAKE_GH_API_URL": gh_srv.base_url})
2265
+
2266
+ with Journal(db_path) as journal:
2267
+ # 1. CLI GitHub confirmed
2268
+ env["FAKE_GH_MODE"] = "normal"
2269
+ gh_ok = wrap_command(
2270
+ [
2271
+ str(fake_gh),
2272
+ "issue",
2273
+ "create",
2274
+ "-R",
2275
+ "acme/app",
2276
+ "--title",
2277
+ "Receipt Confirmed",
2278
+ "--body",
2279
+ "Confirmed issue",
2280
+ ],
2281
+ journal=journal,
2282
+ action_id="s6-gh-confirmed",
2283
+ session_id=session_id,
2284
+ env=env,
2285
+ github_api_url=gh_srv.base_url,
2286
+ )
2287
+
2288
+ # 2. CLI GitHub reconciled (post-commit timeout -> retry recovers URL)
2289
+ cmd_gh_rec = [
2290
+ str(fake_gh),
2291
+ "issue",
2292
+ "create",
2293
+ "-R",
2294
+ "acme/app",
2295
+ "--title",
2296
+ "Receipt Reconciled",
2297
+ "--body",
2298
+ "Reconciled issue",
2299
+ ]
2300
+ env["FAKE_GH_MODE"] = "post_commit_timeout"
2301
+ _ = wrap_command(
2302
+ cmd_gh_rec,
2303
+ journal=journal,
2304
+ action_id="s6-gh-reconciled",
2305
+ session_id=session_id,
2306
+ timeout_seconds=1.0,
2307
+ env=env,
2308
+ github_api_url=gh_srv.base_url,
2309
+ )
2310
+ env["FAKE_GH_MODE"] = "normal"
2311
+ gh_rec = wrap_command(
2312
+ cmd_gh_rec,
2313
+ journal=journal,
2314
+ action_id="s6-gh-reconciled",
2315
+ session_id=session_id,
2316
+ timeout_seconds=5.0,
2317
+ env=env,
2318
+ github_api_url=gh_srv.base_url,
2319
+ )
2320
+
2321
+ # 3. CLI Git push reconciled (slow post-receive timeout -> retry recovers ref)
2322
+ push_sha = git_repo.create_branch_commit(
2323
+ "feat-receipt", "receipt.txt", "ground truth\n"
2324
+ )
2325
+ git_env = _git_env()
2326
+ git_repo.slow_post_flag.write_text("1", encoding="utf-8")
2327
+ _ = wrap_command(
2328
+ ["git", "push", "origin", "feat-receipt"],
2329
+ journal=journal,
2330
+ action_id="s6-git-reconciled",
2331
+ session_id=session_id,
2332
+ timeout_seconds=1.0,
2333
+ cwd=git_repo.work_dir,
2334
+ env=git_env,
2335
+ )
2336
+ git_repo.slow_post_flag.unlink(missing_ok=True)
2337
+ git_rec = wrap_command(
2338
+ ["git", "push", "origin", "feat-receipt"],
2339
+ journal=journal,
2340
+ action_id="s6-git-reconciled",
2341
+ session_id=session_id,
2342
+ timeout_seconds=5.0,
2343
+ cwd=git_repo.work_dir,
2344
+ env=git_env,
2345
+ )
2346
+
2347
+ # 4. CLI generic failed command (0 remote writes)
2348
+ cli_fail = wrap_command(
2349
+ [
2350
+ sys.executable,
2351
+ "-c",
2352
+ "import sys; print('boom', file=sys.stderr); sys.exit(1)",
2353
+ ],
2354
+ journal=journal,
2355
+ action_id="s6-cli-failed",
2356
+ session_id=session_id,
2357
+ target="deploy:script",
2358
+ tool_name="deploy_script",
2359
+ env=_isolated_env(),
2360
+ )
2361
+
2362
+ # 5-7. MCP confirmed + MCP failed + MCP unknown (crashed after write)
2363
+ mode_file.write_text("normal", encoding="utf-8")
2364
+ with _MCPSubprocessClient(
2365
+ db_path=db_path,
2366
+ server_script=server_script,
2367
+ ledger_path=ledger_path,
2368
+ mode_file=mode_file,
2369
+ session_id=session_id,
2370
+ cwd=root,
2371
+ target="mcp:s6",
2372
+ ) as mcp_cli:
2373
+ # Read-only call must NOT appear in receipt
2374
+ _ = mcp_cli.request(
2375
+ {
2376
+ "jsonrpc": "2.0",
2377
+ "id": 1,
2378
+ "method": "tools/call",
2379
+ "params": {"name": "get_item", "arguments": {"id": 99}},
2380
+ }
2381
+ )
2382
+ _ = mcp_cli.request(
2383
+ {
2384
+ "jsonrpc": "2.0",
2385
+ "id": 2,
2386
+ "method": "tools/call",
2387
+ "params": {
2388
+ "name": "create_ticket",
2389
+ "arguments": {
2390
+ "_sidefx_action_id": "s6-mcp-confirmed",
2391
+ "title": "Deploy checklist",
2392
+ },
2393
+ },
2394
+ }
2395
+ )
2396
+ mode_file.write_text("validation_error", encoding="utf-8")
2397
+ _ = mcp_cli.request(
2398
+ {
2399
+ "jsonrpc": "2.0",
2400
+ "id": 3,
2401
+ "method": "tools/call",
2402
+ "params": {
2403
+ "name": "create_ticket",
2404
+ "arguments": {
2405
+ "_sidefx_action_id": "s6-mcp-failed",
2406
+ "title": "Invalid ticket",
2407
+ },
2408
+ },
2409
+ }
2410
+ )
2411
+ mode_file.write_text("post_commit_crash", encoding="utf-8")
2412
+ _ = mcp_cli.request(
2413
+ {
2414
+ "jsonrpc": "2.0",
2415
+ "id": 4,
2416
+ "method": "tools/call",
2417
+ "params": {
2418
+ "name": "create_ticket",
2419
+ "arguments": {
2420
+ "_sidefx_action_id": "s6-mcp-unknown",
2421
+ "title": "Crashed ticket",
2422
+ },
2423
+ },
2424
+ }
2425
+ )
2426
+
2427
+ cfg_path = _write_default_config(root)
2428
+ # Run the REAL `sidefx report` CLI in both JSON and Markdown formats
2429
+ report_json_proc = subprocess.run(
2430
+ [
2431
+ sys.executable,
2432
+ "-m",
2433
+ "sidefx",
2434
+ "report",
2435
+ "--config",
2436
+ str(cfg_path),
2437
+ "--db",
2438
+ str(db_path),
2439
+ "--session-id",
2440
+ session_id,
2441
+ "--format",
2442
+ "json",
2443
+ ],
2444
+ cwd=str(root),
2445
+ env=_isolated_env(),
2446
+ capture_output=True,
2447
+ text=True,
2448
+ timeout=10.0,
2449
+ check=False,
2450
+ )
2451
+ report_md_proc = subprocess.run(
2452
+ [
2453
+ sys.executable,
2454
+ "-m",
2455
+ "sidefx",
2456
+ "report",
2457
+ "--config",
2458
+ str(cfg_path),
2459
+ "--db",
2460
+ str(db_path),
2461
+ "--session-id",
2462
+ session_id,
2463
+ "--format",
2464
+ "markdown",
2465
+ ],
2466
+ cwd=str(root),
2467
+ env=_isolated_env(),
2468
+ capture_output=True,
2469
+ text=True,
2470
+ timeout=10.0,
2471
+ check=False,
2472
+ )
2473
+
2474
+ # Build ground-truth sets strictly from the remote mock servers & bare git repo
2475
+ gh_urls = {item["html_url"] for item in gh_srv.issues}
2476
+ git_events = git_repo.push_events_for_ref("refs/heads/feat-receipt")
2477
+ git_attempts = git_repo.push_attempt_count()
2478
+ remote_git_sha = git_repo.remote_ref_sha("refs/heads/feat-receipt")
2479
+ expected_git_ref = (
2480
+ f"origin refs/heads/feat-receipt@{remote_git_sha[:12]}"
2481
+ if remote_git_sha is not None
2482
+ else None
2483
+ )
2484
+ mcp_entries = _read_mcp_ledger(ledger_path)
2485
+ mcp_confirmed_entries = [
2486
+ e for e in mcp_entries if e.get("arguments", {}).get("title") == "Deploy checklist"
2487
+ ]
2488
+ mcp_crashed_entries = [
2489
+ e for e in mcp_entries if e.get("arguments", {}).get("title") == "Crashed ticket"
2490
+ ]
2491
+
2492
+ expected_confirmed_reconciled_refs = set(gh_urls)
2493
+ if expected_git_ref is not None:
2494
+ expected_confirmed_reconciled_refs.add(expected_git_ref)
2495
+ if mcp_confirmed_entries:
2496
+ expected_confirmed_reconciled_refs.add(str(mcp_confirmed_entries[0]["url"]))
2497
+
2498
+ report_data: dict[str, Any] = {}
2499
+ if report_json_proc.returncode == 0 and report_json_proc.stdout.strip():
2500
+ report_data = json.loads(report_json_proc.stdout)
2501
+ md_text = report_md_proc.stdout
2502
+ groups = report_data.get(
2503
+ "groups", {"confirmed": [], "reconciled": [], "failed": [], "unknown": []}
2504
+ )
2505
+
2506
+ actual_confirmed_reconciled_refs = {
2507
+ row["result_ref"]
2508
+ for row in (groups["confirmed"] + groups["reconciled"])
2509
+ if row.get("result_ref")
2510
+ }
2511
+ actual_confirmed_ids = {row["action_id"] for row in groups["confirmed"]}
2512
+ actual_reconciled_ids = {row["action_id"] for row in groups["reconciled"]}
2513
+ actual_failed_ids = {row["action_id"] for row in groups["failed"]}
2514
+ actual_unknown_ids = {row["action_id"] for row in groups["unknown"]}
2515
+
2516
+ missing_refs = expected_confirmed_reconciled_refs - actual_confirmed_reconciled_refs
2517
+ hallucinated_refs = (
2518
+ actual_confirmed_reconciled_refs - expected_confirmed_reconciled_refs
2519
+ )
2520
+
2521
+ # Pure receipt-content ground-truth checks (JSON + Markdown fidelity).
2522
+ receipt_assertions = [
2523
+ report_json_proc.returncode == 0,
2524
+ report_md_proc.returncode == 0,
2525
+ report_data.get("total") == 7,
2526
+ actual_confirmed_ids == {"s6-gh-confirmed", "s6-mcp-confirmed"},
2527
+ actual_reconciled_ids == {"s6-gh-reconciled", "s6-git-reconciled"},
2528
+ actual_failed_ids == {"s6-cli-failed", "s6-mcp-failed"},
2529
+ actual_unknown_ids == {"s6-mcp-unknown"},
2530
+ len(expected_confirmed_reconciled_refs) == 4,
2531
+ len(missing_refs) == 0,
2532
+ len(hallucinated_refs) == 0,
2533
+ "## sidefx Session Receipt" in md_text,
2534
+ "### Confirmed (2)" in md_text,
2535
+ "### Reconciled (2)" in md_text,
2536
+ "### Failed (2)" in md_text,
2537
+ "### Unknown / Unresolved (1)" in md_text,
2538
+ all(ref in md_text for ref in expected_confirmed_reconciled_refs),
2539
+ "s6-mcp-unknown" in md_text,
2540
+ ]
2541
+ matched = sum(1 for ok in receipt_assertions if ok)
2542
+ accuracy_pct = (matched / len(receipt_assertions)) * 100.0
2543
+
2544
+ subchecks.append(
2545
+ {
2546
+ "check": "github_ground_truth_writes",
2547
+ "passed": (
2548
+ gh_srv.post_count == 2
2549
+ and gh_ok.status == ActionStatus.CONFIRMED
2550
+ and gh_rec.status == ActionStatus.RECONCILED
2551
+ ),
2552
+ "expected_writes": 2,
2553
+ "actual_writes": gh_srv.post_count,
2554
+ "detail": f"github_issues={sorted(gh_urls)}",
2555
+ }
2556
+ )
2557
+ subchecks.append(
2558
+ {
2559
+ "check": "git_ground_truth_pushes",
2560
+ "passed": (
2561
+ len(git_events) == 1
2562
+ and git_attempts == 1
2563
+ and remote_git_sha == push_sha
2564
+ and git_rec.status == ActionStatus.RECONCILED
2565
+ ),
2566
+ "expected_writes": 1,
2567
+ "actual_writes": max(len(git_events), git_attempts),
2568
+ "detail": (f"git_ref={expected_git_ref}, receive_pack_contacts={git_attempts}"),
2569
+ }
2570
+ )
2571
+ subchecks.append(
2572
+ {
2573
+ "check": "cli_failed_command_zero_writes",
2574
+ "passed": cli_fail.status == ActionStatus.FAILED,
2575
+ "expected_writes": 0,
2576
+ "actual_writes": 0,
2577
+ "detail": f"cli_fail_status={cli_fail.status}",
2578
+ }
2579
+ )
2580
+ subchecks.append(
2581
+ {
2582
+ "check": "mcp_ground_truth_writes",
2583
+ "passed": (
2584
+ len(mcp_entries) == 2
2585
+ and len(mcp_confirmed_entries) == 1
2586
+ and len(mcp_crashed_entries) == 1
2587
+ ),
2588
+ "expected_writes": 2,
2589
+ "actual_writes": len(mcp_entries),
2590
+ "detail": (
2591
+ f"mcp_writes={len(mcp_entries)} (1 confirmed + 1 crashed-unknown; "
2592
+ "0 for failed/read)"
2593
+ ),
2594
+ }
2595
+ )
2596
+ subchecks.append(
2597
+ {
2598
+ "check": "receipt_json_and_markdown_accuracy",
2599
+ "passed": accuracy_pct == 100.0,
2600
+ "expected_writes": 0,
2601
+ "actual_writes": 0,
2602
+ "detail": (
2603
+ f"accuracy={accuracy_pct:.1f}% ({matched}/{len(receipt_assertions)}), "
2604
+ f"missing={sorted(missing_refs)}, hallucinated={sorted(hallucinated_refs)}"
2605
+ ),
2606
+ }
2607
+ )
2608
+
2609
+ dups, exp_w, act_w = _count_duplicates(subchecks)
2610
+ all_passed = all(c["passed"] for c in subchecks) and dups == 0 and accuracy_pct == 100.0
2611
+ return ScenarioResult(
2612
+ name=name,
2613
+ title=title,
2614
+ passed=all_passed,
2615
+ duration_ms=(time.perf_counter() - started) * 1000.0,
2616
+ duplicate_remote_writes=dups,
2617
+ expected_remote_writes=exp_w,
2618
+ actual_remote_writes=act_w,
2619
+ receipt_accuracy_pct=accuracy_pct,
2620
+ details=f"JSON & Markdown receipts matched {accuracy_pct:.1f}% of remote ground truth",
2621
+ error=None if all_passed else "Receipt did not match remote ground truth 100%",
2622
+ subchecks=tuple(subchecks),
2623
+ )
2624
+
2625
+
2626
+ # ---------------------------------------------------------------------------
2627
+ # Suite runner, formatting, and CLI handler
2628
+ # ---------------------------------------------------------------------------
2629
+
2630
+ SCENARIO_REGISTRY: tuple[tuple[str, Callable[[], ScenarioResult]], ...] = (
2631
+ ("pre_commit_crash_and_timeout", _scenario_pre_commit_crash_and_timeout),
2632
+ ("post_commit_response_loss", _scenario_post_commit_response_loss),
2633
+ ("concurrent_duplicate_dispatch", _scenario_concurrent_duplicate_dispatch),
2634
+ ("payload_mutation_reused_id", _scenario_payload_mutation_reused_id),
2635
+ ("preflight_policy_enforcement", _scenario_preflight_policy_enforcement),
2636
+ ("session_receipt_ground_truth", _scenario_session_receipt_ground_truth),
2637
+ )
2638
+
2639
+
2640
+ def available_scenario_names() -> tuple[str, ...]:
2641
+ """Return ordered tuple of all registered chaos scenario names."""
2642
+ return tuple(name for name, _ in SCENARIO_REGISTRY)
2643
+
2644
+
2645
+ def run_chaos_suite(
2646
+ *,
2647
+ scenarios: Sequence[str] | None = None,
2648
+ ) -> ChaosSuiteReport:
2649
+ """Execute the automated chaos fault-injection suite and return structured metrics."""
2650
+ registry_map = dict(SCENARIO_REGISTRY)
2651
+ if scenarios is not None:
2652
+ unknown = [s for s in scenarios if s not in registry_map]
2653
+ if unknown:
2654
+ valid = ", ".join(available_scenario_names())
2655
+ raise ValueError(f"Unknown chaos scenario(s): {', '.join(unknown)}. Valid: {valid}")
2656
+ selected = [(s, registry_map[s]) for s in dict.fromkeys(scenarios)]
2657
+ else:
2658
+ selected = list(SCENARIO_REGISTRY)
2659
+
2660
+ suite_start = time.perf_counter()
2661
+ results: list[ScenarioResult] = []
2662
+ with _hermetic_chaos_env():
2663
+ for scenario_name, fn in selected:
2664
+ sc_start = time.perf_counter()
2665
+ try:
2666
+ results.append(fn())
2667
+ except Exception as exc:
2668
+ tb_lines = traceback.format_exc().strip().splitlines()
2669
+ tb_tail = " | ".join(tb_lines[-3:]) if tb_lines else f"{type(exc).__name__}: {exc}"
2670
+ results.append(
2671
+ ScenarioResult(
2672
+ name=scenario_name,
2673
+ title=scenario_name,
2674
+ passed=False,
2675
+ duration_ms=(time.perf_counter() - sc_start) * 1000.0,
2676
+ duplicate_remote_writes=0,
2677
+ expected_remote_writes=0,
2678
+ actual_remote_writes=0,
2679
+ details="Scenario raised unhandled exception (writes unmeasured)",
2680
+ error=tb_tail,
2681
+ )
2682
+ )
2683
+
2684
+ total_ms = (time.perf_counter() - suite_start) * 1000.0
2685
+ return ChaosSuiteReport(scenarios=tuple(results), total_duration_ms=total_ms)
2686
+
2687
+
2688
+ def format_chaos_report(report: ChaosSuiteReport, *, verbose: bool = False) -> str:
2689
+ """Format a human-scannable ASCII summary table for ``sidefx eval``."""
2690
+ name_width = max((len(s.name) for s in report.scenarios), default=20)
2691
+ name_width = max(name_width, len("Scenario"))
2692
+
2693
+ header = (
2694
+ f"{'Scenario':<{name_width}} {'Status':<6} {'Dupes':>5} "
2695
+ f"{'Writes':>8} {'Receipt':>8} {'Time':>8}"
2696
+ )
2697
+ sep = "-" * len(header)
2698
+ lines = [
2699
+ "sidefx Chaos Fault-Injection Evaluation",
2700
+ sep,
2701
+ header,
2702
+ sep,
2703
+ ]
2704
+ for sc in report.scenarios:
2705
+ status_str = "PASS" if sc.passed else "FAIL"
2706
+ writes_str = f"{sc.actual_remote_writes}/{sc.expected_remote_writes}"
2707
+ receipt_str = (
2708
+ f"{sc.receipt_accuracy_pct:.1f}%" if sc.receipt_accuracy_pct is not None else "-"
2709
+ )
2710
+ time_str = f"{sc.duration_ms:.0f}ms"
2711
+ lines.append(
2712
+ f"{sc.name:<{name_width}} {status_str:<6} {sc.duplicate_remote_writes:>5} "
2713
+ f"{writes_str:>8} {receipt_str:>8} {time_str:>8}"
2714
+ )
2715
+ if verbose:
2716
+ if sc.details:
2717
+ lines.append(f" detail: {sc.details}")
2718
+ if sc.error:
2719
+ lines.append(f" error: {sc.error}")
2720
+ for chk in sc.subchecks:
2721
+ chk_status = "PASS" if chk.get("passed") else "FAIL"
2722
+ lines.append(f" - [{chk_status}] {chk.get('check')}: {chk.get('detail', '')}")
2723
+ elif not sc.passed and sc.error:
2724
+ lines.append(f" error: {sc.error}")
2725
+
2726
+ lines.append(sep)
2727
+ overall = "PASS" if report.passed else "FAIL"
2728
+ accuracy_str = (
2729
+ f"{report.receipt_accuracy_pct:.1f}%" if report.receipt_accuracy_pct is not None else "n/a"
2730
+ )
2731
+ dupes_str = (
2732
+ f"{report.duplicate_remote_writes} (incomplete)"
2733
+ if report.failed_scenarios > 0 and report.duplicate_remote_writes == 0
2734
+ else str(report.duplicate_remote_writes)
2735
+ )
2736
+ lines.append(
2737
+ f"Result: {overall} | "
2738
+ f"Scenarios: {report.passed_scenarios}/{report.total_scenarios} passed | "
2739
+ f"Duplicate remote writes: {dupes_str} | "
2740
+ f"Receipt accuracy: {accuracy_str} | "
2741
+ f"Total time: {report.total_duration_ms:.0f}ms"
2742
+ )
2743
+ return "\n".join(lines)
2744
+
2745
+
2746
+ def _build_eval_parser() -> argparse.ArgumentParser:
2747
+ parser = argparse.ArgumentParser(
2748
+ prog="sidefx eval",
2749
+ description=(
2750
+ "Run the automated chaos fault-injection evaluation suite across CLI wrap, "
2751
+ "GitHub & git push reconcilers, MCP proxy, preflight guardrails, and receipts."
2752
+ ),
2753
+ )
2754
+ parser.add_argument(
2755
+ "--json",
2756
+ dest="as_json",
2757
+ action="store_true",
2758
+ help="Emit machine-readable JSON evaluation metrics.",
2759
+ )
2760
+ parser.add_argument(
2761
+ "-v",
2762
+ "--verbose",
2763
+ dest="verbose",
2764
+ action="store_true",
2765
+ help="Include per-subcheck breakdown in human-readable output.",
2766
+ )
2767
+ parser.add_argument(
2768
+ "--scenario",
2769
+ dest="scenarios",
2770
+ action="append",
2771
+ choices=available_scenario_names(),
2772
+ default=None,
2773
+ help="Run only the named scenario (repeatable; default runs all scenarios).",
2774
+ )
2775
+ return parser
2776
+
2777
+
2778
+ def handle_eval_cli(args: argparse.Namespace, config: SidefxConfig) -> int:
2779
+ """CLI handler invoked by ``sidefx.cli`` for ``sidefx eval``."""
2780
+ del config # Eval runs in fully isolated temporary workspaces.
2781
+ parser = _build_eval_parser()
2782
+ sub_args = parser.parse_args(list(getattr(args, "args", [])))
2783
+
2784
+ report = run_chaos_suite(scenarios=sub_args.scenarios)
2785
+ if sub_args.as_json:
2786
+ print(json.dumps(report.to_dict(), indent=2))
2787
+ else:
2788
+ print(format_chaos_report(report, verbose=sub_args.verbose))
2789
+ return 0 if report.passed else 1
2790
+
2791
+
2792
+ def main(argv: Sequence[str] | None = None) -> int:
2793
+ """Standalone entry point for running the chaos evaluation suite directly."""
2794
+ parser = _build_eval_parser()
2795
+ parsed = parser.parse_args(list(argv) if argv is not None else None)
2796
+ report = run_chaos_suite(scenarios=parsed.scenarios)
2797
+ if parsed.as_json:
2798
+ print(json.dumps(report.to_dict(), indent=2))
2799
+ else:
2800
+ print(format_chaos_report(report, verbose=parsed.verbose))
2801
+ return 0 if report.passed else 1
2802
+
2803
+
2804
+ if __name__ == "__main__":
2805
+ raise SystemExit(main())