diff --git a/.github/workflows/release-checks.yml b/.github/workflows/release-checks.yml index 67d162bbf..c1cf65412 100644 --- a/.github/workflows/release-checks.yml +++ b/.github/workflows/release-checks.yml @@ -61,6 +61,103 @@ 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 + + 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')) }} @@ -103,12 +200,131 @@ jobs: - name: Check generated contracts if: always() && steps.install.outcome == 'success' run: python scripts/generate_contracts.py --check + - id: diagnostic-ripgrep + 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 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 + 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 + - 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_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 + continue-on-error: true + env: + OPENDIRECTOR_REAL_CLI: '1' + OD_CI_CLOCK_MODE: libc + OPENDIRECTOR_CI_CLOCK_SHIM: ${{ steps.clock-observer.outputs.path }} + OPENCODE_DISABLE_MODELS_FETCH: '1' + run: | + 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 + 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 + [[ -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 + 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 + result=0 + timeout --kill-after=5s 85s python -m pytest -q --tb=short \ + --basetemp "$basetemp" \ + '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 }')" + 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" != libc ]]; 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 clock comparison + 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: + 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 + 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/docs/development/validation.md b/docs/development/validation.md index c62a5dea9..a420526b5 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -177,6 +177,26 @@ 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 内部事件,以及 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, 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. + +清理前的 `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. + +仅在诊断 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. + +单调时钟诊断仅通过测试夹具为 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_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/scripts/ci/opencode_clock_probe.c b/scripts/ci/opencode_clock_probe.c new file mode 100644 index 000000000..844f460f1 --- /dev/null +++ b/scripts/ci/opencode_clock_probe.c @@ -0,0 +1,72 @@ +#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)) { + ssize_t written = write(fd, line, (size_t)length); + if (written != length) { + close(fd); + return; + } + } + 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/scripts/ci/opencode_minimal_probe.py b/scripts/ci/opencode_minimal_probe.py new file mode 100644 index 000000000..35165d33f --- /dev/null +++ b/scripts/ci/opencode_minimal_probe.py @@ -0,0 +1,240 @@ +"""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", "shell", "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 + 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", "tMs": received_ms - self.server.wall_started_ms, + "results": results, "bashEnabled": self.server.shell_tool 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 = 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", {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)}, + }]} + 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", "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, cli_v2, +): + 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 + 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", 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"}, + "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\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", "--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: + 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=None if cli_v2 else prompt + "\n", timeout=timeout) + timed_out = False + except subprocess.TimeoutExpired: + 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() + 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") + 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, + "snapshotPresent": bool(part.get("snapshot")), + }) + 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(process_done_ms / 1000, 2), "processDoneMs": process_done_ms, + "events": events, "model": server.events, + "shell": shell_events, + } + + +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") + 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() + 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, 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"] + report["passed"] = ( + 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(shell_tool) + ) + 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", 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) + 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()) diff --git a/tests/opencode_ci_probe.py b/tests/opencode_ci_probe.py new file mode 100644 index 000000000..1cb73d286 --- /dev/null +++ b/tests/opencode_ci_probe.py @@ -0,0 +1,231 @@ +"""Optional Linux process boundaries for the bundled OpenCode CI fixture.""" + +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" + 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" +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" + 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) + 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, **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), + } + + +def _process_status(path): + try: + state, parent, *_ = (path / "stat").read_text().rsplit(") ", 1)[1].split() + return state, parent + except FileNotFoundError: + return "gone", None + except (OSError, IndexError, ValueError): + return "unknown", None + + +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 + + +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() + 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 = {} + 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(): + 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 {} + cli_identities = {str(pid) for pid in cli_pids} + with boundaries.open("a", encoding="utf-8") as output: + 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" + 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} {state} {parent_role} " + 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:"): + 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_resources.py b/tests/opencode_ci_resources.py new file mode 100644 index 000000000..691f2e353 --- /dev/null +++ b/tests/opencode_ci_resources.py @@ -0,0 +1,88 @@ +"""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(path): + 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 new file mode 100644 index 000000000..0c5ea4c4e --- /dev/null +++ b/tests/opencode_ci_trace.py @@ -0,0 +1,243 @@ +"""Allowlisted timing evidence for bundled OpenCode test workers.""" + +from datetime import datetime +from heapq import heappush, heapreplace +import json +from math import isfinite +import os +from pathlib import Path +import re + +from opencode_ci_resources import SAMPLE_FILE, read_resource_samples + + +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", "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", + "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") +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 + + +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) + + +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 _boundary_event(line, identities): + fields = line.split() + 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): + 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 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 + 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 + 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 + 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 phase == "watchdog": + count_fields = PIPE_COUNTS if source == "bash" else () + 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 in {"bash", "git"}: + 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 == "-": + 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) + return result + + +def save_opencode_trace(worker: Path, destination: Path, case: str, outcome: str): + runner_samples = [] + events = [] + turns = {} + identities = {} + total = 0 + for folder, directories, files in os.walk(worker): + 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 + 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: + 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: + 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 = 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(report, indent=2) + "\n", + encoding="utf-8", + ) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 58e1b15d1..383f327a1 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -16,10 +16,14 @@ from fastapi.testclient import TestClient import httpx import pytest +from opencode_ci_probe import cpu_probe, gateway_probe, native_stack_probe, process_environment, watchdog_probe +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 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 @@ -364,21 +368,62 @@ 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': - 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_opencode_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') + elif sample_runner: + collect('worker-exit-zero') assert result.returncode == 0, result.stdout return False 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 = [] + 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' + 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']) + 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), asyncio.get_running_loop())) + if probe_cli: + cli_pids.append(process.pid) stage = 'run' if 'run' in args else 'skill_catalog' if 'skill' in args else 'other' print(f'OpenCode trace {monotonic():.3f} process.spawn pid={process.pid} stage={stage}', flush=True) if os.environ.get('OPENDIRECTOR_TEST_CLI_STALL') and 'run' in args: @@ -390,6 +435,13 @@ def timed_out(): print(f'OpenCode trace {monotonic():.3f} watchdog.fired', flush=True) 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)) + 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) pending = [] for process, group, loop in reversed(processes.copy()): print(f'OpenCode subprocess {process.pid}: returncode={process.returncode}', file=sys.stderr, flush=True) diff --git a/tests/test_opencode_ci_trace.py b/tests/test_opencode_ci_trace.py new file mode 100644 index 000000000..e76204ca9 --- /dev/null +++ b/tests/test_opencode_ci_trace.py @@ -0,0 +1,341 @@ +import json +import os +import shutil +import subprocess +import sys + +import pytest + +from opencode_ci_probe import process_environment, record_gateway_event, watchdog_probe +from opencode_ci_resources import SAMPLE_FILE, sample_resources +from opencode_ci_trace import LIMIT, save_opencode_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_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 + 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}, + ] + + +@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, + } + 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", + ) + (worker_case / "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"), + 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_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"] + 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 +@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: + 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: + os.close(write_fd) + watchdog_probe(tmp_path, (os.getpid(),)) + finally: + os.close(read_fd) + destination = tmp_path / "reports" + 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" + assert zombie_cli["event"] == first_cli["event"] == second_cli["event"] == "opencode.watchdog" + assert first_cli["state"] == second_cli["state"] == "R" + 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", "parentRole", "tMs", + "stdoutReaders", "stdoutWriters", "stderrReaders", "stderrWriters", + } + + +@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_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" + 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_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 + 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_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"] + 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"] + + +@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_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"] == [{ + "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) + 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 + + +@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_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") + + +@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_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"] + 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_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"] + + +@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_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 new file mode 100644 index 000000000..fa06ef8bc --- /dev/null +++ b/tests/test_opencode_clock_probe.py @@ -0,0 +1,100 @@ +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + +from opencode_ci_trace import save_opencode_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): + 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" + 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" + 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 +#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" + 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_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"] + 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)}) + 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 +@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_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"] + assert len(events) == 2 and events[0]["span"] == events[1]["span"]