Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions pm-stack/opencode-claimant/bench_poll_timing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
#!/usr/bin/env python3
"""bench_poll_timing.py — the #13135 timing acceptance for poll.py,
runnable anywhere (CI runner included): 10 end-to-end poll.py runs
against fixture backends, p99 wall time must stay under the 30s
pre-#13112 gate budget.

The fixtures reproduce the production read shape the issue measured
(43–100s wall, ~2s CPU) at its low end, with fixed per-read delays:

- session list: 28,000 sessions paginated at poll.py's 200/page,
100ms per page -> ~14s sequential
- active-id set: 1s
- broker /list: 3s per read x 8 reads -> ~24s sequential
- ledger SELECT (stub turso-exec): 5s

Sequential total ~44s; a poll that overlaps the independent reads
lands near max(session list, broker) + ledger ~19s. Delays are
server-side sleeps in a threading fixture server, so the fixture
itself never serializes poll.py's reads.

Argument contract (#3352): bench_poll_timing.py [POLL_PY] — zero
arguments benches the sibling poll.py, one argument benches that
file; anything else is a usage error (exit 2) before any work runs.
Exit 0 iff all 10 runs exit 0 and p99 < 30s.
"""

import json
import os
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

RUNS = 10
P99_BUDGET_S = 30.0
TOTAL_SESSIONS = 28_000
PAGE_DELAY_S = 0.10
ACTIVE_DELAY_S = 1.0
BROKER_DELAY_S = 3.0
LEDGER_DELAY_S = 5.0

CANDIDATE_ROW = {
"id": 42,
"status": "claimed",
"priority": 1,
"progress": {"lane": "opencode", "stage": "handed_off"},
}


class FixtureHandler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass

def _json(self, payload):
body = json.dumps(payload).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/api/session":
time.sleep(PAGE_DELAY_S)
query = urllib.parse.parse_qs(parsed.query)
limit = int(query["limit"][0])
start = int(query.get("cursor", ["0"])[0])
now_ms = int(time.time() * 1000)
page = [
{
"id": f"ses_{i}",
"time": {"created": now_ms - 600_000, "updated": now_ms - 60_000},
}
for i in range(start, min(start + limit, TOTAL_SESSIONS))
]
nxt = start + limit if start + limit < TOTAL_SESSIONS else None
self._json({"data": page, "cursor": {"next": str(nxt) if nxt else None}})
elif parsed.path == "/api/session/active":
time.sleep(ACTIVE_DELAY_S)
self._json({"data": {}})
else:
self.send_response(404)
self.end_headers()

def do_POST(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path != "/list":
self.send_response(404)
self.end_headers()
return
time.sleep(BROKER_DELAY_S)
length = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(length) or b"{}")
rows = []
if body.get("status") == "claimed" and body.get("queue") == (
"repo-health-code-pilot"
):
rows = [CANDIDATE_ROW]
self._json({"ok": True, "rows": rows})


def main():
if len(sys.argv) > 2:
print(
f"bench_poll_timing.py: unexpected argument {sys.argv[2]!r}; "
"usage: python3 bench_poll_timing.py [POLL_PY]",
file=sys.stderr,
)
return 2
poll_py = (
Path(sys.argv[1]).resolve()
if len(sys.argv) == 2
else Path(__file__).resolve().parent / "poll.py"
)
if not poll_py.is_file():
print(f"bench_poll_timing.py: poll.py not found at {poll_py}", file=sys.stderr)
return 2

