From 96240b5a86ffd6c668fefd8a77497d49b594ea31 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 10:57:43 +0800 Subject: [PATCH 01/25] Capture sanitized OpenCode CI failure timelines --- .github/workflows/release-checks.yml | 1 + docs/development/validation.md | 4 + tests/opencode_ci_trace.py | 117 +++++++++++++++++++++++++++ tests/test_native_runtime.py | 26 +++++- tests/test_opencode_ci_trace.py | 39 +++++++++ 5 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 tests/opencode_ci_trace.py create mode 100644 tests/test_opencode_ci_trace.py diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index a338cc60c..f736beb25 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -107,6 +107,7 @@ jobs: timeout-minutes: 5 env: OPENDIRECTOR_REAL_CLI: '1' + OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - id: harness-install name: Install native Harness test tools diff --git a/docs/development/validation.md b/docs/development/validation.md index c62a5dea9..524330fc3 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -177,6 +177,10 @@ Python CI 为全量套件和独立 bundled OpenCode 回归分别保存 JUnit XML Python CI saves separate JUnit XML, `--durations=50` logs and opt-in `--ci-profile` JSON/Markdown for the main suite and bundled OpenCode regression. Download `python-test-evidence-` from the run; retention is 14 days. JSON records SHA, OS, Python/pytest versions, selection, per-test setup/call/teardown timings, outcomes, explicit layers and transitional defaults. It excludes stdout, failure text and local variables. +内置 OpenCode 回归的子进程失败时,同一产物的 `opencode-diagnostics/` 会保存筛选后的模型请求、工具状态和 OpenCode 内部事件,时间以首次保留事件为起点。报告不包含原始日志、模型或工具内容、凭据或文件路径。 + +If a bundled OpenCode regression worker fails, look in `opencode-diagnostics/` in the same artifact for allowlisted model, tool and OpenCode events timed relative to the first retained event. Reports exclude raw logs, model or tool content, credentials and file paths. + ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json ``` diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py new file mode 100644 index 000000000..3ad8b9790 --- /dev/null +++ b/tests/opencode_ci_trace.py @@ -0,0 +1,117 @@ +"""Allowlisted timing evidence for failed bundled OpenCode test workers.""" + +from collections import deque +from datetime import datetime +import json +from math import isfinite +import os +from pathlib import Path +import re + + +MODEL_EVENTS = { + "model.request", "model.response", "model.completed", "model.error", "model.cancelled", +} +NATIVE_EVENTS = {"step_start", "step_finish", "tool_use", "text", "error", "diagnostic"} +TOOLS = {"skill", "read", "bash", "glob", "grep"} +TOOL_STATES = {"pending", "running", "completed", "error"} +LOG_EVENTS = {"downloading ripgrep", "loop", "process", "stream", "initialized", "event connected"} +LOG_LINE = re.compile(r'^timestamp=(\S+) level=\w+ .*?\bmessage=(?:"([^"]+)"|(\S+))') +LIMIT = 256 + + +def _number(value): + return type(value) in (int, float) and abs(value) < 1e15 and isfinite(value) + + +def _json_event(line, source, turn): + try: + record = json.loads(line) + except ValueError: + return None + if not isinstance(record, dict): + return None + if source == "model": + event, at = record.get("event"), record.get("timestamp") + if not isinstance(event, str) or event not in MODEL_EVENTS or not _number(at): + return None + result = {"source": source, "turn": turn, "event": event, "at": at} + for field in ("elapsedMs", "forwardedBytes"): + if _number(record.get(field)): + result[field] = record[field] + return result + + native = record.get("native") + if not isinstance(native, dict): + return None + event, at = native.get("type"), native.get("timestamp") + if not isinstance(event, str) or event not in NATIVE_EVENTS or not _number(at): + return None + result = {"source": source, "turn": turn, "event": event, "at": at / 1000} + if event == "tool_use": + part = native.get("part") + if not isinstance(part, dict): + return result + tool = part.get("tool") + result["tool"] = tool if isinstance(tool, str) and tool in TOOLS else "other" + state = part.get("state") + if not isinstance(state, dict): + return result + status = state.get("status") + if isinstance(status, str) and status in TOOL_STATES: + result["status"] = status + duration = state.get("time") + if not isinstance(duration, dict): + return result + if _number(duration.get("start")) and _number(duration.get("end")): + result["elapsedMs"] = duration["end"] - duration["start"] + return result + + +def _log_event(line): + match = LOG_LINE.match(line) + if not match: + return None + at, quoted, token = match.groups() + event = quoted or token + if event not in LOG_EVENTS: + return None + try: + timestamp = datetime.fromisoformat(at) + except ValueError: + return None + if timestamp.tzinfo is not None: + return {"source": "opencode", "event": event, "at": timestamp.timestamp()} + return None + + +def save_failure_trace(worker: Path, destination: Path, case: str, outcome: str): + events = deque(maxlen=LIMIT) + turns = {} + for folder, directories, files in os.walk(worker): + directories.sort() + for name in sorted(files): + path = Path(folder) / name + is_trace = name.endswith((".model.jsonl", ".opencode.jsonl")) + if not is_trace and name != "opencode.log": + continue + if path.is_symlink() or not path.is_file() or path.stat().st_size > 4_000_000: + continue + if is_trace: + key, source, _ = name.rsplit(".", 2) + turn = turns.setdefault((folder, key), len(turns) + 1) + with path.open(encoding="utf-8", errors="replace") as stream: + for line in stream: + event = _json_event(line, source, turn) if is_trace else _log_event(line) + if event: + events.append(event) + ordered = sorted(events, key=lambda row: row["at"]) + start = ordered[0]["at"] if ordered else 0 + for row in ordered: + row["tMs"] = round((row.pop("at") - start) * 1000) + destination.mkdir(parents=True, exist_ok=True) + name = re.sub(r"[^a-zA-Z0-9_-]", "_", case) + (destination / f"{name}.json").write_text( + json.dumps({"case": case, "outcome": outcome, "events": ordered}, indent=2) + "\n", + encoding="utf-8", + ) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index f9120b4e0..c3d13d4e6 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -15,6 +15,7 @@ from fastapi.testclient import TestClient import httpx import pytest +from opencode_ci_trace import save_failure_trace from process_helpers import assert_process_exited, python_cli from opendirector.application.creation_assets import CreationAssets @@ -364,9 +365,28 @@ def real_opencode_worker(tmp_path, monkeypatch, request): assert native.executable('default') is not None, 'Bundled OpenCode is not installed' timeout = 105 if 'windows_unicode_pipeline' in request.node.name else 60 if os.environ.get('OPENDIRECTOR_REAL_CLI_WORKER') != '1': - result = subprocess.run([sys.executable, '-m', 'pytest', request.node.nodeid, '-s', '-q'], - env={**os.environ, 'OPENDIRECTOR_REAL_CLI_WORKER': '1'}, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", timeout=timeout + 30) + trace_dir = os.environ.get('OPENDIRECTOR_CI_TRACE_DIR') + worker = tmp_path / 'worker' + command = [sys.executable, '-m', 'pytest', request.node.nodeid, '-s', '-q'] + if trace_dir: + command.extend(['--basetemp', str(worker)]) + + def collect(outcome): + if trace_dir: + try: + save_failure_trace(worker, Path(trace_dir), request.node.name, outcome) + except OSError: + print('Could not save OpenCode CI trace', file=sys.stderr, flush=True) + + try: + result = subprocess.run(command, + env={**os.environ, 'OPENDIRECTOR_REAL_CLI_WORKER': '1'}, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", timeout=timeout + 30) + except subprocess.TimeoutExpired: + collect('parent-timeout') + raise + if result.returncode: + collect('watchdog' if 'Real OpenCode integration timed out;' in result.stdout else 'worker-failed') assert result.returncode == 0, result.stdout return False diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py new file mode 100644 index 000000000..260a91498 --- /dev/null +++ b/tests/test_opencode_ci_trace.py @@ -0,0 +1,39 @@ +import json + +import pytest + +from opencode_ci_trace import save_failure_trace + + +@pytest.mark.cpu +@pytest.mark.merge +def test_failed_opencode_export_keeps_timeline_and_drops_raw_content(tmp_path): + worker = tmp_path / "worker" + worker.mkdir() + canary = "private-test-value" + (worker / "run.model.jsonl").write_text( + json.dumps({"event": "model.completed", "timestamp": 10, "elapsedMs": 3, + "payload": canary, "requestId": canary}) + "\n{", encoding="utf-8", + ) + (worker / "run.opencode.jsonl").write_text( + json.dumps({"native": {"type": "tool_use", "timestamp": 10010, "part": { + "tool": "bash", "state": {"status": "completed", "time": {"start": 10004, "end": 10009}, + "input": canary, "output": canary}, + }}}), encoding="utf-8", + ) + (worker / "opencode.log").write_text( + f'timestamp=1970-01-01T00:00:10.015Z level=INFO run=sample message=loop private={canary}\n' + f'timestamp=1970-01-01T00:00:10.016Z level=INFO run=sample message="{canary}"\n', + encoding="utf-8", + ) + destination = tmp_path / "reports" + save_failure_trace(worker, destination, "test_example[image-model]", "watchdog") + report, = destination.glob("*.json") + contents = report.read_text(encoding="utf-8") + assert canary not in contents + assert json.loads(contents)["events"] == [ + {"source": "model", "turn": 1, "event": "model.completed", "elapsedMs": 3, "tMs": 0}, + {"source": "opencode", "turn": 1, "event": "tool_use", "tool": "bash", + "status": "completed", "elapsedMs": 5, "tMs": 10}, + {"source": "opencode", "event": "loop", "tMs": 15}, + ] From 3329b9a51b73b3eace13283610899a7b1a0692c6 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 11:31:58 +0800 Subject: [PATCH 02/25] Trace OpenCode shell and gateway boundaries --- docs/development/validation.md | 4 +- tests/opencode_ci_probe.py | 65 ++++++++++++++++++++++++++++++++ tests/opencode_ci_trace.py | 67 +++++++++++++++++++++++++++++---- tests/test_native_runtime.py | 7 ++++ tests/test_opencode_ci_trace.py | 51 ++++++++++++++++++++++++- 5 files changed, 183 insertions(+), 11 deletions(-) create mode 100644 tests/opencode_ci_probe.py diff --git a/docs/development/validation.md b/docs/development/validation.md index 524330fc3..722ea1bc0 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -177,9 +177,9 @@ Python CI 为全量套件和独立 bundled OpenCode 回归分别保存 JUnit XML Python CI saves separate JUnit XML, `--durations=50` logs and opt-in `--ci-profile` JSON/Markdown for the main suite and bundled OpenCode regression. Download `python-test-evidence-` from the run; retention is 14 days. JSON records SHA, OS, Python/pytest versions, selection, per-test setup/call/teardown timings, outcomes, explicit layers and transitional defaults. It excludes stdout, failure text and local variables. -内置 OpenCode 回归的子进程失败时,同一产物的 `opencode-diagnostics/` 会保存筛选后的模型请求、工具状态和 OpenCode 内部事件,时间以首次保留事件为起点。报告不包含原始日志、模型或工具内容、凭据或文件路径。 +内置 OpenCode 回归的子进程失败时,同一产物的 `opencode-diagnostics/` 会保存筛选后的模型、工具和 OpenCode 内部事件,以及 Linux 上 Bash、Git 与业务网关调用的起止时间。时间以首次保留事件为起点,`droppedEvents` 标记因数量上限省略的事件数。报告不包含原始日志、模型或工具内容、凭据或文件路径。 -If a bundled OpenCode regression worker fails, look in `opencode-diagnostics/` in the same artifact for allowlisted model, tool and OpenCode events timed relative to the first retained event. Reports exclude raw logs, model or tool content, credentials and file paths. +If a bundled OpenCode regression worker fails, look in `opencode-diagnostics/` in the same artifact for allowlisted model, tool and OpenCode events, plus Bash, Git and business gateway boundaries on Linux. Time is relative to the first retained event. `droppedEvents` counts events omitted by the cap. Reports exclude raw logs, model or tool content, credentials and file paths. ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py new file mode 100644 index 000000000..ac4e994ba --- /dev/null +++ b/tests/opencode_ci_probe.py @@ -0,0 +1,65 @@ +"""Optional Linux process boundaries for the bundled OpenCode CI fixture.""" + +import os +from pathlib import Path +import shutil +import time + + +def process_environment(root: Path, env: dict[str, str]): + probe = root / "ci-probe" + probe.mkdir(exist_ok=True) + git = shutil.which("git", path=env.get("PATH", os.defpath)) + if git is None: + return env + startup = probe / "bash-env" + startup.write_text("""unset BASH_ENV +printf '%s bash.start %s\n' "$EPOCHREALTIME" "$BASHPID" >> "$OD_CI_BOUNDARIES" +trap 'rc=$?; printf "%s bash.exit %s %s\\n" "$EPOCHREALTIME" "$BASHPID" "$rc" >> "$OD_CI_BOUNDARIES"' EXIT +""", encoding="utf-8") + git_probe = probe / "git" + git_probe.write_text("""#!/bin/sh +operation=other +for arg do + case "$arg" in + add|write-tree|diff|diff-files|diff-index|check-ignore|rev-parse|ls-files|status|config|hash-object|cat-file) + operation=$arg; break ;; + esac +done +printf '%s git.start %s %s\n' "$(date +%s.%N)" "$$" "$operation" >> "$OD_CI_BOUNDARIES" +"$OD_CI_REAL_GIT" "$@" +rc=$? +printf '%s git.exit %s %s %s\n' "$(date +%s.%N)" "$$" "$operation" "$rc" >> "$OD_CI_BOUNDARIES" +exit "$rc" +""", encoding="utf-8") + git_probe.chmod(0o700) + return { + **env, "BASH_ENV": str(startup), "OD_CI_REAL_GIT": git, + "OD_CI_BOUNDARIES": str(root / "process-boundaries.log"), + "PATH": str(probe) + os.pathsep + env.get("PATH", os.defpath), + } + + +def gateway_probe(root, original): + async def call(gateway, call_id, name, arguments): + if not call_id.startswith("cli:"): + return await original(gateway, call_id, name, arguments) + receipt = "error" + key = time.monotonic_ns() + record_gateway_event(root, "gateway.start", key) + try: + result = await original(gateway, call_id, name, arguments) + receipt = "error" if result.error else "success" + return result + finally: + record_gateway_event(root, "gateway.return", key, receipt) + + return call + + +def record_gateway_event(root, event, key, status=""): + try: + with (root / "process-boundaries.log").open("a", encoding="utf-8") as output: + output.write(f"{time.time()} {event} {key} {status}\n") + except OSError: + pass diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index 3ad8b9790..43c865c30 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -1,7 +1,7 @@ """Allowlisted timing evidence for failed bundled OpenCode test workers.""" -from collections import deque from datetime import datetime +from heapq import heappush, heapreplace import json from math import isfinite import os @@ -15,8 +15,13 @@ NATIVE_EVENTS = {"step_start", "step_finish", "tool_use", "text", "error", "diagnostic"} TOOLS = {"skill", "read", "bash", "glob", "grep"} TOOL_STATES = {"pending", "running", "completed", "error"} -LOG_EVENTS = {"downloading ripgrep", "loop", "process", "stream", "initialized", "event connected"} +LOG_EVENTS = {"downloading ripgrep", "loop", "process", "stream", "initialized", "event connected", "tracking"} LOG_LINE = re.compile(r'^timestamp=(\S+) level=\w+ .*?\bmessage=(?:"([^"]+)"|(\S+))') +BOUNDARY_EVENTS = {"bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return"} +GIT_OPERATIONS = { + "add", "write-tree", "diff", "diff-files", "diff-index", "check-ignore", + "rev-parse", "ls-files", "status", "config", "hash-object", "cat-file", "other", +} LIMIT = 256 @@ -85,15 +90,50 @@ def _log_event(line): return None +def _boundary_event(line, identities): + fields = line.split() + if len(fields) not in (3, 4, 5): + return None + timestamp, event, key, *details = fields + if event not in BOUNDARY_EVENTS or not re.fullmatch(r"[0-9]{1,22}", key): + return None + try: + at = float(timestamp) + except ValueError: + return None + if not _number(at): + return None + source, phase = event.split(".") + result = {"source": source, "event": event, "at": at} + if source == "git": + if not details or details[0] not in GIT_OPERATIONS: + return None + result["operation"] = details.pop(0) + if phase == "exit": + if len(details) != 1 or not re.fullmatch(r"[0-9]{1,3}", details[0]): + return None + result["exitCode"] = int(details.pop()) + if event == "gateway.return": + if len(details) != 1 or details[0] not in {"success", "error"}: + return None + result["status"] = details.pop() + if details: + return None + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result + + def save_failure_trace(worker: Path, destination: Path, case: str, outcome: str): - events = deque(maxlen=LIMIT) + events = [] turns = {} + identities = {} + total = 0 for folder, directories, files in os.walk(worker): directories.sort() for name in sorted(files): path = Path(folder) / name is_trace = name.endswith((".model.jsonl", ".opencode.jsonl")) - if not is_trace and name != "opencode.log": + if not is_trace and name not in {"opencode.log", "process-boundaries.log"}: continue if path.is_symlink() or not path.is_file() or path.stat().st_size > 4_000_000: continue @@ -102,16 +142,27 @@ def save_failure_trace(worker: Path, destination: Path, case: str, outcome: str) turn = turns.setdefault((folder, key), len(turns) + 1) with path.open(encoding="utf-8", errors="replace") as stream: for line in stream: - event = _json_event(line, source, turn) if is_trace else _log_event(line) + if is_trace: + event = _json_event(line, source, turn) + elif name == "process-boundaries.log": + event = _boundary_event(line, identities) + else: + event = _log_event(line) if event: - events.append(event) - ordered = sorted(events, key=lambda row: row["at"]) + total += 1 + entry = (event["at"], total, event) + if len(events) < LIMIT: + heappush(events, entry) + elif entry > events[0]: + heapreplace(events, entry) + ordered = [row for _, _, row in sorted(events)] start = ordered[0]["at"] if ordered else 0 for row in ordered: row["tMs"] = round((row.pop("at") - start) * 1000) destination.mkdir(parents=True, exist_ok=True) name = re.sub(r"[^a-zA-Z0-9_-]", "_", case) (destination / f"{name}.json").write_text( - json.dumps({"case": case, "outcome": outcome, "events": ordered}, indent=2) + "\n", + json.dumps({"case": case, "outcome": outcome, "droppedEvents": total - len(ordered), + "events": ordered}, indent=2) + "\n", encoding="utf-8", ) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index c3d13d4e6..06bebcc35 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -15,11 +15,13 @@ from fastapi.testclient import TestClient import httpx import pytest +from opencode_ci_probe import gateway_probe, process_environment from opencode_ci_trace import save_failure_trace from process_helpers import assert_process_exited, python_cli from opendirector.application.creation_assets import CreationAssets from opendirector.agent import native +from opendirector.agent.gateway import ToolGateway from opendirector.agent.skills import skills from opendirector.agent.runtime import AgentRuntimes from opendirector.agent.context import RunContext @@ -393,9 +395,14 @@ def collect(outcome): for name in ('XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME'): monkeypatch.setenv(name, str(tmp_path / name.lower())) from opendirector.agent.process import _signal_tree + probe_enabled = sys.platform == 'linux' and os.environ.get('OPENDIRECTOR_CI_TRACE_DIR') + if probe_enabled: + monkeypatch.setattr(ToolGateway, 'call', gateway_probe(tmp_path, ToolGateway.call)) processes = [] spawn = asyncio.create_subprocess_exec async def tracked_spawn(*args, **kwargs): + if probe_enabled and args[0] == native.executable('default') and args[1] == 'run': + kwargs['env'] = process_environment(tmp_path, kwargs['env']) process = await spawn(*args, **kwargs) processes.append((process, kwargs.get('start_new_session', False))) if os.environ.get('OPENDIRECTOR_TEST_CLI_STALL') and 'run' in args: diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index 260a91498..fbbc02c54 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -1,8 +1,13 @@ import json +import os +import shutil +import subprocess +import sys import pytest -from opencode_ci_trace import save_failure_trace +from opencode_ci_probe import process_environment, record_gateway_event +from opencode_ci_trace import LIMIT, save_failure_trace @pytest.mark.cpu @@ -37,3 +42,47 @@ def test_failed_opencode_export_keeps_timeline_and_drops_raw_content(tmp_path): "status": "completed", "elapsedMs": 5, "tMs": 10}, {"source": "opencode", "event": "loop", "tMs": 15}, ] + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux" or not shutil.which("bash") or not shutil.which("git"), + reason="Linux Bash and Git probe") +def test_process_probes_preserve_command_exit_and_do_not_record_arguments(tmp_path): + canary = "private-test-value" + repo = tmp_path / "repo" + subprocess.run(["git", "init", "-q", str(repo)], check=True) + env = process_environment(tmp_path, dict(os.environ)) + assert subprocess.run(["bash", "-c", "exit 7", canary], env=env).returncode == 7 + assert subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], env=env, cwd=repo, + capture_output=True, check=True).stdout.strip() == b"true" + record_gateway_event(tmp_path, "gateway.start", 98765) + record_gateway_event(tmp_path, "gateway.return", 98765, "success") + destination = tmp_path / "reports" + save_failure_trace(tmp_path, destination, "probe", "watchdog") + raw = (destination / "probe.json").read_text() + assert canary not in raw and "98765" not in raw + events = json.loads(raw)["events"] + assert [event["event"] for event in events] == [ + "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", + ] + assert events[1]["exitCode"] == 7 + assert events[2]["operation"] == events[3]["operation"] == "rev-parse" + assert events[4]["span"] == events[5]["span"] and events[5]["status"] == "success" + + +@pytest.mark.cpu +@pytest.mark.merge +def test_trace_cap_keeps_latest_events_across_files(tmp_path): + (tmp_path / "a.model.jsonl").write_text( + json.dumps({"event": "model.completed", "timestamp": LIMIT + 1}) + "\n", encoding="utf-8", + ) + (tmp_path / "z.model.jsonl").write_text("".join( + json.dumps({"event": "model.request", "timestamp": timestamp}) + "\n" + for timestamp in range(LIMIT) + ), encoding="utf-8") + save_failure_trace(tmp_path, tmp_path / "reports", "capped", "watchdog") + report = json.loads((tmp_path / "reports/capped.json").read_text()) + assert report["droppedEvents"] == 1 + assert report["events"][-1]["event"] == "model.completed" + assert report["events"][-1]["tMs"] == LIMIT * 1000 From 82f3d6219f901143463e2473f1e07122936c3569 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 12:08:16 +0800 Subject: [PATCH 03/25] Compare standalone OpenCode on the diagnostic runner --- .github/workflows/release-checks.yml | 8 ++ scripts/ci/opencode_minimal_probe.py | 201 +++++++++++++++++++++++++++ 2 files changed, 209 insertions(+) create mode 100644 scripts/ci/opencode_minimal_probe.py diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index f736beb25..374b5a7f5 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -102,6 +102,14 @@ jobs: - name: Check generated contracts if: always() && steps.install.outcome == 'success' run: python scripts/generate_contracts.py --check + - name: Standalone OpenCode control on diagnostic PR + if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' + timeout-minutes: 6 + continue-on-error: true + run: >- + python scripts/ci/opencode_minimal_probe.py --binary node_modules/opencode-ai/bin/opencode + --repeats 2 --timeout 60 --fixture-shape --skill-first + --report test-results/opencode-diagnostics/standalone-control.json - name: Bundled OpenCode model gateway regression if: always() && steps.install.outcome == 'success' timeout-minutes: 5 diff --git a/scripts/ci/opencode_minimal_probe.py b/scripts/ci/opencode_minimal_probe.py new file mode 100644 index 000000000..89e7888a2 --- /dev/null +++ b/scripts/ci/opencode_minimal_probe.py @@ -0,0 +1,201 @@ +"""Run bundled OpenCode against a local mock without OpenDirector.""" + +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import tempfile +import threading +import time + + +EVENT_TYPES = {"step_start", "step_finish", "text", "tool_use", "error"} +TOOL_NAMES = {"bash", "skill"} +TOOL_STATUSES = {"completed", "error", "running", "pending"} + + +class MockModel(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_POST(self): + if self.path != "/v1/chat/completions": + self.send_error(404) + return + payload = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + tools = {t["function"]["name"] for t in payload.get("tools", ())} + messages = payload["messages"] + results = sum(item["role"] == "tool" for item in messages) + self.server.events.append({"event": "request", "results": results, "bashEnabled": "bash" in tools}) + if results < self.server.tool_steps and "bash" in tools: + command = f"printf 'probe-{results + 1}\\n'" + if self.server.fixture_shape: + command = """sleep 1.7; printf '%s\\n' '{"status":"applied","changed":[]}'""" + name = "bash" + arguments = {"command": command, "description": "Run a local no-op diagnostic"} + if self.server.skill_first and results == 0: + name, arguments = "skill", {"name": "ci-probe"} + delta = {"role": "assistant", "tool_calls": [{ + "index": 0, "id": f"call-{results + 1}", "type": "function", + "function": {"name": name, "arguments": json.dumps(arguments)}, + }]} + reason = "tool_calls" + else: + delta, reason = {"role": "assistant", "content": "Mock model finished."}, "stop" + chunk = { + "id": f"completion-{results + 1}", "object": "chat.completion.chunk", + "created": 1, "model": "probe-model", + } + deltas = [(delta, None), ({}, reason)] + if self.server.fixture_shape: + deltas.insert(0, ({"reasoning_content": "Check the request."}, None)) + data = "".join( + "data: " + json.dumps({**chunk, "choices": [{"index": 0, "delta": part, "finish_reason": finish}]}) + "\n\n" + for part, finish in deltas + ) + "data: [DONE]\n\n" + body = data.encode() + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Transfer-Encoding", "chunked") + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(f"{len(body):x}\r\n".encode() + body + b"\r\n0\r\n\r\n") + self.wfile.flush() + self.close_connection = True + self.server.events.append({"event": "response-complete", "results": results, "finish": reason}) + + +def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fixture_shape, skill_first): + root = base / label + work = root / "work" + work.mkdir(parents=True) + if git_worktree: + subprocess.run(["git", "init", "-q", str(work)], check=True) + skill_root = work / ".agents" / "skills" + if skill_first: + skill = skill_root / "ci-probe" + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: ci-probe\ndescription: Local fixture only\n---\nA local fixture skill.\n") + with ThreadingHTTPServer(("127.0.0.1", 0), MockModel) as server: + server.events, server.tool_steps = [], tool_steps + server.fixture_shape = fixture_shape + server.skill_first = skill_first + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + config = { + "autoupdate": False, "default_agent": "probe", + "agent": {"probe": {"mode": "primary", "prompt": "Follow the simulated task."}, + "title": {"disable": True}}, + "permission": {"*": "deny", "bash": "allow"}, + "provider": {"mock": { + "npm": "@ai-sdk/openai-compatible", "name": "Local mock", + "options": {"baseURL": f"http://127.0.0.1:{server.server_port}/v1", "apiKey": "local-fixture-only"}, + "models": {"probe-model": {"name": "probe-model"}}, + }}, + } + if skill_first: + config["skills"] = {"paths": [str(skill_root)]} + config["permission"]["skill"] = {"*": "deny", "ci-probe": "allow"} + env = { + **os.environ, + **{f"XDG_{name}_HOME": str(root / name.lower()) for name in ("CONFIG", "DATA", "STATE", "CACHE")}, + "OPENCODE_CONFIG_CONTENT": json.dumps(config), + "OPENCODE_DISABLE_MODELS_FETCH": "1", "OPENCODE_DISABLE_EXTERNAL_SKILLS": "1", + "OPENCODE_DISABLE_CLAUDE_CODE_SKILLS": "1", "PWD": str(work), + } + env.pop("BASH_ENV", None) + if trace_bash: + hook = root / "bash-env" + hook.write_text('unset BASH_ENV\nprintf "start\u005c\u005cn" >> "$PROBE_SHELL_EVENTS"\ntrap \'printf "exit:%s\\n" "$?" >> "$PROBE_SHELL_EVENTS"\' EXIT\n') + env.update(BASH_ENV=str(hook), PROBE_SHELL_EVENTS=str(root / "shell-events")) + command = [binary, "run", "--dir", str(work), "--pure", "--format", "json", + "--agent", "probe", "--model", "mock/probe-model"] + started = time.monotonic() + try: + with subprocess.Popen(command, env=env, cwd=work, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, start_new_session=True) as process: + try: + stdout, _ = process.communicate(input="Run the diagnostic.\n", timeout=timeout) + timed_out = False + except subprocess.TimeoutExpired: + timed_out = True + os.killpg(process.pid, signal.SIGKILL) + stdout, _ = process.communicate(timeout=5) + finally: + server.shutdown() + thread.join() + events = [] + for line in stdout.splitlines(): + try: + raw = json.loads(line) + except ValueError: + continue + kind = raw.get("type") + if kind not in EVENT_TYPES: + continue + part = raw.get("part", {}) + tool, status = part.get("tool"), part.get("state", {}).get("status") + events.append((kind, tool if tool in TOOL_NAMES else None, status if status in TOOL_STATUSES else None)) + shell = root / "shell-events" + return { + "case": label, "timeout": timed_out, "exitCode": process.returncode, + "elapsedSeconds": round(time.monotonic() - started, 2), + "events": events, "model": server.events, + "shell": shell.read_text().splitlines() if shell.exists() else [], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", required=True) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--timeout", type=int, default=30) + parser.add_argument("--fixture-shape", action="store_true") + parser.add_argument("--skill-first", action="store_true") + parser.add_argument("--report", type=Path) + args = parser.parse_args() + binary = str(Path(args.binary).resolve()) + assert Path(binary).is_file() + reports = [] + + def run(label, tools, git_worktree, trace_bash, skill_first): + report = trial(binary, base, label, len(tools), args.timeout, git_worktree, + trace_bash, args.fixture_shape, skill_first) + completed = [name for kind, name, status in report["events"] + if kind == "tool_use" and status == "completed"] + requests = [row["results"] for row in report["model"] if row["event"] == "request"] + report["passed"] = ( + not report["timeout"] and report["exitCode"] == 0 and completed == tools + and requests == list(range(len(tools) + 1)) + and any(kind == "text" for kind, _, _ in report["events"]) + and report["shell"] == ["start", "exit:0"] * tools.count("bash") + ) + reports.append(report) + print(json.dumps(report), flush=True) + + with tempfile.TemporaryDirectory(prefix="od-minimal-opencode-") as temporary: + base = Path(temporary) + run("text-control", [], False, False, False) + tools = ["skill", "bash"] if args.skill_first else ["bash", "bash"] + for index in range(args.repeats): + for git_worktree in (False, True): + run(f"bash-{index + 1}-git-{int(git_worktree)}", tools, git_worktree, True, args.skill_first) + summary = {"total": len(reports), "passed": sum(report["passed"] for report in reports)} + print(json.dumps(summary)) + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps({ + **summary, "ripgrepOnPath": shutil.which("rg") is not None, "cases": reports, + }, indent=2) + "\n", encoding="utf-8") + return 0 if all(report["passed"] for report in reports) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From c1a70207e1bfd6509a264998f1ca1ad2c9022fbb Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 13:04:42 +0800 Subject: [PATCH 04/25] Resolve the hosted control binary through the runtime --- .github/workflows/release-checks.yml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 374b5a7f5..06e0f3b44 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -106,10 +106,15 @@ jobs: if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' timeout-minutes: 6 continue-on-error: true - run: >- - python scripts/ci/opencode_minimal_probe.py --binary node_modules/opencode-ai/bin/opencode - --repeats 2 --timeout 60 --fixture-shape --skill-first - --report test-results/opencode-diagnostics/standalone-control.json + run: | + binary="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" + if [ -z "$binary" ]; then + echo "::error::Bundled OpenCode is missing" + exit 1 + fi + python scripts/ci/opencode_minimal_probe.py --binary "$binary" \ + --repeats 2 --timeout 60 --fixture-shape --skill-first \ + --report test-results/opencode-diagnostics/standalone-control.json - name: Bundled OpenCode model gateway regression if: always() && steps.install.outcome == 'success' timeout-minutes: 5 From 8a55eb4c8b82f2880fa02bb68da1b89cd1760ce1 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 14:24:17 +0800 Subject: [PATCH 05/25] Timestamp standalone OpenCode diagnostic events --- scripts/ci/opencode_minimal_probe.py | 48 +++++++++++++++++++++------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/scripts/ci/opencode_minimal_probe.py b/scripts/ci/opencode_minimal_probe.py index 89e7888a2..dd620342a 100644 --- a/scripts/ci/opencode_minimal_probe.py +++ b/scripts/ci/opencode_minimal_probe.py @@ -28,11 +28,15 @@ def do_POST(self): if self.path != "/v1/chat/completions": self.send_error(404) return + received_ms = time.time_ns() // 1_000_000 payload = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) tools = {t["function"]["name"] for t in payload.get("tools", ())} messages = payload["messages"] results = sum(item["role"] == "tool" for item in messages) - self.server.events.append({"event": "request", "results": results, "bashEnabled": "bash" in tools}) + self.server.events.append({ + "event": "request", "tMs": received_ms - self.server.wall_started_ms, + "results": results, "bashEnabled": "bash" in tools, + }) if results < self.server.tool_steps and "bash" in tools: command = f"printf 'probe-{results + 1}\\n'" if self.server.fixture_shape: @@ -68,7 +72,10 @@ def do_POST(self): self.wfile.write(f"{len(body):x}\r\n".encode() + body + b"\r\n0\r\n\r\n") self.wfile.flush() self.close_connection = True - self.server.events.append({"event": "response-complete", "results": results, "finish": reason}) + self.server.events.append({ + "event": "response-complete", "tMs": time.time_ns() // 1_000_000 - self.server.wall_started_ms, + "results": results, "finish": reason, + }) def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fixture_shape, skill_first): @@ -112,11 +119,16 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi env.pop("BASH_ENV", None) if trace_bash: hook = root / "bash-env" - hook.write_text('unset BASH_ENV\nprintf "start\u005c\u005cn" >> "$PROBE_SHELL_EVENTS"\ntrap \'printf "exit:%s\\n" "$?" >> "$PROBE_SHELL_EVENTS"\' EXIT\n') + hook.write_text( + 'unset BASH_ENV\n' + 'printf "%s start\\n" "$EPOCHREALTIME" >> "$PROBE_SHELL_EVENTS"\n' + """trap 'printf "%s exit:%s\\n" "$EPOCHREALTIME" "$?" >> "$PROBE_SHELL_EVENTS"' EXIT\n""" + ) env.update(BASH_ENV=str(hook), PROBE_SHELL_EVENTS=str(root / "shell-events")) command = [binary, "run", "--dir", str(work), "--pure", "--format", "json", "--agent", "probe", "--model", "mock/probe-model"] - started = time.monotonic() + monotonic_started = time.monotonic() + server.wall_started_ms = time.time_ns() // 1_000_000 try: with subprocess.Popen(command, env=env, cwd=work, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -128,6 +140,7 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi timed_out = True os.killpg(process.pid, signal.SIGKILL) stdout, _ = process.communicate(timeout=5) + process_done_ms = round((time.monotonic() - monotonic_started) * 1000) finally: server.shutdown() thread.join() @@ -142,13 +155,26 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi continue part = raw.get("part", {}) tool, status = part.get("tool"), part.get("state", {}).get("status") - events.append((kind, tool if tool in TOOL_NAMES else None, status if status in TOOL_STATUSES else None)) + timestamp = raw.get("timestamp") + events.append({ + "event": kind, "tMs": timestamp - server.wall_started_ms if type(timestamp) is int else None, + "tool": tool if tool in TOOL_NAMES else None, "status": status if status in TOOL_STATUSES else None, + }) shell = root / "shell-events" + shell_events = [] + for line in shell.read_text().splitlines() if shell.exists() else []: + timestamp, _, event = line.partition(" ") + if event == "start" or (event.startswith("exit:") and event[5:].isdigit()): + try: + t_ms = int(float(timestamp) * 1000) - server.wall_started_ms + except (ValueError, OverflowError): + t_ms = None + shell_events.append({"event": event, "tMs": t_ms}) return { "case": label, "timeout": timed_out, "exitCode": process.returncode, - "elapsedSeconds": round(time.monotonic() - started, 2), + "elapsedSeconds": round(process_done_ms / 1000, 2), "processDoneMs": process_done_ms, "events": events, "model": server.events, - "shell": shell.read_text().splitlines() if shell.exists() else [], + "shell": shell_events, } @@ -168,14 +194,14 @@ def main(): def run(label, tools, git_worktree, trace_bash, skill_first): report = trial(binary, base, label, len(tools), args.timeout, git_worktree, trace_bash, args.fixture_shape, skill_first) - completed = [name for kind, name, status in report["events"] - if kind == "tool_use" and status == "completed"] + completed = [row["tool"] for row in report["events"] + if row["event"] == "tool_use" and row["status"] == "completed"] requests = [row["results"] for row in report["model"] if row["event"] == "request"] report["passed"] = ( not report["timeout"] and report["exitCode"] == 0 and completed == tools and requests == list(range(len(tools) + 1)) - and any(kind == "text" for kind, _, _ in report["events"]) - and report["shell"] == ["start", "exit:0"] * tools.count("bash") + and any(row["event"] == "text" for row in report["events"]) + and [row["event"] for row in report["shell"]] == ["start", "exit:0"] * tools.count("bash") ) reports.append(report) print(json.dumps(report), flush=True) From 26079c5374cd2679ded2f689a8d4e055c6fc50d0 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 14:58:02 +0800 Subject: [PATCH 06/25] Provide ripgrep for the hosted OpenCode diagnostic --- .github/workflows/release-checks.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 06e0f3b44..4ee1c10e9 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -102,6 +102,12 @@ jobs: - name: Check generated contracts if: always() && steps.install.outcome == 'success' run: python scripts/generate_contracts.py --check + - name: Install ripgrep on diagnostic PR + if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' + timeout-minutes: 3 + run: | + sudo apt-get install --yes ripgrep + rg --version - name: Standalone OpenCode control on diagnostic PR if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' timeout-minutes: 6 From 0e4c6c157dc0f532471d3b78f739ad2fb3baf1c0 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 15:28:55 +0800 Subject: [PATCH 07/25] Capture watchdog process and pipe state in OpenCode CI --- tests/opencode_ci_probe.py | 82 +++++++++++++++++++++++++++++++++ tests/opencode_ci_trace.py | 21 ++++++++- tests/test_native_runtime.py | 13 +++++- tests/test_opencode_ci_trace.py | 38 ++++++++++++++- 4 files changed, 149 insertions(+), 5 deletions(-) diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index ac4e994ba..3f08c9c29 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -15,6 +15,17 @@ def process_environment(root: Path, env: dict[str, str]): startup = probe / "bash-env" startup.write_text("""unset BASH_ENV printf '%s bash.start %s\n' "$EPOCHREALTIME" "$BASHPID" >> "$OD_CI_BOUNDARIES" +for od_fd in 1 2; do + if [[ -p /proc/$BASHPID/fd/$od_fd ]]; then + while read -r od_key od_value; do + if [[ $od_key == ino: ]]; then + printf '%s %s %s\\n' "$BASHPID" "$od_fd" "$od_value" >> "$OD_CI_BASH_PIPES" + break + fi + done < "/proc/$BASHPID/fdinfo/$od_fd" + fi +done +unset od_fd od_key od_value trap 'rc=$?; printf "%s bash.exit %s %s\\n" "$EPOCHREALTIME" "$BASHPID" "$rc" >> "$OD_CI_BOUNDARIES"' EXIT """, encoding="utf-8") git_probe = probe / "git" @@ -36,10 +47,81 @@ def process_environment(root: Path, env: dict[str, str]): return { **env, "BASH_ENV": str(startup), "OD_CI_REAL_GIT": git, "OD_CI_BOUNDARIES": str(root / "process-boundaries.log"), + "OD_CI_BASH_PIPES": str(root / "bash-pipes.log"), "PATH": str(probe) + os.pathsep + env.get("PATH", os.defpath), } +def _process_state(path): + try: + return (path / "stat").read_text().rsplit(") ", 1)[1].split()[0] + except FileNotFoundError: + return "gone" + except (OSError, IndexError): + return "unknown" + + +def _pipe_holders(proc, pipes): + holders = {pipe: [0, 0] for pipe in pipes} + uid = os.getuid() + for path in proc.iterdir(): + if not path.name.isdecimal(): + continue + try: + if path.stat().st_uid != uid: + continue + for descriptor in (path / "fd").iterdir(): + try: + pipe = os.readlink(descriptor) + if pipe not in holders: + continue + flags = next(line.split()[1] for line in + (path / "fdinfo" / descriptor.name).read_text().splitlines() + if line.startswith("flags:")) + access = int(flags, 8) & os.O_ACCMODE + except (OSError, StopIteration, ValueError, IndexError): + continue + if access in (os.O_RDONLY, os.O_RDWR): + holders[pipe][0] += 1 + if access in (os.O_WRONLY, os.O_RDWR): + holders[pipe][1] += 1 + except OSError: + continue + return holders + + +def watchdog_probe(root, cli_pids): + proc = Path("/proc") + boundaries = root / "process-boundaries.log" + bash_pids = {} + if boundaries.is_file(): + for line in boundaries.read_text().splitlines(): + fields = line.split() + if len(fields) == 3 and fields[1] == "bash.start" and fields[2].isdecimal(): + bash_pids[fields[2]] = {} + bash_pids = dict(list(bash_pids.items())[-4:]) + pipe_log = root / "bash-pipes.log" + if pipe_log.is_file(): + for line in pipe_log.read_text().splitlines(): + fields = line.split() + if len(fields) != 3: + continue + pid, descriptor, inode = fields + if pid in bash_pids and descriptor in {"1", "2"} and inode.isdecimal(): + bash_pids[pid][descriptor] = f"pipe:[{inode}]" + pipes = {pipe for descriptors in bash_pids.values() for pipe in descriptors.values()} + holders = _pipe_holders(proc, pipes) if pipes else {} + with boundaries.open("a", encoding="utf-8") as output: + for pid in cli_pids: + output.write(f"{time.time()} opencode.watchdog {pid} {_process_state(proc / str(pid))}\n") + for pid, descriptors in bash_pids.items(): + counts = [count for descriptor in ("1", "2") for count in + holders.get(descriptors.get(descriptor), ("-", "-"))] + readers_out, writers_out, readers_err, writers_err = counts + output.write(f"{time.time()} bash.watchdog {pid} {_process_state(proc / pid)} " + f"{readers_out} {writers_out} {readers_err} {writers_err}\n") + + def gateway_probe(root, original): async def call(gateway, call_id, name, arguments): if not call_id.startswith("cli:"): diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index 43c865c30..dc8814ef8 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -17,7 +17,12 @@ TOOL_STATES = {"pending", "running", "completed", "error"} LOG_EVENTS = {"downloading ripgrep", "loop", "process", "stream", "initialized", "event connected", "tracking"} LOG_LINE = re.compile(r'^timestamp=(\S+) level=\w+ .*?\bmessage=(?:"([^"]+)"|(\S+))') -BOUNDARY_EVENTS = {"bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return"} +BOUNDARY_EVENTS = { + "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", + "bash.watchdog", "opencode.watchdog", +} +PROCESS_STATES = {"R", "S", "D", "Z", "T", "t", "X", "I", "gone", "unknown"} +PIPE_COUNTS = ("stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters") GIT_OPERATIONS = { "add", "write-tree", "diff", "diff-files", "diff-index", "check-ignore", "rev-parse", "ls-files", "status", "config", "hash-object", "cat-file", "other", @@ -92,7 +97,7 @@ def _log_event(line): def _boundary_event(line, identities): fields = line.split() - if len(fields) not in (3, 4, 5): + if len(fields) not in (3, 4, 5, 8): return None timestamp, event, key, *details = fields if event not in BOUNDARY_EVENTS or not re.fullmatch(r"[0-9]{1,22}", key): @@ -117,6 +122,18 @@ def _boundary_event(line, identities): if len(details) != 1 or details[0] not in {"success", "error"}: return None result["status"] = details.pop() + if phase == "watchdog": + count_fields = PIPE_COUNTS if source == "bash" else () + if len(details) != 1 + len(count_fields) or details[0] not in PROCESS_STATES: + return None + result["state"] = details.pop(0) + for field in count_fields: + count = details.pop(0) + if count == "-": + continue + if not re.fullmatch(r"[0-9]{1,7}", count): + return None + result[field] = int(count) if details: return None result["span"] = identities.setdefault((source, key), len(identities) + 1) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 06bebcc35..651024bf7 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -15,7 +15,7 @@ from fastapi.testclient import TestClient import httpx import pytest -from opencode_ci_probe import gateway_probe, process_environment +from opencode_ci_probe import gateway_probe, process_environment, watchdog_probe from opencode_ci_trace import save_failure_trace from process_helpers import assert_process_exited, python_cli @@ -399,12 +399,16 @@ def collect(outcome): if probe_enabled: monkeypatch.setattr(ToolGateway, 'call', gateway_probe(tmp_path, ToolGateway.call)) processes = [] + cli_pids = [] spawn = asyncio.create_subprocess_exec async def tracked_spawn(*args, **kwargs): - if probe_enabled and args[0] == native.executable('default') and args[1] == 'run': + probe_cli = probe_enabled and args[0] == native.executable('default') and args[1] == 'run' + if probe_cli: kwargs['env'] = process_environment(tmp_path, kwargs['env']) process = await spawn(*args, **kwargs) processes.append((process, kwargs.get('start_new_session', False))) + if probe_cli: + cli_pids.append(process.pid) if os.environ.get('OPENDIRECTOR_TEST_CLI_STALL') and 'run' in args: Path(os.environ['OPENDIRECTOR_TEST_CLI_STALL']).write_text(str(process.pid)) await asyncio.Event().wait() @@ -413,6 +417,11 @@ async def tracked_spawn(*args, **kwargs): def timed_out(): print('Real OpenCode integration timed out; thread stacks:', file=sys.stderr, flush=True) faulthandler.dump_traceback(file=sys.stderr, all_threads=True) + if cli_pids: + try: + watchdog_probe(tmp_path, tuple(cli_pids)) + except OSError: + print('Could not sample OpenCode process state', file=sys.stderr, flush=True) for process, group in reversed(processes): if process.returncode is None: try: diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index fbbc02c54..b7c796c18 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -6,7 +6,7 @@ import pytest -from opencode_ci_probe import process_environment, record_gateway_event +from opencode_ci_probe import process_environment, record_gateway_event, watchdog_probe from opencode_ci_trace import LIMIT, save_failure_trace @@ -71,6 +71,42 @@ def test_process_probes_preserve_command_exit_and_do_not_record_arguments(tmp_pa assert events[4]["span"] == events[5]["span"] and events[5]["status"] == "success" +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux" or not shutil.which("bash") or not shutil.which("git"), + reason="Linux Bash and Git probe") +def test_watchdog_probe_distinguishes_exited_bash_from_open_pipe(tmp_path): + env = process_environment(tmp_path, dict(os.environ)) + read_fd, write_fd = os.pipe() + try: + try: + with subprocess.Popen(["bash", "-c", "exit 0"], env=env, stdout=write_fd, stderr=write_fd) as bash: + assert bash.wait(timeout=5) == 0 + watchdog_probe(tmp_path, (os.getpid(),)) + finally: + os.close(write_fd) + watchdog_probe(tmp_path, (os.getpid(),)) + finally: + os.close(read_fd) + destination = tmp_path / "reports" + save_failure_trace(tmp_path, destination, "probe", "watchdog") + events = json.loads((destination / "probe.json").read_text())["events"] + start, exit_, first_cli, held, second_cli, closed = events + assert start["event"] == "bash.start" and exit_["event"] == "bash.exit" + assert first_cli["event"] == second_cli["event"] == "opencode.watchdog" + assert first_cli["state"] == second_cli["state"] == "R" + assert held["event"] == closed["event"] == "bash.watchdog" + assert held["span"] == closed["span"] == start["span"] + assert held["state"] == closed["state"] == "gone" + assert held["stdoutWriters"] == held["stderrWriters"] == 1 + assert closed["stdoutWriters"] == closed["stderrWriters"] == 0 + assert closed["stdoutReaders"] == closed["stderrReaders"] == 1 + assert set(held) == { + "event", "source", "span", "state", "tMs", + "stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters", + } + + @pytest.mark.cpu @pytest.mark.merge def test_trace_cap_keeps_latest_events_across_files(tmp_path): From 204cb9d8dc21042c7ce65dbb3a3074515a279998 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 16:01:51 +0800 Subject: [PATCH 08/25] Compare OpenCode child-process exit behavior in CI --- .github/workflows/release-checks.yml | 15 ++++ scripts/ci/opencode_child_process_probe.mjs | 88 +++++++++++++++++++++ tests/opencode_ci_probe.py | 21 +++-- tests/opencode_ci_trace.py | 10 ++- tests/test_opencode_ci_trace.py | 14 ++-- 5 files changed, 134 insertions(+), 14 deletions(-) create mode 100644 scripts/ci/opencode_child_process_probe.mjs diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 4ee1c10e9..1df4aa80a 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -128,6 +128,21 @@ jobs: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json + - name: Compare Node and Bun child processes on diagnostic PR + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' }} + timeout-minutes: 3 + continue-on-error: true + run: | + evidence=test-results/opencode-diagnostics + mkdir -p "$evidence" + probe=scripts/ci/opencode_child_process_probe.mjs + status=0 + timeout --kill-after=5s 45s node "$probe" > "$evidence/child-process-node.jsonl" || status=$? + bun_root="$RUNNER_TEMP/opencode-bun-control" + timeout --kill-after=5s 45s npm install --prefix "$bun_root" --ignore-scripts --no-package-lock --no-audit --no-fund @oven/bun-linux-x64@1.4.4 + bun="$bun_root/node_modules/@oven/bun-linux-x64/bin/bun" + timeout --kill-after=5s 45s "$bun" "$probe" > "$evidence/child-process-bun.jsonl" || status=$? + exit "$status" - id: harness-install name: Install native Harness test tools if: always() && steps.install.outcome == 'success' diff --git a/scripts/ci/opencode_child_process_probe.mjs b/scripts/ci/opencode_child_process_probe.mjs new file mode 100644 index 000000000..ca4789069 --- /dev/null +++ b/scripts/ci/opencode_child_process_probe.mjs @@ -0,0 +1,88 @@ +import { spawn } from "node:child_process"; +import { readFileSync, readlinkSync, writeSync } from "node:fs"; + +function emit(row) { + writeSync(1, JSON.stringify(row) + "\n"); +} + +function processState(pid) { + if (!pid) return "unknown"; + try { + return readFileSync(`/proc/${pid}/stat`, "utf8").split(") ").at(-1).split(" ")[0]; + } catch (error) { + return error.code === "ENOENT" ? "gone" : "unknown"; + } +} + +function descriptorKind(pid, fd) { + try { + const target = readlinkSync(`/proc/${pid}/fd/${fd}`); + if (target.startsWith("pipe:[")) return "pipe"; + if (target.startsWith("socket:[")) return "socket"; + return "other"; + } catch { + return "unavailable"; + } +} + +function trial(label, index, command) { + return new Promise((resolve) => { + const started = performance.now(); + const child = spawn("/bin/bash", ["-c", command], { + detached: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const events = {}; + let descriptorKinds; + let exitCode; + let settled = false; + const stamp = (event) => { + events[event] = Math.round(performance.now() - started); + }; + function finish(outcome, closeCode) { + if (settled) return; + settled = true; + clearTimeout(timer); + const state = processState(child.pid); + const passed = outcome === "close" && closeCode === 0 && exitCode === 0 && state === "gone" + && ["spawn", "exit", "stdoutEnd", "stderrEnd"].every((event) => event in events); + emit({ label, index, outcome, passed, state, descriptorKinds, events }); + resolve(passed); + } + const timer = setTimeout(() => { + finish("timeout"); + child.kill("SIGKILL"); + child.stdout.destroy(); + child.stderr.destroy(); + }, 3000); + child.once("spawn", () => { + stamp("spawn"); + descriptorKinds = [descriptorKind(child.pid, 1), descriptorKind(child.pid, 2)]; + }); + child.once("exit", (code) => { + stamp("exit"); + exitCode = code; + }); + child.stdout.once("end", () => stamp("stdoutEnd")); + child.stderr.once("end", () => stamp("stderrEnd")); + child.stdout.resume(); + child.stderr.resume(); + child.once("error", () => finish("error")); + child.once("close", (code) => { + stamp("close"); + finish("close", code); + }); + }); +} + +emit({ runtime: process.versions.bun ? "bun" : "node", version: process.versions.bun ?? process.versions.node }); +const fixture = "printf 'control\\n'; printf 'control\\n' >&2"; +let passed = 0; +for (let index = 1; index <= 50; index++) { + passed += Number(await trial("fast", index, fixture)); +} +for (let index = 1; index <= 4; index++) { + passed += Number(await trial("delayed", index, `sleep 1.7; ${fixture}`)); +} +emit({ passed, total: 54 }); +process.exitCode = passed === 54 ? 0 : 1; diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index 3f08c9c29..5773213c7 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -52,13 +52,14 @@ def process_environment(root: Path, env: dict[str, str]): } -def _process_state(path): +def _process_status(path): try: - return (path / "stat").read_text().rsplit(") ", 1)[1].split()[0] + state, parent, *_ = (path / "stat").read_text().rsplit(") ", 1)[1].split() + return state, parent except FileNotFoundError: - return "gone" - except (OSError, IndexError): - return "unknown" + return "gone", None + except (OSError, IndexError, ValueError): + return "unknown", None def _pipe_holders(proc, pipes): @@ -111,14 +112,20 @@ def watchdog_probe(root, cli_pids): bash_pids[pid][descriptor] = f"pipe:[{inode}]" pipes = {pipe for descriptors in bash_pids.values() for pipe in descriptors.values()} holders = _pipe_holders(proc, pipes) if pipes else {} + cli_identities = {str(pid) for pid in cli_pids} with boundaries.open("a", encoding="utf-8") as output: for pid in cli_pids: - output.write(f"{time.time()} opencode.watchdog {pid} {_process_state(proc / str(pid))}\n") + state, _ = _process_status(proc / str(pid)) + output.write(f"{time.time()} opencode.watchdog {pid} {state}\n") for pid, descriptors in bash_pids.items(): + state, parent = _process_status(proc / pid) + parent_role = "unknown" + if parent is not None: + parent_role = "opencode" if parent in cli_identities else "other" counts = [count for descriptor in ("1", "2") for count in holders.get(descriptors.get(descriptor), ("-", "-"))] readers_out, writers_out, readers_err, writers_err = counts - output.write(f"{time.time()} bash.watchdog {pid} {_process_state(proc / pid)} " + output.write(f"{time.time()} bash.watchdog {pid} {state} {parent_role} " f"{readers_out} {writers_out} {readers_err} {writers_err}\n") diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index dc8814ef8..e9f5337fd 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -97,7 +97,7 @@ def _log_event(line): def _boundary_event(line, identities): fields = line.split() - if len(fields) not in (3, 4, 5, 8): + if len(fields) not in (3, 4, 5, 9): return None timestamp, event, key, *details = fields if event not in BOUNDARY_EVENTS or not re.fullmatch(r"[0-9]{1,22}", key): @@ -124,9 +124,15 @@ def _boundary_event(line, identities): result["status"] = details.pop() if phase == "watchdog": count_fields = PIPE_COUNTS if source == "bash" else () - if len(details) != 1 + len(count_fields) or details[0] not in PROCESS_STATES: + expected = 2 + len(count_fields) if source == "bash" else 1 + if len(details) != expected or details[0] not in PROCESS_STATES: return None result["state"] = details.pop(0) + if source == "bash": + parent = details.pop(0) + if parent not in {"opencode", "other", "unknown"}: + return None + result["parentRole"] = parent for field in count_fields: count = details.pop(0) if count == "-": diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index b7c796c18..8825b81db 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -81,6 +81,8 @@ def test_watchdog_probe_distinguishes_exited_bash_from_open_pipe(tmp_path): try: try: with subprocess.Popen(["bash", "-c", "exit 0"], env=env, stdout=write_fd, stderr=write_fd) as bash: + os.waitid(os.P_PID, bash.pid, os.WEXITED | os.WNOWAIT) + watchdog_probe(tmp_path, (os.getpid(),)) assert bash.wait(timeout=5) == 0 watchdog_probe(tmp_path, (os.getpid(),)) finally: @@ -91,18 +93,20 @@ def test_watchdog_probe_distinguishes_exited_bash_from_open_pipe(tmp_path): destination = tmp_path / "reports" save_failure_trace(tmp_path, destination, "probe", "watchdog") events = json.loads((destination / "probe.json").read_text())["events"] - start, exit_, first_cli, held, second_cli, closed = events + start, exit_, zombie_cli, zombie, first_cli, held, second_cli, closed = events assert start["event"] == "bash.start" and exit_["event"] == "bash.exit" - assert first_cli["event"] == second_cli["event"] == "opencode.watchdog" + assert zombie_cli["event"] == first_cli["event"] == second_cli["event"] == "opencode.watchdog" assert first_cli["state"] == second_cli["state"] == "R" - assert held["event"] == closed["event"] == "bash.watchdog" - assert held["span"] == closed["span"] == start["span"] + assert zombie["event"] == held["event"] == closed["event"] == "bash.watchdog" + assert zombie["span"] == held["span"] == closed["span"] == start["span"] + assert zombie["state"] == "Z" and zombie["parentRole"] == "opencode" assert held["state"] == closed["state"] == "gone" + assert held["parentRole"] == closed["parentRole"] == "unknown" assert held["stdoutWriters"] == held["stderrWriters"] == 1 assert closed["stdoutWriters"] == closed["stderrWriters"] == 0 assert closed["stdoutReaders"] == closed["stderrReaders"] == 1 assert set(held) == { - "event", "source", "span", "state", "tMs", + "event", "source", "span", "state", "parentRole", "tMs", "stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters", } From 67a198e678a24cda21754ab9e0a4bcbbd2264473 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 16:40:19 +0800 Subject: [PATCH 09/25] Compare Bun child waits on the hosted diagnostic runner --- .github/workflows/release-checks.yml | 39 +++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 1df4aa80a..782803657 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -102,7 +102,8 @@ jobs: - name: Check generated contracts if: always() && steps.install.outcome == 'success' run: python scripts/generate_contracts.py --check - - name: Install ripgrep on diagnostic PR + - id: diagnostic-ripgrep + name: Install ripgrep on diagnostic PR if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' timeout-minutes: 3 run: | @@ -128,6 +129,42 @@ jobs: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json + - name: Compare Bun child wait paths on diagnostic PR + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} + timeout-minutes: 6 + continue-on-error: true + env: + OPENDIRECTOR_REAL_CLI: '1' + BUN_GARBAGE_COLLECTOR_LEVEL: '0' + run: | + evidence="$RUNNER_TEMP/opencode-waiter-evidence" + mkdir -p "$evidence" + printf 'trial\texit_code\telapsed_seconds\n' > "$evidence/results.tsv" + for trial in 01-default 02-waiter 03-waiter 04-default; do + unset BUN_FEATURE_FLAG_FORCE_WAITER_THREAD + if [[ "$trial" == *-waiter ]]; then + export BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1 + fi + export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" + started=$SECONDS + result=0 + timeout --kill-after=5s 85s python -m pytest -q --tb=short \ + --basetemp "$RUNNER_TEMP/opencode-waiter-$trial" \ + 'tests/test_native_runtime.py::test_real_opencode_native_skill_and_gateway_write[False-default]' || result=$? + printf '%s\t%s\t%s\n' "$trial" "$result" "$((SECONDS - started))" | tee -a "$evidence/results.tsv" + if [[ "$result" == 124 || "$result" == 137 ]]; then + exit "$result" + fi + done + - name: Upload Bun child wait comparison + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} + continue-on-error: true + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opencode-waiter-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-waiter-evidence/ + retention-days: 14 + if-no-files-found: warn - name: Compare Node and Bun child processes on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' }} timeout-minutes: 3 From d80039796d552e2ca3cccc959b31ae270733c995 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 17:27:46 +0800 Subject: [PATCH 10/25] Compare OpenCode snapshots around first tool completion --- .github/workflows/release-checks.yml | 30 ++++++++++++++-------------- tests/test_native_runtime.py | 8 +++++++- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 782803657..4817b04ce 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -129,40 +129,40 @@ jobs: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - - name: Compare Bun child wait paths on diagnostic PR + - name: Compare OpenCode snapshots on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} timeout-minutes: 6 continue-on-error: true env: OPENDIRECTOR_REAL_CLI: '1' - BUN_GARBAGE_COLLECTOR_LEVEL: '0' run: | - evidence="$RUNNER_TEMP/opencode-waiter-evidence" + evidence="$RUNNER_TEMP/opencode-snapshot-evidence" mkdir -p "$evidence" - printf 'trial\texit_code\telapsed_seconds\n' > "$evidence/results.tsv" - for trial in 01-default 02-waiter 03-waiter 04-default; do - unset BUN_FEATURE_FLAG_FORCE_WAITER_THREAD - if [[ "$trial" == *-waiter ]]; then - export BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1 - fi + printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\n' > "$evidence/results.tsv" + for trial in 01-on 02-off 03-off 04-on; do + export OPENDIRECTOR_CI_SNAPSHOT="${trial#*-}" export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" + basetemp="$RUNNER_TEMP/opencode-snapshot-$trial" started=$SECONDS result=0 timeout --kill-after=5s 85s python -m pytest -q --tb=short \ - --basetemp "$RUNNER_TEMP/opencode-waiter-$trial" \ - 'tests/test_native_runtime.py::test_real_opencode_native_skill_and_gateway_write[False-default]' || result=$? - printf '%s\t%s\t%s\n' "$trial" "$result" "$((SECONDS - started))" | tee -a "$evidence/results.tsv" + --basetemp "$basetemp" \ + 'tests/test_agent_visual_gate.py::test_real_opencode_native_visual_input[text-only-model]' || result=$? + elapsed=$((SECONDS - started)) + counts="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | + awk '$2 == "git.start" { git++; if ($4 == "write-tree") snapshots++ } END { printf "%d\t%d", git, snapshots }')" + printf '%s\t%s\t%s\t%s\n' "$trial" "$result" "$elapsed" "$counts" | tee -a "$evidence/results.tsv" if [[ "$result" == 124 || "$result" == 137 ]]; then exit "$result" fi done - - name: Upload Bun child wait comparison + - name: Upload OpenCode snapshot comparison if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: opencode-waiter-comparison-${{ github.run_attempt }} - path: ${{ runner.temp }}/opencode-waiter-evidence/ + name: opencode-snapshot-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-snapshot-evidence/ retention-days: 14 if-no-files-found: warn - name: Compare Node and Bun child processes on diagnostic PR diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 651024bf7..9b2ce6724 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -404,7 +404,13 @@ def collect(outcome): async def tracked_spawn(*args, **kwargs): probe_cli = probe_enabled and args[0] == native.executable('default') and args[1] == 'run' if probe_cli: - kwargs['env'] = process_environment(tmp_path, kwargs['env']) + env = process_environment(tmp_path, kwargs['env']) + snapshot = os.environ.get('OPENDIRECTOR_CI_SNAPSHOT') + if snapshot in {'on', 'off'}: + config = json.loads(env['OPENCODE_CONFIG_CONTENT']) + config['snapshot'] = snapshot == 'on' + env['OPENCODE_CONFIG_CONTENT'] = json.dumps(config) + kwargs['env'] = env process = await spawn(*args, **kwargs) processes.append((process, kwargs.get('start_new_session', False))) if probe_cli: From dd222f05e8b9396e476bc442bc96788b19db5e16 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 19:56:41 +0800 Subject: [PATCH 11/25] [ci] Sample Git child state on OpenCode timeout ## summary Record recent Git wrapper process states and parent roles at the existing watchdog. Preserve allowlisted trace fields and add synthetic and Linux reaping checks. Refs: #162 --- docs/development/validation.md | 4 +++ tests/opencode_ci_probe.py | 9 +++++++ tests/opencode_ci_trace.py | 8 +++--- tests/test_opencode_ci_trace.py | 46 +++++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/docs/development/validation.md b/docs/development/validation.md index 722ea1bc0..ee73ca3bd 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -181,6 +181,10 @@ Python CI saves separate JUnit XML, `--durations=50` logs and opt-in `--ci-profi If a bundled OpenCode regression worker fails, look in `opencode-diagnostics/` in the same artifact for allowlisted model, tool and OpenCode events, plus Bash, Git and business gateway boundaries on Linux. Time is relative to the first retained event. `droppedEvents` counts events omitted by the cap. Reports exclude raw logs, model or tool content, credentials and file paths. +Linux watchdog 还采样最近 8 个 Git 包装进程的状态和父进程归属,通过 `span` 关联起止事件。`git.exit` 只表示包装脚本到达退出前的记录点;`git.watchdog` 的 `Z` 表示采样时已退出但尚未回收,`gone` 表示原 PID 已不存在。PID 可能复用,因此其他存活状态不能单独证明原进程仍在运行。 + +The Linux watchdog also samples the last eight Git wrapper process states and parent roles, linked to start/exit events by `span`. `git.exit` only marks the wrapper's pre-exit logging point; watchdog state `Z` means exited but unreaped at sampling time, while `gone` means the PID no longer exists. PIDs can be reused, so other live states alone do not prove that the original process remains alive. + ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json ``` diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index 5773213c7..47b6563e5 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -95,12 +95,16 @@ def watchdog_probe(root, cli_pids): proc = Path("/proc") boundaries = root / "process-boundaries.log" bash_pids = {} + git_pids = {} if boundaries.is_file(): for line in boundaries.read_text().splitlines(): fields = line.split() if len(fields) == 3 and fields[1] == "bash.start" and fields[2].isdecimal(): bash_pids[fields[2]] = {} + if len(fields) == 4 and fields[1] == "git.start" and fields[2].isdecimal(): + git_pids[fields[2]] = fields[3] bash_pids = dict(list(bash_pids.items())[-4:]) + git_pids = dict(list(git_pids.items())[-8:]) pipe_log = root / "bash-pipes.log" if pipe_log.is_file(): for line in pipe_log.read_text().splitlines(): @@ -117,6 +121,11 @@ def watchdog_probe(root, cli_pids): for pid in cli_pids: state, _ = _process_status(proc / str(pid)) output.write(f"{time.time()} opencode.watchdog {pid} {state}\n") + for pid, operation in git_pids.items(): + state, parent = _process_status(proc / pid) + parent_role = "unknown" if parent is None else ( + "opencode" if parent in cli_identities else "other") + output.write(f"{time.time()} git.watchdog {pid} {operation} {state} {parent_role}\n") for pid, descriptors in bash_pids.items(): state, parent = _process_status(proc / pid) parent_role = "unknown" diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index e9f5337fd..d1cd33f07 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -19,7 +19,7 @@ LOG_LINE = re.compile(r'^timestamp=(\S+) level=\w+ .*?\bmessage=(?:"([^"]+)"|(\S+))') BOUNDARY_EVENTS = { "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", - "bash.watchdog", "opencode.watchdog", + "bash.watchdog", "opencode.watchdog", "git.watchdog", } PROCESS_STATES = {"R", "S", "D", "Z", "T", "t", "X", "I", "gone", "unknown"} PIPE_COUNTS = ("stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters") @@ -97,7 +97,7 @@ def _log_event(line): def _boundary_event(line, identities): fields = line.split() - if len(fields) not in (3, 4, 5, 9): + if len(fields) not in (3, 4, 5, 6, 9): return None timestamp, event, key, *details = fields if event not in BOUNDARY_EVENTS or not re.fullmatch(r"[0-9]{1,22}", key): @@ -124,11 +124,11 @@ def _boundary_event(line, identities): result["status"] = details.pop() if phase == "watchdog": count_fields = PIPE_COUNTS if source == "bash" else () - expected = 2 + len(count_fields) if source == "bash" else 1 + expected = 2 + len(count_fields) if source in {"bash", "git"} else 1 if len(details) != expected or details[0] not in PROCESS_STATES: return None result["state"] = details.pop(0) - if source == "bash": + if source in {"bash", "git"}: parent = details.pop(0) if parent not in {"opencode", "other", "unknown"}: return None diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index 8825b81db..51fd4f6c2 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -126,3 +126,49 @@ def test_trace_cap_keeps_latest_events_across_files(tmp_path): assert report["droppedEvents"] == 1 assert report["events"][-1]["event"] == "model.completed" assert report["events"][-1]["tMs"] == LIMIT * 1000 + + +@pytest.mark.cpu +@pytest.mark.merge +def test_git_watchdog_exports_recent_process_relationships_without_raw_ids(tmp_path, monkeypatch): + import opencode_ci_probe + + (tmp_path / "process-boundaries.log").write_text("".join( + f"{pid} git.start {pid} diff\n{pid}.1 git.exit {pid} diff 0\n" + for pid in range(100, 110) + ), encoding="utf-8") + statuses = {"200": ("R", "1"), "109": ("Z", "200"), "108": ("S", "300")} + monkeypatch.setattr(opencode_ci_probe, "_process_status", + lambda path: statuses.get(path.name, ("gone", None))) + watchdog_probe(tmp_path, (200,)) + save_failure_trace(tmp_path, tmp_path / "reports", "git", "watchdog") + events = json.loads((tmp_path / "reports/git.json").read_text())["events"] + samples = [event for event in events if event["event"] == "git.watchdog"] + assert len(samples) == 8 + assert [event["state"] for event in samples] == ["gone"] * 6 + ["S", "Z"] + assert [event["parentRole"] for event in samples] == ["unknown"] * 6 + ["other", "opencode"] + assert all(event["operation"] == "diff" for event in samples) + starts = [event for event in events if event["event"] == "git.start"] + assert [event["span"] for event in samples] == [event["span"] for event in starts[-8:]] + assert all(set(event) == {"event", "source", "operation", "span", "state", "parentRole", "tMs"} + for event in samples) + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux" or not shutil.which("git"), reason="Linux Git probe") +def test_git_watchdog_observes_wrapper_exit_before_parent_reaps_it(tmp_path): + env = process_environment(tmp_path, dict(os.environ)) + with subprocess.Popen(["git", "--version"], env=env, stdout=subprocess.DEVNULL) as child: + os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOWAIT) + watchdog_probe(tmp_path, (os.getpid(),)) + assert child.wait(timeout=5) == 0 + watchdog_probe(tmp_path, (os.getpid(),)) + save_failure_trace(tmp_path, tmp_path / "reports", "git", "watchdog") + events = json.loads((tmp_path / "reports/git.json").read_text())["events"] + samples = [event for event in events if event["event"] == "git.watchdog"] + assert [event["state"] for event in samples] == ["Z", "gone"] + assert [event["parentRole"] for event in samples] == ["opencode", "unknown"] + exit_event, = [event for event in events if event["event"] == "git.exit"] + assert exit_event["exitCode"] == 0 + assert samples[0]["span"] == samples[1]["span"] == exit_event["span"] From 8c1f74c01e1883abf3b2d317770587777e3f129f Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 20:35:59 +0800 Subject: [PATCH 12/25] [ci] Measure OpenCode CPU activity at watchdog ## summary Record bounded main-thread and process CPU tick deltas before timeout cleanup. Omit unavailable or changed process identities and export only numeric evidence. Refs: #162 --- docs/development/validation.md | 4 +++ tests/opencode_ci_probe.py | 28 ++++++++++++++++ tests/opencode_ci_trace.py | 12 +++++-- tests/test_native_runtime.py | 3 +- tests/test_opencode_ci_trace.py | 57 +++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 3 deletions(-) diff --git a/docs/development/validation.md b/docs/development/validation.md index ee73ca3bd..76cdff9e9 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -185,6 +185,10 @@ Linux watchdog 还采样最近 8 个 Git 包装进程的状态和父进程归属 The Linux watchdog also samples the last eight Git wrapper process states and parent roles, linked to start/exit events by `span`. `git.exit` only marks the wrapper's pre-exit logging point; watchdog state `Z` means exited but unreaped at sampling time, while `gone` means the PID no longer exists. PIDs can be reused, so other live states alone do not prove that the original process remains alive. +清理前的 `opencode.cpu` 在约 200 毫秒窗口内记录主线程及整个进程的 CPU tick 增量,同时保存实际窗口长度和每秒 tick 数。两端进程启动时间必须一致;不可读、已退出或身份变化的样本不导出。CPU 活跃并不能单独证明 JavaScript 忙循环;采样会使超时后的清理延迟约 200 毫秒。 + +Before cleanup, `opencode.cpu` records main-thread and whole-process CPU tick deltas over an approximately 200 ms window, together with actual sample duration and ticks per second. Process start times must match across samples; unreadable, exited or changed identities are omitted. CPU activity alone does not establish a JavaScript busy loop. Sampling delays timeout cleanup by approximately 200 ms. + ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json ``` diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index 47b6563e5..6476d2ce1 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -62,6 +62,34 @@ def _process_status(path): return "unknown", None +def _cpu_ticks(path): + try: + fields = path.read_text().rsplit(") ", 1)[1].split() + return int(fields[19]), int(fields[11]) + int(fields[12]) + except (OSError, IndexError, ValueError): + return None + + +def cpu_probe(root, cli_pids): + proc = Path("/proc") + paths = {pid: (proc / str(pid) / "stat", proc / str(pid) / "task" / str(pid) / "stat") + for pid in cli_pids} + before = {pid: tuple(_cpu_ticks(path) for path in pair) for pid, pair in paths.items()} + started = time.monotonic() + time.sleep(0.2) + after = {pid: tuple(_cpu_ticks(path) for path in pair) for pid, pair in paths.items()} + elapsed_ms = round((time.monotonic() - started) * 1000) + with (root / "process-boundaries.log").open("a", encoding="utf-8") as output: + for pid in paths: + old, new = before[pid], after[pid] + if any(a is None or b is None or a[0] != b[0] or b[1] < a[1] + for a, b in zip(old, new)): + continue + total, main = (b[1] - a[1] for a, b in zip(old, new)) + output.write(f"{time.time()} opencode.cpu {pid} {elapsed_ms} {main} {total} " + f"{os.sysconf('SC_CLK_TCK')}\n") + + def _pipe_holders(proc, pipes): holders = {pipe: [0, 0] for pipe in pipes} uid = os.getuid() diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index d1cd33f07..5e48a81ab 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -19,7 +19,7 @@ LOG_LINE = re.compile(r'^timestamp=(\S+) level=\w+ .*?\bmessage=(?:"([^"]+)"|(\S+))') BOUNDARY_EVENTS = { "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", - "bash.watchdog", "opencode.watchdog", "git.watchdog", + "bash.watchdog", "opencode.watchdog", "git.watchdog", "opencode.cpu", } PROCESS_STATES = {"R", "S", "D", "Z", "T", "t", "X", "I", "gone", "unknown"} PIPE_COUNTS = ("stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters") @@ -97,7 +97,7 @@ def _log_event(line): def _boundary_event(line, identities): fields = line.split() - if len(fields) not in (3, 4, 5, 6, 9): + if len(fields) not in (3, 4, 5, 6, 7, 9): return None timestamp, event, key, *details = fields if event not in BOUNDARY_EVENTS or not re.fullmatch(r"[0-9]{1,22}", key): @@ -110,6 +110,14 @@ def _boundary_event(line, identities): return None source, phase = event.split(".") result = {"source": source, "event": event, "at": at} + if event == "opencode.cpu": + if len(details) != 4 or any(not re.fullmatch(r"[0-9]{1,9}", value) for value in details): + return None + result.update(zip(("sampleMs", "mainTicks", "totalTicks", "ticksPerSecond"), map(int, details))) + if result["sampleMs"] == 0 or result["ticksPerSecond"] == 0: + return None + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result if source == "git": if not details or details[0] not in GIT_OPERATIONS: return None diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 9b2ce6724..99bd0f66b 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -15,7 +15,7 @@ from fastapi.testclient import TestClient import httpx import pytest -from opencode_ci_probe import gateway_probe, process_environment, watchdog_probe +from opencode_ci_probe import cpu_probe, gateway_probe, process_environment, watchdog_probe from opencode_ci_trace import save_failure_trace from process_helpers import assert_process_exited, python_cli @@ -426,6 +426,7 @@ def timed_out(): if cli_pids: try: watchdog_probe(tmp_path, tuple(cli_pids)) + cpu_probe(tmp_path, tuple(cli_pids)) except OSError: print('Could not sample OpenCode process state', file=sys.stderr, flush=True) for process, group in reversed(processes): diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index 51fd4f6c2..e8fff3315 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -172,3 +172,60 @@ def test_git_watchdog_observes_wrapper_exit_before_parent_reaps_it(tmp_path): exit_event, = [event for event in events if event["event"] == "git.exit"] assert exit_event["exitCode"] == 0 assert samples[0]["span"] == samples[1]["span"] == exit_event["span"] + + +@pytest.mark.cpu +@pytest.mark.merge +def test_cpu_probe_exports_tick_deltas_and_omits_reused_processes(tmp_path, monkeypatch): + import opencode_ci_probe as probe + + values = iter([(10, 100), (10, 50), (11, 30), None, + (10, 125), (10, 70), (12, 40), None]) + monkeypatch.setattr(probe, "_cpu_ticks", lambda path: next(values)) + times = iter([10, 10.25]) + monkeypatch.setattr(probe.time, "monotonic", lambda: next(times)) + monkeypatch.setattr(probe.time, "sleep", lambda seconds: None) + monkeypatch.setattr(probe.os, "sysconf", lambda key: 100, raising=False) + probe.cpu_probe(tmp_path, (123456, 234567)) + save_failure_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") + raw = (tmp_path / "reports/cpu.json").read_text() + assert "123456" not in raw and "234567" not in raw + assert json.loads(raw)["events"] == [{ + "event": "opencode.cpu", "source": "opencode", "sampleMs": 250, + "mainTicks": 20, "totalTicks": 25, "ticksPerSecond": 100, "span": 1, "tMs": 0, + }] + + +@pytest.mark.cpu +@pytest.mark.merge +def test_cpu_ticks_reads_stat_fields_with_spaces_and_parentheses_in_name(tmp_path): + from opencode_ci_probe import _cpu_ticks + + stat = tmp_path / "stat" + fields = ["S"] + ["0"] * 19 + fields[11], fields[12], fields[19] = "12", "3", "987" + stat.write_text("42 (private ) process) " + " ".join(fields)) + assert _cpu_ticks(stat) == (987, 15) + stat.write_text("truncated") + assert _cpu_ticks(stat) is None + assert _cpu_ticks(tmp_path / "missing") is None + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux", reason="Linux per-thread CPU accounting") +def test_cpu_probe_observes_live_main_thread_work(tmp_path, monkeypatch): + import time + import opencode_ci_probe as probe + + def work(seconds): + until = time.thread_time() + seconds + while time.thread_time() < until: + pass + + monkeypatch.setattr(probe.time, "sleep", work) + probe.cpu_probe(tmp_path, (os.getpid(),)) + save_failure_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") + event, = json.loads((tmp_path / "reports/cpu.json").read_text())["events"] + assert event["mainTicks"] > 0 and event["totalTicks"] > 0 + assert event["sampleMs"] >= 100 and event["ticksPerSecond"] == os.sysconf("SC_CLK_TCK") From 2cc5bccb4e9b151b9aa3950c666f8f981e28248a Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 20:37:55 +0800 Subject: [PATCH 13/25] [ci] Omit exited processes from CPU sampling ## summary Reject zombie and dead process states when reading CPU counters, matching the documented sampling contract. --- tests/opencode_ci_probe.py | 2 ++ tests/test_opencode_ci_trace.py | 3 +++ 2 files changed, 5 insertions(+) diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index 6476d2ce1..e8b9830bb 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -65,6 +65,8 @@ def _process_status(path): def _cpu_ticks(path): try: fields = path.read_text().rsplit(") ", 1)[1].split() + if fields[0] in {"Z", "X", "x"}: + return None return int(fields[19]), int(fields[11]) + int(fields[12]) except (OSError, IndexError, ValueError): return None diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index e8fff3315..18621a957 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -206,6 +206,9 @@ def test_cpu_ticks_reads_stat_fields_with_spaces_and_parentheses_in_name(tmp_pat fields[11], fields[12], fields[19] = "12", "3", "987" stat.write_text("42 (private ) process) " + " ".join(fields)) assert _cpu_ticks(stat) == (987, 15) + fields[0] = "Z" + stat.write_text("42 (exited) " + " ".join(fields)) + assert _cpu_ticks(stat) is None stat.write_text("truncated") assert _cpu_ticks(stat) is None assert _cpu_ticks(tmp_path / "missing") is None From 572034d98ed7f90a26ca689b6325e7cfdbec56d6 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 21:18:51 +0800 Subject: [PATCH 14/25] [ci] Capture bounded native stack on OpenCode timeout ## summary Add opt-in main-thread GDB sampling with a hard timeout and restricted runtime-symbol export. Install GDB only for diagnostic PR 633 and test sanitization, failure outcomes and live detach. Refs: #162 --- .github/workflows/release-checks.yml | 6 ++- docs/development/validation.md | 4 ++ tests/opencode_ci_probe.py | 36 ++++++++++++++ tests/opencode_ci_trace.py | 21 ++++++++ tests/test_native_runtime.py | 3 +- tests/test_opencode_ci_trace.py | 74 ++++++++++++++++++++++++++++ 6 files changed, 141 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 4817b04ce..e9a4c5ab1 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -103,12 +103,14 @@ jobs: if: always() && steps.install.outcome == 'success' run: python scripts/generate_contracts.py --check - id: diagnostic-ripgrep - name: Install ripgrep on diagnostic PR + name: Install diagnostic runtime tools if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' timeout-minutes: 3 run: | - sudo apt-get install --yes ripgrep + sudo apt-get install --yes ripgrep gdb rg --version + gdb --version | head -1 + echo 'OPENDIRECTOR_CI_NATIVE_STACK=1' >> "$GITHUB_ENV" - name: Standalone OpenCode control on diagnostic PR if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' timeout-minutes: 6 diff --git a/docs/development/validation.md b/docs/development/validation.md index 76cdff9e9..d4146612a 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -189,6 +189,10 @@ The Linux watchdog also samples the last eight Git wrapper process states and pa Before cleanup, `opencode.cpu` records main-thread and whole-process CPU tick deltas over an approximately 200 ms window, together with actual sample duration and ticks per second. Process start times must match across samples; unreadable, exited or changed identities are omitted. CPU activity alone does not establish a JavaScript busy loop. Sampling delays timeout cleanup by approximately 200 ms. +仅在诊断 PR 显式开启 `OPENDIRECTOR_CI_NATIVE_STACK=1` 时,watchdog 在清理前通过 GDB 采样最后一个 CLI 的主线程原生栈。调试器禁止自动加载和符号下载,由独立的 3 秒硬超时限制,调用方另有 5 秒超时;正常采样后解除附加。报告仅保留最多 20 帧的深度及受限运行时符号,其他符号标记为 unknown;不保存原始 GDB 输出、地址、参数、路径或内存。附加会短暂停止进程,原生栈不等于 JavaScript 调用栈,缺失符号不能证明对应代码未执行。 + +Only when the diagnostic PR explicitly enables `OPENDIRECTOR_CI_NATIVE_STACK=1`, the watchdog samples the last CLI's main native thread with GDB before cleanup. Auto-loading and symbol downloads are disabled; an independent three-second hard timeout bounds GDB, with a five-second caller timeout. Normal sampling detaches. Reports retain at most 20 frame depths and restricted runtime symbols, mapping other symbols to unknown; raw GDB output, addresses, arguments, paths and memory are not saved. Attaching briefly pauses the process. Native frames are not a JavaScript stack, and missing symbols do not establish that corresponding code was absent. + ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json ``` diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index e8b9830bb..8d8fa55ad 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -3,8 +3,44 @@ import os from pathlib import Path import shutil +import re +import subprocess import time +from opencode_ci_trace import native_symbol + + +def native_stack_probe(root, cli_pids): + if os.environ.get("OPENDIRECTOR_CI_NATIVE_STACK") != "1": + return + for pid in cli_pids[-1:]: + status, frames = "missing", [] + if shutil.which("gdb") and shutil.which("sudo") and shutil.which("timeout"): + command = ["sudo", "-n", "timeout", "--signal=KILL", "3s", "gdb", "--batch", "--nx", "--quiet", + "-iex", "set auto-load off", "-iex", "set debuginfod enabled off", + "-ex", "set print thread-events off", "-ex", "set print frame-arguments none", + "-ex", "set print entry-values no", "-p", str(pid), + "-ex", "python import gdb; next(t for t in gdb.selected_inferior().threads() " + f"if t.ptid[1] == {int(pid)}).switch()", + "-ex", "bt 20", "-ex", "detach"] + try: + result = subprocess.run(command, capture_output=True, text=True, timeout=5, + env={**os.environ, "DEBUGINFOD_URLS": "", "LC_ALL": "C"}) + for line in result.stdout.splitlines(): + match = re.match(r"^#(\d+)\s+(?:0x[0-9a-fA-F]+\s+in\s+)?([^\s(]+)", line) + if match and int(match[1]) < 20: + frames.append((int(match[1]), native_symbol(match[2]))) + status = "timeout" if result.returncode in {124, 137} else ( + "error" if result.returncode else "ok" if frames else "empty") + except subprocess.TimeoutExpired: + status = "timeout" + except OSError: + status = "error" + with (root / "process-boundaries.log").open("a", encoding="utf-8") as output: + output.write(f"{time.time()} opencode.stack {pid} {status}\n") + for depth, symbol in frames[:20]: + output.write(f"{time.time()} opencode.frame {pid} {depth} {symbol}\n") + def process_environment(root: Path, env: dict[str, str]): probe = root / "ci-probe" diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index 5e48a81ab..c34cd4225 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -20,6 +20,7 @@ BOUNDARY_EVENTS = { "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", "bash.watchdog", "opencode.watchdog", "git.watchdog", "opencode.cpu", + "opencode.stack", "opencode.frame", } PROCESS_STATES = {"R", "S", "D", "Z", "T", "t", "X", "I", "gone", "unknown"} PIPE_COUNTS = ("stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters") @@ -30,6 +31,14 @@ LIMIT = 256 +def native_symbol(value): + if (re.fullmatch(r"[A-Za-z0-9_:.$~<>]{1,160}", value) + and value.startswith(("JSC::", "WTF::", "Bun::", "bun::", "uv_", "mi_", + "__pthread", "epoll_", "pthread_"))): + return value + return "unknown" + + def _number(value): return type(value) in (int, float) and abs(value) < 1e15 and isfinite(value) @@ -110,6 +119,18 @@ def _boundary_event(line, identities): return None source, phase = event.split(".") result = {"source": source, "event": event, "at": at} + if event == "opencode.stack": + if len(details) != 1 or details[0] not in {"ok", "empty", "error", "timeout", "missing"}: + return None + result["status"] = details[0] + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result + if event == "opencode.frame": + if len(details) != 2 or not details[0].isdigit() or int(details[0]) >= 20: + return None + result.update(depth=int(details[0]), symbol=native_symbol(details[1])) + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result if event == "opencode.cpu": if len(details) != 4 or any(not re.fullmatch(r"[0-9]{1,9}", value) for value in details): return None diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 99bd0f66b..a515bd640 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -15,7 +15,7 @@ from fastapi.testclient import TestClient import httpx import pytest -from opencode_ci_probe import cpu_probe, gateway_probe, process_environment, watchdog_probe +from opencode_ci_probe import cpu_probe, gateway_probe, native_stack_probe, process_environment, watchdog_probe from opencode_ci_trace import save_failure_trace from process_helpers import assert_process_exited, python_cli @@ -427,6 +427,7 @@ def timed_out(): try: watchdog_probe(tmp_path, tuple(cli_pids)) cpu_probe(tmp_path, tuple(cli_pids)) + native_stack_probe(tmp_path, tuple(cli_pids)) except OSError: print('Could not sample OpenCode process state', file=sys.stderr, flush=True) for process, group in reversed(processes): diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index 18621a957..e197c037e 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -232,3 +232,77 @@ def work(seconds): event, = json.loads((tmp_path / "reports/cpu.json").read_text())["events"] assert event["mainTicks"] > 0 and event["totalTicks"] > 0 assert event["sampleMs"] >= 100 and event["ticksPerSecond"] == os.sysconf("SC_CLK_TCK") + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.parametrize("returncode,expected", [(0, "ok"), (1, "error"), (137, "timeout")]) +def test_native_stack_probe_bounds_and_sanitizes_debugger_output(tmp_path, monkeypatch, returncode, expected): + from types import SimpleNamespace + import opencode_ci_probe as probe + + monkeypatch.setenv("OPENDIRECTOR_CI_NATIVE_STACK", "1") + monkeypatch.setattr(probe.shutil, "which", lambda name: name) + + def run(command, **kwargs): + assert command[:6] == ["sudo", "-n", "timeout", "--signal=KILL", "3s", "gdb"] + assert kwargs["timeout"] == 5 + assert command[-4:] == ["-ex", "bt 20", "-ex", "detach"] + assert "set auto-load off" in command + return SimpleNamespace(returncode=returncode, stdout=( + "#0 0x123abc in JSC::Heap::collect () at /private/canary:42\n" + "#1 private_canary (credential=private_canary)\n#2 ?? ()\n" + "#99 JSC::ShouldNotExport ()\n"), stderr="private_canary") + + monkeypatch.setattr(probe.subprocess, "run", run) + probe.native_stack_probe(tmp_path, (123456,)) + save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + raw = (tmp_path / "reports/stack.json").read_text() + assert all(value not in raw for value in ("private", "123abc", "123456", "ShouldNotExport")) + events = json.loads(raw)["events"] + assert events[0]["status"] == expected + assert [event["symbol"] for event in events[1:]] == ["JSC::Heap::collect", "unknown", "unknown"] + + +@pytest.mark.cpu +@pytest.mark.merge +def test_native_stack_probe_is_opt_in_and_handles_missing_tools_and_timeout(tmp_path, monkeypatch): + import opencode_ci_probe as probe + + monkeypatch.delenv("OPENDIRECTOR_CI_NATIVE_STACK", raising=False) + probe.native_stack_probe(tmp_path, (123,)) + assert not (tmp_path / "process-boundaries.log").exists() + monkeypatch.setenv("OPENDIRECTOR_CI_NATIVE_STACK", "1") + monkeypatch.setattr(probe.shutil, "which", lambda name: None) + probe.native_stack_probe(tmp_path, (123,)) + monkeypatch.setattr(probe.shutil, "which", lambda name: name) + + def timeout(*args, **kwargs): + raise subprocess.TimeoutExpired("gdb", 5, output="private_canary") + + monkeypatch.setattr(probe.subprocess, "run", timeout) + probe.native_stack_probe(tmp_path, (123,)) + save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + raw = (tmp_path / "reports/stack.json").read_text() + assert "private_canary" not in raw + assert [event["status"] for event in json.loads(raw)["events"]] == ["missing", "timeout"] + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux" or not all(shutil.which(name) for name in ("gdb", "sudo", "timeout")), + reason="Linux GDB attach tools") +def test_native_stack_probe_detaches_from_live_process(tmp_path, monkeypatch): + from opencode_ci_probe import native_stack_probe + + monkeypatch.setenv("OPENDIRECTOR_CI_NATIVE_STACK", "1") + with subprocess.Popen([sys.executable, "-c", "import time; time.sleep(20)"]) as child: + try: + native_stack_probe(tmp_path, (child.pid,)) + assert child.poll() is None + finally: + child.terminate() + child.wait(timeout=5) + save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + events = json.loads((tmp_path / "reports/stack.json").read_text())["events"] + assert events[0]["status"] == "ok" and len(events) <= 21 From 7229f60c7aaf76ecef19a591f97860b876a463e4 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 21:54:31 +0800 Subject: [PATCH 15/25] [ci] Compare JIT modes in OpenCode diagnostic job ## summary Replace the completed snapshot experiment with same-runner JIT on/off/off/on trials. Verify each runtime option, hold snapshots on, and upload existing integration traces early. Refs: #162 --- .github/workflows/release-checks.yml | 36 +++++++++++++++++++++------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index e9a4c5ab1..89df03afc 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -131,20 +131,38 @@ jobs: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - - name: Compare OpenCode snapshots on diagnostic PR + - name: Compare OpenCode JIT on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} timeout-minutes: 6 continue-on-error: true env: OPENDIRECTOR_REAL_CLI: '1' + OPENDIRECTOR_CI_SNAPSHOT: 'on' + OPENCODE_DISABLE_MODELS_FETCH: '1' run: | - evidence="$RUNNER_TEMP/opencode-snapshot-evidence" + evidence="$RUNNER_TEMP/opencode-jit-evidence" mkdir -p "$evidence" - printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\n' > "$evidence/results.tsv" + if [ -d test-results/opencode-diagnostics ]; then + cp -R test-results/opencode-diagnostics "$evidence/integrated" + fi + binary="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" + printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\tuseJIT\n' > "$evidence/results.tsv" for trial in 01-on 02-off 03-off 04-on; do - export OPENDIRECTOR_CI_SNAPSHOT="${trial#*-}" + expected=true + export BUN_JSC_useJIT=1 + if [[ "$trial" == *-off ]]; then + expected=false + export BUN_JSC_useJIT=0 + fi + options="$RUNNER_TEMP/opencode-jit-options-$trial" + BUN_JSC_dumpOptions=2 "$binary" debug paths > /dev/null 2> "$options" + resolved="$(awk -F= '/^[[:space:]]*useJIT=/ { split($2, value, " "); print value[1]; exit }' "$options")" + if [[ "$resolved" != "$expected" ]]; then + echo '::error::OpenCode JIT option verification failed' + exit 1 + fi export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" - basetemp="$RUNNER_TEMP/opencode-snapshot-$trial" + basetemp="$RUNNER_TEMP/opencode-jit-$trial" started=$SECONDS result=0 timeout --kill-after=5s 85s python -m pytest -q --tb=short \ @@ -153,18 +171,18 @@ jobs: elapsed=$((SECONDS - started)) counts="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | awk '$2 == "git.start" { git++; if ($4 == "write-tree") snapshots++ } END { printf "%d\t%d", git, snapshots }')" - printf '%s\t%s\t%s\t%s\n' "$trial" "$result" "$elapsed" "$counts" | tee -a "$evidence/results.tsv" + printf '%s\t%s\t%s\t%s\t%s\n' "$trial" "$result" "$elapsed" "$counts" "$resolved" | tee -a "$evidence/results.tsv" if [[ "$result" == 124 || "$result" == 137 ]]; then exit "$result" fi done - - name: Upload OpenCode snapshot comparison + - name: Upload OpenCode JIT comparison if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: opencode-snapshot-comparison-${{ github.run_attempt }} - path: ${{ runner.temp }}/opencode-snapshot-evidence/ + name: opencode-jit-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-jit-evidence/ retention-days: 14 if-no-files-found: warn - name: Compare Node and Bun child processes on diagnostic PR From ab6c9b819efa13ef405e6bd82380353856105773 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Wed, 2 Dec 2026 23:39:15 +0800 Subject: [PATCH 16/25] [ci] Compare monotonic clock sources in OpenCode ## summary Route only the tracked CLI through a diagnostic clock shim. Compare libc and direct syscall readings, report bounded positive discrepancies, and validate routes with a separate synthetic C driver before same-runner trials. Refs: #162 --- .github/workflows/release-checks.yml | 46 +++++++-------- docs/development/validation.md | 4 ++ scripts/ci/opencode_clock_probe.c | 66 ++++++++++++++++++++++ tests/opencode_ci_probe.py | 4 +- tests/opencode_ci_trace.py | 13 +++++ tests/test_native_runtime.py | 2 + tests/test_opencode_clock_probe.py | 83 ++++++++++++++++++++++++++++ 7 files changed, 194 insertions(+), 24 deletions(-) create mode 100644 scripts/ci/opencode_clock_probe.c create mode 100644 tests/test_opencode_clock_probe.py diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 89df03afc..298484b7b 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -131,7 +131,7 @@ jobs: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - - name: Compare OpenCode JIT on diagnostic PR + - name: Compare OpenCode monotonic clocks on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} timeout-minutes: 6 continue-on-error: true @@ -140,29 +140,21 @@ jobs: OPENDIRECTOR_CI_SNAPSHOT: 'on' OPENCODE_DISABLE_MODELS_FETCH: '1' run: | - evidence="$RUNNER_TEMP/opencode-jit-evidence" + evidence="$RUNNER_TEMP/opencode-clock-evidence" mkdir -p "$evidence" if [ -d test-results/opencode-diagnostics ]; then cp -R test-results/opencode-diagnostics "$evidence/integrated" fi - binary="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" - printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\tuseJIT\n' > "$evidence/results.tsv" - for trial in 01-on 02-off 03-off 04-on; do - expected=true - export BUN_JSC_useJIT=1 - if [[ "$trial" == *-off ]]; then - expected=false - export BUN_JSC_useJIT=0 - fi - options="$RUNNER_TEMP/opencode-jit-options-$trial" - BUN_JSC_dumpOptions=2 "$binary" debug paths > /dev/null 2> "$options" - resolved="$(awk -F= '/^[[:space:]]*useJIT=/ { split($2, value, " "); print value[1]; exit }' "$options")" - if [[ "$resolved" != "$expected" ]]; then - echo '::error::OpenCode JIT option verification failed' - exit 1 - fi + python -m pytest tests/test_opencode_clock_probe.py --noconftest -q + export OPENDIRECTOR_CI_CLOCK_SHIM="$RUNNER_TEMP/opencode-clock-probe.so" + gcc -std=c11 -Wall -Wextra -Werror -O2 -shared -fPIC \ + scripts/ci/opencode_clock_probe.c -ldl -o "$OPENDIRECTOR_CI_CLOCK_SHIM" + export BUN_JSC_useJIT=1 + printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\tclockSource\taheadCount\tmaxAheadMs\n' > "$evidence/results.tsv" + for trial in 01-libc 02-syscall 03-syscall 04-libc; do + export OD_CI_CLOCK_MODE="${trial#*-}" export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" - basetemp="$RUNNER_TEMP/opencode-jit-$trial" + basetemp="$RUNNER_TEMP/opencode-clock-$trial" started=$SECONDS result=0 timeout --kill-after=5s 85s python -m pytest -q --tb=short \ @@ -171,18 +163,26 @@ jobs: elapsed=$((SECONDS - started)) counts="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | awk '$2 == "git.start" { git++; if ($4 == "write-tree") snapshots++ } END { printf "%d\t%d", git, snapshots }')" - printf '%s\t%s\t%s\t%s\t%s\n' "$trial" "$result" "$elapsed" "$counts" "$resolved" | tee -a "$evidence/results.tsv" + resolved="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | + awk '$2 == "opencode.clock" { print $4 }' | sort -u)" + ahead="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | + awk '$2 == "opencode.clockAhead" { n++; if ($4 > max) max=$4 } END { printf "%d\t%d", n, max }')" + if [[ "$resolved" != "$OD_CI_CLOCK_MODE" ]]; then + echo '::error::OpenCode clock route verification failed' + if [[ "$result" == 0 ]]; then result=1; fi + fi + printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$trial" "$result" "$elapsed" "$counts" "$resolved" "$ahead" | tee -a "$evidence/results.tsv" if [[ "$result" == 124 || "$result" == 137 ]]; then exit "$result" fi done - - name: Upload OpenCode JIT comparison + - name: Upload OpenCode clock comparison if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: opencode-jit-comparison-${{ github.run_attempt }} - path: ${{ runner.temp }}/opencode-jit-evidence/ + name: opencode-clock-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-clock-evidence/ retention-days: 14 if-no-files-found: warn - name: Compare Node and Bun child processes on diagnostic PR diff --git a/docs/development/validation.md b/docs/development/validation.md index d4146612a..a420526b5 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -193,6 +193,10 @@ Before cleanup, `opencode.cpu` records main-thread and whole-process CPU tick de Only when the diagnostic PR explicitly enables `OPENDIRECTOR_CI_NATIVE_STACK=1`, the watchdog samples the last CLI's main native thread with GDB before cleanup. Auto-loading and symbol downloads are disabled; an independent three-second hard timeout bounds GDB, with a five-second caller timeout. Normal sampling detaches. Reports retain at most 20 frame depths and restricted runtime symbols, mapping other symbols to unknown; raw GDB output, addresses, arguments, paths and memory are not saved. Attaching briefly pauses the process. Native frames are not a JavaScript stack, and missing symbols do not establish that corresponding code was absent. +单调时钟诊断仅通过测试夹具为 CLI 设置 `OPENDIRECTOR_CI_CLOCK_SHIM`。两种模式都比较 libc 与随后直接系统调用的 `CLOCK_MONOTONIC` 读数;`libc` 返回原值,`syscall` 返回系统调用的值。首次实际调用记录路径选择,最多记录 8 次 libc 比系统调用领先至少 10 毫秒的偏差。该包装会增加时钟调用开销;没有偏差记录不能排除漏采或其他运行时原因。已知未来读数的注入只发生在独立 C 驱动测试中,不用于 OpenCode 集成对照。 + +Monotonic clock diagnosis sets `OPENDIRECTOR_CI_CLOCK_SHIM` on the CLI through the test fixture only. Both modes compare libc's `CLOCK_MONOTONIC` reading with a subsequent direct syscall; `libc` returns the original value and `syscall` returns the kernel value. The first actual call records the route; at most eight libc readings at least 10 ms ahead are recorded. Wrapping adds clock-call overhead. No recorded discrepancy does not exclude missed anomalies or other runtime causes. A known future reading is injected only in the standalone C driver test, never in the OpenCode integration comparison. + ```sh python -m pytest tests -q -ra --durations=50 --junitxml=test-results/python.xml --ci-profile=test-results/python.json ``` diff --git a/scripts/ci/opencode_clock_probe.c b/scripts/ci/opencode_clock_probe.c new file mode 100644 index 000000000..230a1cb55 --- /dev/null +++ b/scripts/ci/opencode_clock_probe.c @@ -0,0 +1,66 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int (*next_clock)(clockid_t, struct timespec *); +static int use_syscall; +static atomic_int announced; +static atomic_int ahead_count; +static atomic_int initialized; + +__attribute__((constructor)) static void initialize(void) { + next_clock = dlsym(RTLD_NEXT, "clock_gettime"); + const char *mode = getenv("OD_CI_CLOCK_MODE"); + use_syscall = mode && strcmp(mode, "syscall") == 0; + const char *target = getenv("OD_CI_CLOCK_TARGET"); + char executable[PATH_MAX]; + ssize_t length = readlink("/proc/self/exe", executable, sizeof(executable) - 1); + if (length >= 0) executable[length] = '\0'; + atomic_store(&initialized, target && length >= 0 && strcmp(target, executable) == 0 ? 1 : 2); +} + +static void record(const char *event, const char *detail) { + const char *path = getenv("OD_CI_BOUNDARIES"); + if (!path) return; + struct timespec wall; + if (syscall(SYS_clock_gettime, CLOCK_REALTIME, &wall) != 0) return; + int fd = open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600); + if (fd < 0) return; + char line[160]; + int length = snprintf(line, sizeof(line), "%lld.%09ld %s %ld %s\n", + (long long)wall.tv_sec, wall.tv_nsec, event, (long)getpid(), detail); + if (length > 0 && (size_t)length < sizeof(line)) (void)write(fd, line, (size_t)length); + close(fd); +} + +int clock_gettime(clockid_t id, struct timespec *value) { + if (!atomic_load(&initialized)) return (int)syscall(SYS_clock_gettime, id, value); + int result = next_clock ? next_clock(id, value) : (int)syscall(SYS_clock_gettime, id, value); + if (atomic_load(&initialized) != 1) return result; + if (id != CLOCK_MONOTONIC || result != 0) return result; + int saved_errno = errno; + struct timespec kernel; + if (syscall(SYS_clock_gettime, id, &kernel) == 0) { + long long ahead_ms = ((long long)value->tv_sec - kernel.tv_sec) * 1000 + + (value->tv_nsec - kernel.tv_nsec) / 1000000; + if (ahead_ms >= 10 && atomic_fetch_add(&ahead_count, 1) < 8) { + char detail[32]; + snprintf(detail, sizeof(detail), "%lld", ahead_ms); + record("opencode.clockAhead", detail); + } + if (use_syscall) *value = kernel; + if (atomic_exchange(&announced, 1) == 0) + record("opencode.clock", use_syscall ? "syscall" : "libc"); + } + errno = saved_errno; + return result; +} diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py index 8d8fa55ad..1cb73d286 100644 --- a/tests/opencode_ci_probe.py +++ b/tests/opencode_ci_probe.py @@ -80,8 +80,10 @@ def process_environment(root: Path, env: dict[str, str]): exit "$rc" """, encoding="utf-8") git_probe.chmod(0o700) + clock_shim = env.get("OPENDIRECTOR_CI_CLOCK_SHIM") + clock_env = {"LD_PRELOAD": clock_shim + (":" + env["LD_PRELOAD"] if env.get("LD_PRELOAD") else "")} if clock_shim else {} return { - **env, "BASH_ENV": str(startup), "OD_CI_REAL_GIT": git, + **env, **clock_env, "BASH_ENV": str(startup), "OD_CI_REAL_GIT": git, "OD_CI_BOUNDARIES": str(root / "process-boundaries.log"), "OD_CI_BASH_PIPES": str(root / "bash-pipes.log"), "PATH": str(probe) + os.pathsep + env.get("PATH", os.defpath), diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index c34cd4225..17c21260b 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -21,6 +21,7 @@ "bash.start", "bash.exit", "git.start", "git.exit", "gateway.start", "gateway.return", "bash.watchdog", "opencode.watchdog", "git.watchdog", "opencode.cpu", "opencode.stack", "opencode.frame", + "opencode.clock", "opencode.clockAhead", } PROCESS_STATES = {"R", "S", "D", "Z", "T", "t", "X", "I", "gone", "unknown"} PIPE_COUNTS = ("stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters") @@ -119,6 +120,18 @@ def _boundary_event(line, identities): return None source, phase = event.split(".") result = {"source": source, "event": event, "at": at} + if event == "opencode.clock": + if len(details) != 1 or details[0] not in {"libc", "syscall"}: + return None + result["clockSource"] = details[0] + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result + if event == "opencode.clockAhead": + if len(details) != 1 or not re.fullmatch(r"[0-9]{1,12}", details[0]): + return None + result["aheadMs"] = int(details[0]) + result["span"] = identities.setdefault((source, key), len(identities) + 1) + return result if event == "opencode.stack": if len(details) != 1 or details[0] not in {"ok", "empty", "error", "timeout", "missing"}: return None diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index a515bd640..e65e34b96 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -405,6 +405,8 @@ async def tracked_spawn(*args, **kwargs): probe_cli = probe_enabled and args[0] == native.executable('default') and args[1] == 'run' if probe_cli: env = process_environment(tmp_path, kwargs['env']) + if env.get('OPENDIRECTOR_CI_CLOCK_SHIM'): + env['OD_CI_CLOCK_TARGET'] = str(Path(args[0]).resolve()) snapshot = os.environ.get('OPENDIRECTOR_CI_SNAPSHOT') if snapshot in {'on', 'off'}: config = json.loads(env['OPENCODE_CONFIG_CONTENT']) diff --git a/tests/test_opencode_clock_probe.py b/tests/test_opencode_clock_probe.py new file mode 100644 index 000000000..f073b8b67 --- /dev/null +++ b/tests/test_opencode_clock_probe.py @@ -0,0 +1,83 @@ +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from opencode_ci_trace import save_failure_trace + + +@pytest.mark.cpu +@pytest.mark.merge +@pytest.mark.skipif(sys.platform != "linux" or not shutil.which("gcc"), reason="Linux clock interposition") +def test_clock_probe_routes_known_future_read_and_exports_only_counters(tmp_path): + source = Path(__file__).resolve().parents[1] / "scripts/ci/opencode_clock_probe.c" + shim = tmp_path / "clock.so" + subprocess.run(["gcc", "-std=c11", "-Wall", "-Wextra", "-Werror", "-O2", "-shared", "-fPIC", + str(source), "-ldl", "-o", str(shim)], check=True) + fake = tmp_path / "fake.c" + fake.write_text("""#define _GNU_SOURCE +#include +#include +#include +int clock_gettime(clockid_t id, struct timespec *value) { + int result = (int)syscall(SYS_clock_gettime, id, value); + if (result == 0 && id == CLOCK_MONOTONIC) value->tv_sec += 2; + return result; +} +""") + fake_shim = tmp_path / "fake.so" + subprocess.run(["gcc", "-shared", "-fPIC", str(fake), "-o", str(fake_shim)], check=True) + driver = tmp_path / "driver.c" + driver.write_text("""#define _GNU_SOURCE +#include +#include +#include +#include +int main(void) { + struct timespec observed, kernel; + if (clock_gettime(CLOCK_MONOTONIC, &observed) != 0) return 2; + if (syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &kernel) != 0) return 3; + printf("%lld\\n", ((long long)observed.tv_sec - kernel.tv_sec) * 1000 + + (observed.tv_nsec - kernel.tv_nsec) / 1000000); + return 0; +} +""") + binary = tmp_path / "driver" + subprocess.run(["gcc", str(driver), "-o", str(binary)], check=True) + for mode in ("libc", "syscall"): + root = tmp_path / mode + root.mkdir() + result = subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=5, + env={**os.environ, "LD_PRELOAD": f"{shim}:{fake_shim}", "OD_CI_CLOCK_MODE": mode, + "OD_CI_CLOCK_TARGET": str(binary.resolve()), + "OD_CI_BOUNDARIES": str(root / "process-boundaries.log")}) + ahead = int(result.stdout) + assert ahead >= 1900 if mode == "libc" else abs(ahead) < 100 + save_failure_trace(root, root / "reports", "clock", "probe") + events = json.loads((root / "reports/clock.json").read_text())["events"] + assert [event["event"] for event in events] == ["opencode.clockAhead", "opencode.clock"] + assert events[0]["aheadMs"] >= 1900 + assert events[1]["clockSource"] == mode + assert str(tmp_path) not in json.dumps(events) + bypass = tmp_path / "bypass.log" + result = subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=5, + env={**os.environ, "LD_PRELOAD": f"{shim}:{fake_shim}", "OD_CI_CLOCK_MODE": "syscall", + "OD_CI_CLOCK_TARGET": str(tmp_path / "other"), "OD_CI_BOUNDARIES": str(bypass)}) + assert int(result.stdout) >= 1900 and not bypass.exists() + + +@pytest.mark.cpu +@pytest.mark.merge +def test_clock_events_drop_raw_identity_and_invalid_values(tmp_path): + (tmp_path / "process-boundaries.log").write_text( + "10 opencode.clock 987654 libc\n11 opencode.clockAhead 987654 2500\n" + "12 opencode.clock 987654 private_canary\n13 opencode.clockAhead 987654 private_canary\n") + save_failure_trace(tmp_path, tmp_path / "reports", "clock", "probe") + raw = (tmp_path / "reports/clock.json").read_text() + assert "987654" not in raw and "private_canary" not in raw + events = json.loads(raw)["events"] + assert len(events) == 2 and events[0]["span"] == events[1]["span"] From 09aa713fdef9bc63f63000bb98a7a67aad43840c Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 00:11:16 +0800 Subject: [PATCH 17/25] [ci] Handle clock probe writes and expose preflight state ## summary Check diagnostic write results under fortified GCC and retain strict compiler flags. Export sanitized preflight stages and initialize comparison results before the gate. Refs: #162 --- .github/workflows/release-checks.yml | 13 ++++++++++--- scripts/ci/opencode_clock_probe.c | 8 +++++++- tests/test_opencode_clock_probe.py | 19 ++++++++++++++++++- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 298484b7b..14a31dbb0 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -145,12 +145,19 @@ jobs: if [ -d test-results/opencode-diagnostics ]; then cp -R test-results/opencode-diagnostics "$evidence/integrated" fi - python -m pytest tests/test_opencode_clock_probe.py --noconftest -q + printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\tclockSource\taheadCount\tmaxAheadMs\n' > "$evidence/results.tsv" + printf 'stage\texit_code\n' > "$evidence/preflight.tsv" + status=0 + OPENDIRECTOR_CI_CLOCK_PREFLIGHT_REPORT="$evidence/preflight.json" \ + python -m pytest tests/test_opencode_clock_probe.py --noconftest -q || status=$? + printf 'clock_tests\t%s\n' "$status" >> "$evidence/preflight.tsv" + if [[ "$status" != 0 ]]; then exit "$status"; fi export OPENDIRECTOR_CI_CLOCK_SHIM="$RUNNER_TEMP/opencode-clock-probe.so" gcc -std=c11 -Wall -Wextra -Werror -O2 -shared -fPIC \ - scripts/ci/opencode_clock_probe.c -ldl -o "$OPENDIRECTOR_CI_CLOCK_SHIM" + scripts/ci/opencode_clock_probe.c -ldl -o "$OPENDIRECTOR_CI_CLOCK_SHIM" || status=$? + printf 'clock_compile\t%s\n' "$status" >> "$evidence/preflight.tsv" + if [[ "$status" != 0 ]]; then exit "$status"; fi export BUN_JSC_useJIT=1 - printf 'trial\texit_code\telapsed_seconds\tgit_starts\twrite_tree_starts\tclockSource\taheadCount\tmaxAheadMs\n' > "$evidence/results.tsv" for trial in 01-libc 02-syscall 03-syscall 04-libc; do export OD_CI_CLOCK_MODE="${trial#*-}" export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" diff --git a/scripts/ci/opencode_clock_probe.c b/scripts/ci/opencode_clock_probe.c index 230a1cb55..844f460f1 100644 --- a/scripts/ci/opencode_clock_probe.c +++ b/scripts/ci/opencode_clock_probe.c @@ -38,7 +38,13 @@ static void record(const char *event, const char *detail) { char line[160]; int length = snprintf(line, sizeof(line), "%lld.%09ld %s %ld %s\n", (long long)wall.tv_sec, wall.tv_nsec, event, (long)getpid(), detail); - if (length > 0 && (size_t)length < sizeof(line)) (void)write(fd, line, (size_t)length); + if (length > 0 && (size_t)length < sizeof(line)) { + ssize_t written = write(fd, line, (size_t)length); + if (written != length) { + close(fd); + return; + } + } close(fd); } diff --git a/tests/test_opencode_clock_probe.py b/tests/test_opencode_clock_probe.py index f073b8b67..a8baa0ba5 100644 --- a/tests/test_opencode_clock_probe.py +++ b/tests/test_opencode_clock_probe.py @@ -14,8 +14,14 @@ @pytest.mark.merge @pytest.mark.skipif(sys.platform != "linux" or not shutil.which("gcc"), reason="Linux clock interposition") def test_clock_probe_routes_known_future_read_and_exports_only_counters(tmp_path): + def progress(stage, **facts): + report = os.environ.get("OPENDIRECTOR_CI_CLOCK_PREFLIGHT_REPORT") + if report: + Path(report).write_text(json.dumps({"stage": stage, **facts}) + "\n", encoding="utf-8") + source = Path(__file__).resolve().parents[1] / "scripts/ci/opencode_clock_probe.c" shim = tmp_path / "clock.so" + progress("compile_shim") subprocess.run(["gcc", "-std=c11", "-Wall", "-Wextra", "-Werror", "-O2", "-shared", "-fPIC", str(source), "-ldl", "-o", str(shim)], check=True) fake = tmp_path / "fake.c" @@ -30,6 +36,7 @@ def test_clock_probe_routes_known_future_read_and_exports_only_counters(tmp_path } """) fake_shim = tmp_path / "fake.so" + progress("compile_fake") subprocess.run(["gcc", "-shared", "-fPIC", str(fake), "-o", str(fake_shim)], check=True) driver = tmp_path / "driver.c" driver.write_text("""#define _GNU_SOURCE @@ -47,27 +54,37 @@ def test_clock_probe_routes_known_future_read_and_exports_only_counters(tmp_path } """) binary = tmp_path / "driver" + progress("compile_driver") subprocess.run(["gcc", str(driver), "-o", str(binary)], check=True) + cases = [] for mode in ("libc", "syscall"): root = tmp_path / mode root.mkdir() + progress(mode + "_driver") result = subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=5, env={**os.environ, "LD_PRELOAD": f"{shim}:{fake_shim}", "OD_CI_CLOCK_MODE": mode, "OD_CI_CLOCK_TARGET": str(binary.resolve()), "OD_CI_BOUNDARIES": str(root / "process-boundaries.log")}) ahead = int(result.stdout) + progress(mode + "_value", aheadMs=ahead) assert ahead >= 1900 if mode == "libc" else abs(ahead) < 100 save_failure_trace(root, root / "reports", "clock", "probe") events = json.loads((root / "reports/clock.json").read_text())["events"] + progress(mode + "_events", events=events) assert [event["event"] for event in events] == ["opencode.clockAhead", "opencode.clock"] assert events[0]["aheadMs"] >= 1900 assert events[1]["clockSource"] == mode assert str(tmp_path) not in json.dumps(events) + cases.append({"mode": mode, "aheadMs": ahead, "events": events}) bypass = tmp_path / "bypass.log" + progress("bypass") result = subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=5, env={**os.environ, "LD_PRELOAD": f"{shim}:{fake_shim}", "OD_CI_CLOCK_MODE": "syscall", "OD_CI_CLOCK_TARGET": str(tmp_path / "other"), "OD_CI_BOUNDARIES": str(bypass)}) - assert int(result.stdout) >= 1900 and not bypass.exists() + bypass_ahead = int(result.stdout) + progress("bypass_value", aheadMs=bypass_ahead) + assert bypass_ahead >= 1900 and not bypass.exists() + progress("passed", cases=cases, bypassAheadMs=bypass_ahead) @pytest.mark.cpu From 53eda069208c85f826db405f1a08827032913b62 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 00:31:25 +0800 Subject: [PATCH 18/25] [ci] Isolate clock preflight and retain interrupted evidence ## summary Run the diagnostic Linux C fixture in a bounded standalone job and retain sanitized artifacts even when the comparison step is interrupted. Preserve the existing required check dependencies. Refs: #162 --- .github/workflows/release-checks.yml | 34 +++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 14a31dbb0..65983a0a0 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -61,6 +61,38 @@ jobs: MERGE_GROUP_BASE_SHA: ${{ github.event.merge_group.base_sha }} run: python scripts/ci/select_checks.py + clock-preflight: + needs: static + if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && needs.static.result == 'success' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + continue-on-error: true + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: '3.12' + - name: Install clock probe test runner + run: python -m pip install pytest==9.1.1 + - name: Verify Linux clock interposition + env: + OPENDIRECTOR_CI_CLOCK_PREFLIGHT_REPORT: ${{ runner.temp }}/opencode-clock-preflight/preflight.json + run: | + mkdir -p "$RUNNER_TEMP/opencode-clock-preflight" + gcc --version | head -1 + status=0 + timeout --kill-after=5s 60s python -m pytest tests/test_opencode_clock_probe.py --noconftest -q || status=$? + printf 'exit_code\t%s\n' "$status" > "$RUNNER_TEMP/opencode-clock-preflight/status.tsv" + exit "$status" + - name: Upload clock preflight evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opencode-clock-preflight-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-clock-preflight/ + retention-days: 14 + if-no-files-found: warn + python: needs: static if: ${{ !cancelled() && ((needs.static.result == 'success' && needs.static.outputs.run-heavy != 'false') || (!inputs.static-checks && needs.static.result == 'skipped')) }} @@ -184,7 +216,7 @@ jobs: fi done - name: Upload OpenCode clock comparison - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} + if: ${{ always() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} continue-on-error: true uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: From 6ca06c9c6d86a4e32957e48da3d523a3ce784fba Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 09:02:27 +0800 Subject: [PATCH 19/25] [ci] Observe monotonic clock in the bundled regression --- .github/workflows/release-checks.yml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index f82a3d77d..f9bc66d3e 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -157,12 +157,23 @@ jobs: python scripts/ci/opencode_minimal_probe.py --binary "$binary" \ --repeats 2 --timeout 60 --fixture-shape --skill-first \ --report test-results/opencode-diagnostics/standalone-control.json + - id: clock-observer + name: Build OpenCode clock observer on diagnostic PR + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} + timeout-minutes: 1 + continue-on-error: true + run: | + shim="$RUNNER_TEMP/opencode-clock-probe.so" + gcc -std=c11 -Wall -Wextra -Werror -O2 -shared -fPIC scripts/ci/opencode_clock_probe.c -ldl -o "$shim" + printf 'path=%s\n' "$shim" >> "$GITHUB_OUTPUT" - name: Bundled OpenCode model gateway regression if: always() && steps.install.outcome == 'success' timeout-minutes: 5 env: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics + OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} + OD_CI_CLOCK_MODE: libc run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - name: Compare OpenCode monotonic clocks on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} @@ -171,6 +182,7 @@ jobs: env: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_SNAPSHOT: 'on' + OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} OPENCODE_DISABLE_MODELS_FETCH: '1' run: | evidence="$RUNNER_TEMP/opencode-clock-evidence" @@ -185,9 +197,7 @@ jobs: python -m pytest tests/test_opencode_clock_probe.py --noconftest -q || status=$? printf 'clock_tests\t%s\n' "$status" >> "$evidence/preflight.tsv" if [[ "$status" != 0 ]]; then exit "$status"; fi - export OPENDIRECTOR_CI_CLOCK_SHIM="$RUNNER_TEMP/opencode-clock-probe.so" - gcc -std=c11 -Wall -Wextra -Werror -O2 -shared -fPIC \ - scripts/ci/opencode_clock_probe.c -ldl -o "$OPENDIRECTOR_CI_CLOCK_SHIM" || status=$? + [[ -f "$OPENDIRECTOR_CI_CLOCK_SHIM" ]] || status=$? printf 'clock_compile\t%s\n' "$status" >> "$evidence/preflight.tsv" if [[ "$status" != 0 ]]; then exit "$status"; fi export BUN_JSC_useJIT=1 From 08aa0c1f05c972090f0e9fca4d90e2a791c1be65 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 09:32:20 +0800 Subject: [PATCH 20/25] [ci] Compare snapshot completion with libc observation --- .github/workflows/release-checks.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index f9bc66d3e..596829c42 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -175,13 +175,13 @@ jobs: OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} OD_CI_CLOCK_MODE: libc run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json - - name: Compare OpenCode monotonic clocks on diagnostic PR + - name: Compare OpenCode snapshots with libc observation on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} timeout-minutes: 6 continue-on-error: true env: OPENDIRECTOR_REAL_CLI: '1' - OPENDIRECTOR_CI_SNAPSHOT: 'on' + OD_CI_CLOCK_MODE: libc OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} OPENCODE_DISABLE_MODELS_FETCH: '1' run: | @@ -201,8 +201,8 @@ jobs: printf 'clock_compile\t%s\n' "$status" >> "$evidence/preflight.tsv" if [[ "$status" != 0 ]]; then exit "$status"; fi export BUN_JSC_useJIT=1 - for trial in 01-libc 02-syscall 03-syscall 04-libc; do - export OD_CI_CLOCK_MODE="${trial#*-}" + for trial in 01-on 02-off 03-off 04-on; do + export OPENDIRECTOR_CI_SNAPSHOT="${trial#*-}" export OPENDIRECTOR_CI_TRACE_DIR="$evidence/$trial" basetemp="$RUNNER_TEMP/opencode-clock-$trial" started=$SECONDS @@ -217,7 +217,7 @@ jobs: awk '$2 == "opencode.clock" { print $4 }' | sort -u)" ahead="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | awk '$2 == "opencode.clockAhead" { n++; if ($4 > max) max=$4 } END { printf "%d\t%d", n, max }')" - if [[ "$resolved" != "$OD_CI_CLOCK_MODE" ]]; then + if [[ "$resolved" != libc ]]; then echo '::error::OpenCode clock route verification failed' if [[ "$result" == 0 ]]; then result=1; fi fi From 17fb58907dd515acb18fac5915a9d63273c9e241 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 10:31:45 +0800 Subject: [PATCH 21/25] [ci] Compare snapshots in the thinking direct-reply case --- .github/workflows/release-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 596829c42..052eb3bcd 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -209,7 +209,7 @@ jobs: result=0 timeout --kill-after=5s 85s python -m pytest -q --tb=short \ --basetemp "$basetemp" \ - 'tests/test_agent_visual_gate.py::test_real_opencode_native_visual_input[text-only-model]' || result=$? + 'tests/test_native_runtime.py::test_real_opencode_default_hello_saves_direct_reply[thinking]' || result=$? elapsed=$((SECONDS - started)) counts="$(find "$basetemp" -name process-boundaries.log -type f -exec cat {} + | awk '$2 == "git.start" { git++; if ($4 == "write-tree") snapshots++ } END { printf "%d\t%d", git, snapshots }')" From 67a30d3628a7226c742ecb302f685f111a4854b6 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 11:14:59 +0800 Subject: [PATCH 22/25] Compare bundled and stable OpenCode on one CI runner --- .github/workflows/release-checks.yml | 48 ++++++++++++++++++++++------ scripts/ci/opencode_minimal_probe.py | 41 ++++++++++++++++-------- 2 files changed, 65 insertions(+), 24 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 052eb3bcd..da72740ab 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -144,19 +144,47 @@ jobs: rg --version gdb --version | head -1 echo 'OPENDIRECTOR_CI_NATIVE_STACK=1' >> "$GITHUB_ENV" - - name: Standalone OpenCode control on diagnostic PR + - name: Compare bundled and stable OpenCode on diagnostic PR if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' - timeout-minutes: 6 + timeout-minutes: 14 continue-on-error: true run: | - binary="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" - if [ -z "$binary" ]; then - echo "::error::Bundled OpenCode is missing" - exit 1 - fi - python scripts/ci/opencode_minimal_probe.py --binary "$binary" \ - --repeats 2 --timeout 60 --fixture-shape --skill-first \ - --report test-results/opencode-diagnostics/standalone-control.json + output="$RUNNER_TEMP/opencode-version-comparison" + prefix="$RUNNER_TEMP/opencode-stable" + mkdir -p "$output" + bundled="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" + test -x "$bundled" + "$bundled" --version | tee "$output/bundled-version.txt" + npm install --prefix "$prefix" --no-audit --no-fund --ignore-scripts --no-package-lock @opencode/cli-linux-x64@2.4.4 + stable="$prefix/node_modules/@opencode/cli-linux-x64/bin/opencode" + "$stable" --version | tee "$output/stable-version.txt" + index=0 + failed=0 + printf 'case\tlane\texit\n' > "$output/results.tsv" + for lane in bundled stable stable bundled; do + index=$((index + 1)) + binary="$bundled" + options=() + if [ "$lane" = stable ]; then + binary="$stable" + options=(--cli-v2) + fi + status=0 + python scripts/ci/opencode_minimal_probe.py --binary "$binary" "${options[@]}" \ + --repeats 1 --timeout 60 --fixture-shape --skill-first \ + --report "$output/$index-$lane.json" || status=$? + printf '%s\t%s\t%s\n' "$index" "$lane" "$status" >> "$output/results.tsv" + if [ "$status" -ne 0 ]; then + failed=1 + fi + done + exit "$failed" + - name: Upload OpenCode version comparison on diagnostic PR + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opencode-version-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-version-comparison/ - id: clock-observer name: Build OpenCode clock observer on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} diff --git a/scripts/ci/opencode_minimal_probe.py b/scripts/ci/opencode_minimal_probe.py index dd620342a..35165d33f 100644 --- a/scripts/ci/opencode_minimal_probe.py +++ b/scripts/ci/opencode_minimal_probe.py @@ -14,7 +14,7 @@ EVENT_TYPES = {"step_start", "step_finish", "text", "tool_use", "error"} -TOOL_NAMES = {"bash", "skill"} +TOOL_NAMES = {"bash", "shell", "skill"} TOOL_STATUSES = {"completed", "error", "running", "pending"} @@ -35,16 +35,18 @@ def do_POST(self): results = sum(item["role"] == "tool" for item in messages) self.server.events.append({ "event": "request", "tMs": received_ms - self.server.wall_started_ms, - "results": results, "bashEnabled": "bash" in tools, + "results": results, "bashEnabled": self.server.shell_tool in tools, }) - if results < self.server.tool_steps and "bash" in tools: + if results < self.server.tool_steps and self.server.shell_tool in tools: command = f"printf 'probe-{results + 1}\\n'" if self.server.fixture_shape: command = """sleep 1.7; printf '%s\\n' '{"status":"applied","changed":[]}'""" - name = "bash" - arguments = {"command": command, "description": "Run a local no-op diagnostic"} + name = self.server.shell_tool + arguments = {"command": command} + if name == "bash": + arguments["description"] = "Run a local no-op diagnostic" if self.server.skill_first and results == 0: - name, arguments = "skill", {"name": "ci-probe"} + name, arguments = "skill", {self.server.skill_identifier: "ci-probe"} delta = {"role": "assistant", "tool_calls": [{ "index": 0, "id": f"call-{results + 1}", "type": "function", "function": {"name": name, "arguments": json.dumps(arguments)}, @@ -78,7 +80,9 @@ def do_POST(self): }) -def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fixture_shape, skill_first): +def trial( + binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fixture_shape, skill_first, cli_v2, +): root = base / label work = root / "work" work.mkdir(parents=True) @@ -93,13 +97,15 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi server.events, server.tool_steps = [], tool_steps server.fixture_shape = fixture_shape server.skill_first = skill_first + server.shell_tool = "shell" if cli_v2 else "bash" + server.skill_identifier = "id" if cli_v2 else "name" thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() config = { "autoupdate": False, "default_agent": "probe", "agent": {"probe": {"mode": "primary", "prompt": "Follow the simulated task."}, "title": {"disable": True}}, - "permission": {"*": "deny", "bash": "allow"}, + "permission": {"*": "deny", server.shell_tool: "allow"}, "provider": {"mock": { "npm": "@ai-sdk/openai-compatible", "name": "Local mock", "options": {"baseURL": f"http://127.0.0.1:{server.server_port}/v1", "apiKey": "local-fixture-only"}, @@ -125,8 +131,12 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi """trap 'printf "%s exit:%s\\n" "$EPOCHREALTIME" "$?" >> "$PROBE_SHELL_EVENTS"' EXIT\n""" ) env.update(BASH_ENV=str(hook), PROBE_SHELL_EVENTS=str(root / "shell-events")) - command = [binary, "run", "--dir", str(work), "--pure", "--format", "json", - "--agent", "probe", "--model", "mock/probe-model"] + command = [binary, "run", "--format", "json", "--agent", "probe", "--model", "mock/probe-model"] + prompt = "Run the diagnostic." + if cli_v2: + command.extend(("--standalone", prompt)) + else: + command.extend(("--dir", str(work), "--pure")) monotonic_started = time.monotonic() server.wall_started_ms = time.time_ns() // 1_000_000 try: @@ -134,7 +144,7 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True) as process: try: - stdout, _ = process.communicate(input="Run the diagnostic.\n", timeout=timeout) + stdout, _ = process.communicate(input=None if cli_v2 else prompt + "\n", timeout=timeout) timed_out = False except subprocess.TimeoutExpired: timed_out = True @@ -159,6 +169,7 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi events.append({ "event": kind, "tMs": timestamp - server.wall_started_ms if type(timestamp) is int else None, "tool": tool if tool in TOOL_NAMES else None, "status": status if status in TOOL_STATUSES else None, + "snapshotPresent": bool(part.get("snapshot")), }) shell = root / "shell-events" shell_events = [] @@ -181,6 +192,7 @@ def trial(binary, base, label, tool_steps, timeout, git_worktree, trace_bash, fi def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", required=True) + parser.add_argument("--cli-v2", action="store_true", help="Use the OpenCode 2.x command and tool interfaces.") parser.add_argument("--repeats", type=int, default=3) parser.add_argument("--timeout", type=int, default=30) parser.add_argument("--fixture-shape", action="store_true") @@ -189,11 +201,12 @@ def main(): args = parser.parse_args() binary = str(Path(args.binary).resolve()) assert Path(binary).is_file() + shell_tool = "shell" if args.cli_v2 else "bash" reports = [] def run(label, tools, git_worktree, trace_bash, skill_first): report = trial(binary, base, label, len(tools), args.timeout, git_worktree, - trace_bash, args.fixture_shape, skill_first) + trace_bash, args.fixture_shape, skill_first, args.cli_v2) completed = [row["tool"] for row in report["events"] if row["event"] == "tool_use" and row["status"] == "completed"] requests = [row["results"] for row in report["model"] if row["event"] == "request"] @@ -201,7 +214,7 @@ def run(label, tools, git_worktree, trace_bash, skill_first): not report["timeout"] and report["exitCode"] == 0 and completed == tools and requests == list(range(len(tools) + 1)) and any(row["event"] == "text" for row in report["events"]) - and [row["event"] for row in report["shell"]] == ["start", "exit:0"] * tools.count("bash") + and [row["event"] for row in report["shell"]] == ["start", "exit:0"] * tools.count(shell_tool) ) reports.append(report) print(json.dumps(report), flush=True) @@ -209,7 +222,7 @@ def run(label, tools, git_worktree, trace_bash, skill_first): with tempfile.TemporaryDirectory(prefix="od-minimal-opencode-") as temporary: base = Path(temporary) run("text-control", [], False, False, False) - tools = ["skill", "bash"] if args.skill_first else ["bash", "bash"] + tools = ["skill", shell_tool] if args.skill_first else [shell_tool, shell_tool] for index in range(args.repeats): for git_worktree in (False, True): run(f"bash-{index + 1}-git-{int(git_worktree)}", tools, git_worktree, True, args.skill_first) From 153dfd33375bef31e19fc634e6c9068efd1011c8 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 11:18:18 +0800 Subject: [PATCH 23/25] Isolate the version comparison from required CI --- .github/workflows/release-checks.yml | 113 ++++++++++++++++++--------- 1 file changed, 75 insertions(+), 38 deletions(-) diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index da72740ab..c5518f6d2 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -93,6 +93,71 @@ jobs: retention-days: 14 if-no-files-found: warn + opencode-version-comparison: + needs: static + if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && needs.static.result == 'success' + runs-on: ubuntu-22.04 + timeout-minutes: 18 + continue-on-error: true + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: '3.12' + - name: Install ripgrep + run: | + sudo apt-get update + sudo apt-get install --yes ripgrep + rg --version + - name: Compare bundled and stable OpenCode on diagnostic PR + timeout-minutes: 16 + run: | + output="$RUNNER_TEMP/opencode-version-comparison" + mkdir -p "$output" + printf 'case\tlane\texit\n' > "$output/results.tsv" + bundled_url="$(python -c 'import json; print(json.load(open("package-lock.json"))["packages"]["node_modules/opencode-linux-x64"]["resolved"])')" + stable_url="https://registry.npmjs.org/@opencode/cli-linux-x64/-/cli-linux-x64-2.4.4.tgz" + fetch_binary() { + local url="$1" binary="$2" + curl --fail --silent --show-error --location --retry 2 --retry-max-time 90 --max-time 60 "$url" --output "$binary.tgz" + tar -xOzf "$binary.tgz" package/bin/opencode > "$binary" + chmod +x "$binary" + } + bundled="$RUNNER_TEMP/opencode-bundled" + stable="$RUNNER_TEMP/opencode-stable" + fetch_binary "$bundled_url" "$bundled" + fetch_binary "$stable_url" "$stable" + "$bundled" --version | tee "$output/bundled-version.txt" + "$stable" --version | tee "$output/stable-version.txt" + index=0 + failed=0 + for lane in bundled stable stable bundled; do + index=$((index + 1)) + binary="$bundled" + options=() + if [ "$lane" = stable ]; then + binary="$stable" + options=(--cli-v2) + fi + status=0 + python scripts/ci/opencode_minimal_probe.py --binary "$binary" "${options[@]}" \ + --repeats 1 --timeout 60 --fixture-shape --skill-first \ + --report "$output/$index-$lane.json" || status=$? + printf '%s\t%s\t%s\n' "$index" "$lane" "$status" >> "$output/results.tsv" + if [ "$status" -ne 0 ]; then + failed=1 + fi + done + exit "$failed" + - name: Upload OpenCode version comparison on diagnostic PR + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opencode-version-comparison-${{ github.run_attempt }} + path: ${{ runner.temp }}/opencode-version-comparison/ + retention-days: 14 + if-no-files-found: warn + python: needs: static if: ${{ !cancelled() && ((needs.static.result == 'success' && needs.static.outputs.run-heavy != 'false') || (!inputs.static-checks && needs.static.result == 'skipped')) }} @@ -144,47 +209,19 @@ jobs: rg --version gdb --version | head -1 echo 'OPENDIRECTOR_CI_NATIVE_STACK=1' >> "$GITHUB_ENV" - - name: Compare bundled and stable OpenCode on diagnostic PR + - name: Standalone OpenCode control on diagnostic PR if: github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' - timeout-minutes: 14 + timeout-minutes: 6 continue-on-error: true run: | - output="$RUNNER_TEMP/opencode-version-comparison" - prefix="$RUNNER_TEMP/opencode-stable" - mkdir -p "$output" - bundled="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" - test -x "$bundled" - "$bundled" --version | tee "$output/bundled-version.txt" - npm install --prefix "$prefix" --no-audit --no-fund --ignore-scripts --no-package-lock @opencode/cli-linux-x64@2.4.4 - stable="$prefix/node_modules/@opencode/cli-linux-x64/bin/opencode" - "$stable" --version | tee "$output/stable-version.txt" - index=0 - failed=0 - printf 'case\tlane\texit\n' > "$output/results.tsv" - for lane in bundled stable stable bundled; do - index=$((index + 1)) - binary="$bundled" - options=() - if [ "$lane" = stable ]; then - binary="$stable" - options=(--cli-v2) - fi - status=0 - python scripts/ci/opencode_minimal_probe.py --binary "$binary" "${options[@]}" \ - --repeats 1 --timeout 60 --fixture-shape --skill-first \ - --report "$output/$index-$lane.json" || status=$? - printf '%s\t%s\t%s\n' "$index" "$lane" "$status" >> "$output/results.tsv" - if [ "$status" -ne 0 ]; then - failed=1 - fi - done - exit "$failed" - - name: Upload OpenCode version comparison on diagnostic PR - if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' }} - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: opencode-version-comparison-${{ github.run_attempt }} - path: ${{ runner.temp }}/opencode-version-comparison/ + binary="$(python -c 'from opendirector.agent.native import executable; print(executable("default") or "")')" + if [ -z "$binary" ]; then + echo "::error::Bundled OpenCode is missing" + exit 1 + fi + python scripts/ci/opencode_minimal_probe.py --binary "$binary" \ + --repeats 2 --timeout 60 --fixture-shape --skill-first \ + --report test-results/opencode-diagnostics/standalone-control.json - id: clock-observer name: Build OpenCode clock observer on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} From bf681a373f52026d5a53ca9b58ea3651cac25c26 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 11:40:31 +0800 Subject: [PATCH 24/25] Sample runner pressure around bundled OpenCode cases --- .github/workflows/release-checks.yml | 10 ++++ tests/opencode_ci_resources.py | 89 ++++++++++++++++++++++++++++ tests/opencode_ci_trace.py | 20 ++++--- tests/test_native_runtime.py | 10 +++- tests/test_opencode_ci_trace.py | 55 +++++++++++++---- tests/test_opencode_clock_probe.py | 6 +- 6 files changed, 166 insertions(+), 24 deletions(-) create mode 100644 tests/opencode_ci_resources.py diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index c5518f6d2..c1cf65412 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -237,9 +237,19 @@ jobs: env: OPENDIRECTOR_REAL_CLI: '1' OPENDIRECTOR_CI_TRACE_DIR: ${{ github.workspace }}/test-results/opencode-diagnostics + OPENDIRECTOR_CI_RUNNER_PRESSURE: ${{ github.event_name == 'pull_request' && github.event.pull_request.number == 633 && '1' || '0' }} OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} OD_CI_CLOCK_MODE: libc run: python -m pytest tests/test_native_runtime.py tests/test_agent_visual_gate.py -k real_opencode -m cpu -q -ra --durations=50 --junitxml=test-results/bundled-opencode.xml --ci-profile=test-results/bundled-opencode.json + - name: Upload OpenCode runner pressure on diagnostic PR + if: ${{ always() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.install.outcome == 'success' }} + continue-on-error: true + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opencode-runner-pressure-${{ github.run_attempt }} + path: test-results/opencode-diagnostics/ + retention-days: 14 + if-no-files-found: warn - name: Compare OpenCode snapshots with libc observation on diagnostic PR if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.number == 633 && steps.diagnostic-ripgrep.outcome == 'success' }} timeout-minutes: 6 diff --git a/tests/opencode_ci_resources.py b/tests/opencode_ci_resources.py new file mode 100644 index 000000000..de549b4b7 --- /dev/null +++ b/tests/opencode_ci_resources.py @@ -0,0 +1,89 @@ +"""Bounded Linux resource samples for the diagnostic OpenCode regression.""" + +from contextlib import suppress +import json +from pathlib import Path +import threading +import time + + +SAMPLE_LIMIT = 110 +SAMPLE_FILE = "runner-resources.jsonl" +PRESSURE_FIELDS = { + "cpu": ("some",), + "memory": ("some", "full"), + "io": ("some", "full"), +} +SAMPLE_FIELDS = { + "cpuTotalTicks", "cpuStealTicks", "memAvailableKiB", + "cliIndex", "mainCpuNs", "mainRunQueueNs", "schedStatsEnabled", + *(f"{resource}{kind.title()}Us" for resource, kinds in PRESSURE_FIELDS.items() for kind in kinds), +} + + +def sample_resources(proc, cli_pid): + metrics = {} + for resource, kinds in PRESSURE_FIELDS.items(): + with suppress(OSError, ValueError): + for line in (proc / "pressure" / resource).read_text().splitlines(): + kind, *fields = line.split() + if kind in kinds: + for field in fields: + if field.startswith("total="): + metrics[f"{resource}{kind.title()}Us"] = int(field.removeprefix("total=")) + with suppress(OSError, ValueError, IndexError): + with (proc / "stat").open() as source: + cpu = [int(field) for field in source.readline().split()[1:9]] + metrics.update(cpuTotalTicks=sum(cpu), cpuStealTicks=cpu[7]) + with suppress(OSError, ValueError, IndexError): + for line in (proc / "meminfo").read_text().splitlines(): + if line.startswith("MemAvailable:"): + metrics["memAvailableKiB"] = int(line.split()[1]) + break + if cli_pid is not None: + with suppress(OSError, ValueError): + sample = (proc / str(cli_pid) / "schedstat").read_text().split() + cpu, wait = map(int, sample[:2]) + metrics.update(mainCpuNs=cpu, mainRunQueueNs=wait) + with suppress(OSError, ValueError): + metrics["schedStatsEnabled"] = int((proc / "sys/kernel/sched_schedstats").read_text()) + return metrics + + +def start_resource_probe(root, cli_pids): + """Sample before and during a worker without delaying watchdog cleanup.""" + stop = threading.Event() + + def record(): + with suppress(OSError), (root / SAMPLE_FILE).open("x", encoding="utf-8") as stream: + for _ in range(SAMPLE_LIMIT): + at = time.time() + cli_index = len(cli_pids) + pid = cli_pids[cli_index - 1] if cli_index else None + metrics = sample_resources(Path("/proc"), pid) + stream.write(json.dumps({"at": at, "cliIndex": cli_index, **metrics}) + "\n") + stream.flush() + if stop.wait(1): + break + + threading.Thread(target=record, daemon=True).start() + return stop.set + + +def read_resource_samples(root): + path = root / SAMPLE_FILE + if path.is_symlink() or not path.is_file() or path.stat().st_size > 100_000: + return [] + samples = [] + with path.open(encoding="utf-8", errors="replace") as stream: + for _, line in zip(range(SAMPLE_LIMIT), stream): + with suppress(ValueError): + data = json.loads(line) + if not isinstance(data, dict): + continue + at = data.get("at") + if type(at) not in (float, int) or not 0 < at < 10_000_000_000: + continue + samples.append({"at": at, **{key: value for key, value in data.items() + if key in SAMPLE_FIELDS and type(value) is int and value >= 0}}) + return samples diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index 17c21260b..b97583157 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -1,4 +1,4 @@ -"""Allowlisted timing evidence for failed bundled OpenCode test workers.""" +"""Allowlisted timing evidence for bundled OpenCode test workers.""" from datetime import datetime from heapq import heappush, heapreplace @@ -8,6 +8,8 @@ from pathlib import Path import re +from opencode_ci_resources import read_resource_samples + MODEL_EVENTS = { "model.request", "model.response", "model.completed", "model.error", "model.cancelled", @@ -188,7 +190,8 @@ def _boundary_event(line, identities): return result -def save_failure_trace(worker: Path, destination: Path, case: str, outcome: str): +def save_opencode_trace(worker: Path, destination: Path, case: str, outcome: str): + runner_samples = read_resource_samples(worker) events = [] turns = {} identities = {} @@ -221,13 +224,16 @@ def save_failure_trace(worker: Path, destination: Path, case: str, outcome: str) elif entry > events[0]: heapreplace(events, entry) ordered = [row for _, _, row in sorted(events)] - start = ordered[0]["at"] if ordered else 0 - for row in ordered: - row["tMs"] = round((row.pop("at") - start) * 1000) + start = min((row["at"] for row in (*ordered, *runner_samples)), default=0) + for rows in (ordered, runner_samples): + for row in rows: + row["tMs"] = round((row.pop("at") - start) * 1000) + report = {"case": case, "outcome": outcome, "droppedEvents": total - len(ordered), "events": ordered} + if runner_samples: + report["runnerSamples"] = runner_samples destination.mkdir(parents=True, exist_ok=True) name = re.sub(r"[^a-zA-Z0-9_-]", "_", case) (destination / f"{name}.json").write_text( - json.dumps({"case": case, "outcome": outcome, "droppedEvents": total - len(ordered), - "events": ordered}, indent=2) + "\n", + json.dumps(report, indent=2) + "\n", encoding="utf-8", ) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 68454aeae..383f327a1 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -17,7 +17,8 @@ import httpx import pytest from opencode_ci_probe import cpu_probe, gateway_probe, native_stack_probe, process_environment, watchdog_probe -from opencode_ci_trace import save_failure_trace +from opencode_ci_resources import start_resource_probe +from opencode_ci_trace import save_opencode_trace from process_helpers import assert_process_exited, python_cli from opendirector.application.creation_assets import CreationAssets @@ -367,6 +368,7 @@ def real_opencode_worker(tmp_path, monkeypatch, request): pytest.skip('Set OPENDIRECTOR_REAL_CLI=1 to run the bundled CLI integration') assert native.executable('default') is not None, 'Bundled OpenCode is not installed' timeout = 105 if 'windows_unicode_pipeline' in request.node.name else 60 + sample_runner = sys.platform == 'linux' and os.environ.get('OPENDIRECTOR_CI_RUNNER_PRESSURE') == '1' if os.environ.get('OPENDIRECTOR_REAL_CLI_WORKER') != '1': trace_dir = os.environ.get('OPENDIRECTOR_CI_TRACE_DIR') worker = tmp_path / 'worker' @@ -377,7 +379,7 @@ def real_opencode_worker(tmp_path, monkeypatch, request): def collect(outcome): if trace_dir: try: - save_failure_trace(worker, Path(trace_dir), request.node.name, outcome) + save_opencode_trace(worker, Path(trace_dir), request.node.name, outcome) except OSError: print('Could not save OpenCode CI trace', file=sys.stderr, flush=True) @@ -390,6 +392,8 @@ def collect(outcome): raise if result.returncode: collect('watchdog' if 'Real OpenCode integration timed out;' in result.stdout else 'worker-failed') + elif sample_runner: + collect('worker-exit-zero') assert result.returncode == 0, result.stdout return False @@ -401,6 +405,8 @@ def collect(outcome): monkeypatch.setattr(ToolGateway, 'call', gateway_probe(tmp_path, ToolGateway.call)) processes = [] cli_pids = [] + if probe_enabled and sample_runner: + request.addfinalizer(start_resource_probe(tmp_path, cli_pids)) spawn = asyncio.create_subprocess_exec async def tracked_spawn(*args, **kwargs): probe_cli = probe_enabled and args[0] == native.executable('default') and args[1] == 'run' diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index e197c037e..f15675f18 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -7,7 +7,8 @@ import pytest from opencode_ci_probe import process_environment, record_gateway_event, watchdog_probe -from opencode_ci_trace import LIMIT, save_failure_trace +from opencode_ci_resources import SAMPLE_FILE, sample_resources +from opencode_ci_trace import LIMIT, save_opencode_trace @pytest.mark.cpu @@ -32,7 +33,7 @@ def test_failed_opencode_export_keeps_timeline_and_drops_raw_content(tmp_path): encoding="utf-8", ) destination = tmp_path / "reports" - save_failure_trace(worker, destination, "test_example[image-model]", "watchdog") + save_opencode_trace(worker, destination, "test_example[image-model]", "watchdog") report, = destination.glob("*.json") contents = report.read_text(encoding="utf-8") assert canary not in contents @@ -44,6 +45,36 @@ def test_failed_opencode_export_keeps_timeline_and_drops_raw_content(tmp_path): ] +@pytest.mark.cpu +@pytest.mark.merge +def test_runner_resources_align_to_model_events_and_drop_raw_fields(tmp_path): + proc = tmp_path / "proc" + (proc / "pressure").mkdir(parents=True) + (proc / "pressure" / "cpu").write_text("some avg10=0.02 avg60=0.00 avg300=0.00 total=700\n") + (proc / "pressure" / "io").write_text("some total=12\nfull total=8\n") + (proc / "stat").write_text("cpu 100 10 30 70 4 3 2 1 50\n") + (proc / "meminfo").write_text("MemFree: 300 kB\nMemAvailable: 800 kB\n") + (proc / "41").mkdir() + (proc / "41" / "schedstat").write_text("1234 987 20\n") + metrics = sample_resources(proc, 41) + assert metrics == { + "cpuSomeUs": 700, "ioSomeUs": 12, "ioFullUs": 8, "cpuTotalTicks": 220, + "cpuStealTicks": 1, "memAvailableKiB": 800, "mainCpuNs": 1234, "mainRunQueueNs": 987, + } + (tmp_path / SAMPLE_FILE).write_text( + json.dumps({"at": 9, **metrics, "cliIndex": 1, "raw": "private-test-value"}) + "\n{", + encoding="utf-8", + ) + (tmp_path / "run.model.jsonl").write_text( + json.dumps({"event": "model.completed", "timestamp": 10}), encoding="utf-8", + ) + reports = tmp_path / "reports" + save_opencode_trace(tmp_path, reports, "passed", "worker-exit-zero") + report = json.loads((reports / "passed.json").read_text()) + assert report["runnerSamples"] == [{**metrics, "cliIndex": 1, "tMs": 0}] + assert report["events"][0]["tMs"] == 1000 + + @pytest.mark.cpu @pytest.mark.merge @pytest.mark.skipif(sys.platform != "linux" or not shutil.which("bash") or not shutil.which("git"), @@ -59,7 +90,7 @@ def test_process_probes_preserve_command_exit_and_do_not_record_arguments(tmp_pa record_gateway_event(tmp_path, "gateway.start", 98765) record_gateway_event(tmp_path, "gateway.return", 98765, "success") destination = tmp_path / "reports" - save_failure_trace(tmp_path, destination, "probe", "watchdog") + save_opencode_trace(tmp_path, destination, "probe", "watchdog") raw = (destination / "probe.json").read_text() assert canary not in raw and "98765" not in raw events = json.loads(raw)["events"] @@ -91,7 +122,7 @@ def test_watchdog_probe_distinguishes_exited_bash_from_open_pipe(tmp_path): finally: os.close(read_fd) destination = tmp_path / "reports" - save_failure_trace(tmp_path, destination, "probe", "watchdog") + save_opencode_trace(tmp_path, destination, "probe", "watchdog") events = json.loads((destination / "probe.json").read_text())["events"] start, exit_, zombie_cli, zombie, first_cli, held, second_cli, closed = events assert start["event"] == "bash.start" and exit_["event"] == "bash.exit" @@ -121,7 +152,7 @@ def test_trace_cap_keeps_latest_events_across_files(tmp_path): json.dumps({"event": "model.request", "timestamp": timestamp}) + "\n" for timestamp in range(LIMIT) ), encoding="utf-8") - save_failure_trace(tmp_path, tmp_path / "reports", "capped", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "capped", "watchdog") report = json.loads((tmp_path / "reports/capped.json").read_text()) assert report["droppedEvents"] == 1 assert report["events"][-1]["event"] == "model.completed" @@ -141,7 +172,7 @@ def test_git_watchdog_exports_recent_process_relationships_without_raw_ids(tmp_p monkeypatch.setattr(opencode_ci_probe, "_process_status", lambda path: statuses.get(path.name, ("gone", None))) watchdog_probe(tmp_path, (200,)) - save_failure_trace(tmp_path, tmp_path / "reports", "git", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "git", "watchdog") events = json.loads((tmp_path / "reports/git.json").read_text())["events"] samples = [event for event in events if event["event"] == "git.watchdog"] assert len(samples) == 8 @@ -164,7 +195,7 @@ def test_git_watchdog_observes_wrapper_exit_before_parent_reaps_it(tmp_path): watchdog_probe(tmp_path, (os.getpid(),)) assert child.wait(timeout=5) == 0 watchdog_probe(tmp_path, (os.getpid(),)) - save_failure_trace(tmp_path, tmp_path / "reports", "git", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "git", "watchdog") events = json.loads((tmp_path / "reports/git.json").read_text())["events"] samples = [event for event in events if event["event"] == "git.watchdog"] assert [event["state"] for event in samples] == ["Z", "gone"] @@ -187,7 +218,7 @@ def test_cpu_probe_exports_tick_deltas_and_omits_reused_processes(tmp_path, monk monkeypatch.setattr(probe.time, "sleep", lambda seconds: None) monkeypatch.setattr(probe.os, "sysconf", lambda key: 100, raising=False) probe.cpu_probe(tmp_path, (123456, 234567)) - save_failure_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") raw = (tmp_path / "reports/cpu.json").read_text() assert "123456" not in raw and "234567" not in raw assert json.loads(raw)["events"] == [{ @@ -228,7 +259,7 @@ def work(seconds): monkeypatch.setattr(probe.time, "sleep", work) probe.cpu_probe(tmp_path, (os.getpid(),)) - save_failure_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "cpu", "watchdog") event, = json.loads((tmp_path / "reports/cpu.json").read_text())["events"] assert event["mainTicks"] > 0 and event["totalTicks"] > 0 assert event["sampleMs"] >= 100 and event["ticksPerSecond"] == os.sysconf("SC_CLK_TCK") @@ -256,7 +287,7 @@ def run(command, **kwargs): monkeypatch.setattr(probe.subprocess, "run", run) probe.native_stack_probe(tmp_path, (123456,)) - save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") raw = (tmp_path / "reports/stack.json").read_text() assert all(value not in raw for value in ("private", "123abc", "123456", "ShouldNotExport")) events = json.loads(raw)["events"] @@ -282,7 +313,7 @@ def timeout(*args, **kwargs): monkeypatch.setattr(probe.subprocess, "run", timeout) probe.native_stack_probe(tmp_path, (123,)) - save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") raw = (tmp_path / "reports/stack.json").read_text() assert "private_canary" not in raw assert [event["status"] for event in json.loads(raw)["events"]] == ["missing", "timeout"] @@ -303,6 +334,6 @@ def test_native_stack_probe_detaches_from_live_process(tmp_path, monkeypatch): finally: child.terminate() child.wait(timeout=5) - save_failure_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") + save_opencode_trace(tmp_path, tmp_path / "reports", "stack", "watchdog") events = json.loads((tmp_path / "reports/stack.json").read_text())["events"] assert events[0]["status"] == "ok" and len(events) <= 21 diff --git a/tests/test_opencode_clock_probe.py b/tests/test_opencode_clock_probe.py index a8baa0ba5..fa06ef8bc 100644 --- a/tests/test_opencode_clock_probe.py +++ b/tests/test_opencode_clock_probe.py @@ -7,7 +7,7 @@ import pytest -from opencode_ci_trace import save_failure_trace +from opencode_ci_trace import save_opencode_trace @pytest.mark.cpu @@ -68,7 +68,7 @@ def progress(stage, **facts): ahead = int(result.stdout) progress(mode + "_value", aheadMs=ahead) assert ahead >= 1900 if mode == "libc" else abs(ahead) < 100 - save_failure_trace(root, root / "reports", "clock", "probe") + save_opencode_trace(root, root / "reports", "clock", "probe") events = json.loads((root / "reports/clock.json").read_text())["events"] progress(mode + "_events", events=events) assert [event["event"] for event in events] == ["opencode.clockAhead", "opencode.clock"] @@ -93,7 +93,7 @@ def test_clock_events_drop_raw_identity_and_invalid_values(tmp_path): (tmp_path / "process-boundaries.log").write_text( "10 opencode.clock 987654 libc\n11 opencode.clockAhead 987654 2500\n" "12 opencode.clock 987654 private_canary\n13 opencode.clockAhead 987654 private_canary\n") - save_failure_trace(tmp_path, tmp_path / "reports", "clock", "probe") + save_opencode_trace(tmp_path, tmp_path / "reports", "clock", "probe") raw = (tmp_path / "reports/clock.json").read_text() assert "987654" not in raw and "private_canary" not in raw events = json.loads(raw)["events"] From a044c76dce5d7a988489d91b0be1d6abc2c55c4a Mon Sep 17 00:00:00 2001 From: wangtiance Date: Thu, 3 Dec 2026 11:42:51 +0800 Subject: [PATCH 25/25] Collect samples from the nested pytest worker --- tests/opencode_ci_resources.py | 3 +-- tests/opencode_ci_trace.py | 8 ++++++-- tests/test_opencode_ci_trace.py | 6 ++++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/tests/opencode_ci_resources.py b/tests/opencode_ci_resources.py index de549b4b7..691f2e353 100644 --- a/tests/opencode_ci_resources.py +++ b/tests/opencode_ci_resources.py @@ -70,8 +70,7 @@ def record(): return stop.set -def read_resource_samples(root): - path = root / SAMPLE_FILE +def read_resource_samples(path): if path.is_symlink() or not path.is_file() or path.stat().st_size > 100_000: return [] samples = [] diff --git a/tests/opencode_ci_trace.py b/tests/opencode_ci_trace.py index b97583157..0c5ea4c4e 100644 --- a/tests/opencode_ci_trace.py +++ b/tests/opencode_ci_trace.py @@ -8,7 +8,7 @@ from pathlib import Path import re -from opencode_ci_resources import read_resource_samples +from opencode_ci_resources import SAMPLE_FILE, read_resource_samples MODEL_EVENTS = { @@ -191,7 +191,7 @@ def _boundary_event(line, identities): def save_opencode_trace(worker: Path, destination: Path, case: str, outcome: str): - runner_samples = read_resource_samples(worker) + runner_samples = [] events = [] turns = {} identities = {} @@ -200,6 +200,10 @@ def save_opencode_trace(worker: Path, destination: Path, case: str, outcome: str directories.sort() for name in sorted(files): path = Path(folder) / name + if name == SAMPLE_FILE: + if not runner_samples: + runner_samples = read_resource_samples(path) + continue is_trace = name.endswith((".model.jsonl", ".opencode.jsonl")) if not is_trace and name not in {"opencode.log", "process-boundaries.log"}: continue diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py index f15675f18..e76204ca9 100644 --- a/tests/test_opencode_ci_trace.py +++ b/tests/test_opencode_ci_trace.py @@ -61,11 +61,13 @@ def test_runner_resources_align_to_model_events_and_drop_raw_fields(tmp_path): "cpuSomeUs": 700, "ioSomeUs": 12, "ioFullUs": 8, "cpuTotalTicks": 220, "cpuStealTicks": 1, "memAvailableKiB": 800, "mainCpuNs": 1234, "mainRunQueueNs": 987, } - (tmp_path / SAMPLE_FILE).write_text( + worker_case = tmp_path / "worker" / "test_case0" + worker_case.mkdir(parents=True) + (worker_case / SAMPLE_FILE).write_text( json.dumps({"at": 9, **metrics, "cliIndex": 1, "raw": "private-test-value"}) + "\n{", encoding="utf-8", ) - (tmp_path / "run.model.jsonl").write_text( + (worker_case / "run.model.jsonl").write_text( json.dumps({"event": "model.completed", "timestamp": 10}), encoding="utf-8", ) reports = tmp_path / "reports"