server = ThreadingHTTPServer(("127.0.0.1", 0), FixtureHandler)
server.daemon_threads = True
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
with tempfile.TemporaryDirectory(prefix="poll-bench-") as tmp:
home = Path(tmp)
auth = home / ".local" / "state" / "opencode" / "service-prod.json"
auth.parent.mkdir(parents=True)
auth.write_text(json.dumps({"password": "bench"}))
tools = home / "tools"
tools.mkdir()
(tools / "turso-exec.py").write_text(
"import time\n"
f"time.sleep({LEDGER_DELAY_S})\n"
'print("[0] ok affected=0 rowid=None rows=[]")\n'
)
token = home / "token"
token.write_text("bench-token\n")
env = dict(
os.environ,
HOME=tmp,
OPENCODE_URL=f"http://127.0.0.1:{port}",
OPENCODE_AUTH_FILE=str(auth),
REPO_QUEUE_BROKER_URL=f"http://127.0.0.1:{port}",
REPO_QUEUE_TOKEN_FILE=str(token),
)
times = []
for i in range(RUNS):
start = time.monotonic()
result = subprocess.run(
[sys.executable, str(poll_py)],
env=env,
capture_output=True,
text=True,
timeout=300,
)
elapsed = time.monotonic() - start
times.append(elapsed)
print(f"run {i + 1}/{RUNS}: {elapsed:.2f}s exit={result.returncode}")
if result.returncode != 0:
print(result.stderr[-2000:], file=sys.stderr)
return 1
out = json.loads(result.stdout)
if len(out["candidates"]) != 1 or out["cap_room"] is None:
print(
"bench_poll_timing.py: poll output lost its fixture "
f"shape: candidates={len(out['candidates'])} "
f"cap_room={out['cap_room']}",
file=sys.stderr,
)
return 1
ordered = sorted(times)
# Nearest-rank p99 over RUNS samples.
p99 = ordered[min(RUNS, max(1, -(-99 * RUNS // 100))) - 1]
print(
f"runs={RUNS} min={ordered[0]:.2f}s "
f"median={ordered[RUNS // 2]:.2f}s p99={p99:.2f}s "
f"budget={P99_BUDGET_S:.0f}s"
)
return 0 if p99 < P99_BUDGET_S else 1
finally:
server.shutdown()


if __name__ == "__main__":
sys.exit(main())
79 changes: 56 additions & 23 deletions pm-stack/opencode-claimant/claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,43 @@ def read_mode() -> str:
_code_source: "Dict[str, Any] | None" = None


def _read_git_ref(git_dir: "Path", ref: str) -> "str | None":
"""Resolve a git ref to its commit sha by reading .git directly.

Loose ref first, then packed-refs. Returns None when the ref is
not recorded anywhere. Pure file reads: no git binary is spawned,
so this stays usable under the hermetic suite's no-subprocess
guard (#13135).
"""
try:
sha = (git_dir.joinpath(*ref.split("/"))).read_text().strip()
except OSError:
sha = ""
if len(sha) == 40 and all(c in "0123456789abcdef" for c in sha):
return sha
try:
packed = (git_dir / "packed-refs").read_text().splitlines()
except OSError:
return None
for line in packed:
if line.startswith("#") or line.startswith("^"):
continue
parts = line.split(" ", 1)
if len(parts) == 2 and parts[1].strip() == ref and len(parts[0]) == 40:
return parts[0]
return None


def read_code_source() -> "Dict[str, Any]":
"""Read the primary clone's checked-out branch and commit.

Fail-open by design: this is provenance for the fire log, never
a gate. Any git failure (no git binary, not a checkout, timeout)
yields state "unreadable" with branch/commit None rather than
raising - a fire must never abort because its own provenance
Reads .git directly (HEAD plus loose/packed refs) instead of
spawning `git rev-parse`: the fire path never forks for its own
provenance, and the read stays usable under the hermetic suite's
no-subprocess guard (#13135). Fail-open by design: this is
provenance for the fire log, never a gate. Any unreadable .git
layout yields state "unreadable" with branch/commit None rather
than raising - a fire must never abort because its own provenance
read failed. The result is cached per process: one fire is one
process, and the checkout does not change under a running fire.
"""
Expand All @@ -305,25 +335,28 @@ def read_code_source() -> "Dict[str, Any]":
}
_code_source = source
try:
branch = subprocess.run(
["git", "-C", str(PRIMARY_CLONE), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
timeout=10,
)
commit = subprocess.run(
["git", "-C", str(PRIMARY_CLONE), "rev-parse", "HEAD"],
capture_output=True,
text=True,
timeout=10,
)
if branch.returncode != 0 or commit.returncode != 0:
source["state"] = "unreadable"
return source
source["branch"] = branch.stdout.strip() or None
source["commit"] = commit.stdout.strip() or None
if source["branch"] is None or source["commit"] is None:
source["state"] = "unreadable"
git_dir = PRIMARY_CLONE / ".git"
if git_dir.is_file():
# Worktree / linked checkout: .git holds "gitdir: <path>".
target = git_dir.read_text().strip()
if not target.startswith("gitdir:"):
raise ValueError("unexpected .git file")
git_dir = Path(target[len("gitdir:") :].strip())
if not git_dir.is_absolute():
git_dir = PRIMARY_CLONE / git_dir
head = (git_dir / "HEAD").read_text().strip()
if head.startswith("ref:"):
ref = head[len("ref:") :].strip()
branch = ref[len("refs/heads/") :] if ref.startswith("refs/heads/") else ref
commit = _read_git_ref(git_dir, ref)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve shared branch refs through the worktree's common directory

When PRIMARY_CLONE is an attached linked worktree, its .git file points to a per-worktree directory containing HEAD, but branch refs and packed-refs live in the shared directory identified by commondir. Passing the private directory to _read_git_ref therefore makes a valid checkout report state: "unreadable" with null branch and commit on every fire, whereas the previous git rev-parse calls resolved it correctly. Keep reading HEAD from the private directory, but resolve shared refs against the common directory when commondir exists.

Useful? React with 👍 / 👎.

elif len(head) == 40 and all(c in "0123456789abcdef" for c in head):
branch, commit = "HEAD", head # detached HEAD, as rev-parse reports it
else:
raise ValueError("unparsable HEAD")
if not branch or commit is None:
raise ValueError("ref unresolvable")
source["branch"] = branch
source["commit"] = commit
except Exception:
source["state"] = "unreadable"
return source
Expand Down
Loading