Skip to content

perf(opencode-claimant): cut poll.py end-to-end latency (parallelize + bound its sequential external reads) - #13210

Open
dezren39 wants to merge 2 commits into
mainfrom
xaltha/13135-poll-latency
Open

dezren39 wants to merge 2 commits into
mainfrom
xaltha/13135-poll-latency

Conversation

@dezren39

@dezren39 dezren39 commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Closes #13135.

Problem

pm-stack/opencode-claimant/poll.py took 43–100s wall with only ~2s CPU per run: waits on sequential external reads (turso ledger SELECTs, broker queue queries, OpenCode session list over a 28k+ root-session store). #13112 raised the gate timeout to 300s as a symptom fix; this slice cuts the latency itself.

Change

  • poll.py: parallelize the independent external reads (ledger bindings, per-queue claimed/handed_off rows, session list, active-id set) instead of running them strictly sequentially.
  • Each external read gets an explicit per-read timeout plus a recorded slow-read note, so one slow backend degrades the poll visibly instead of silently eating the budget.
  • claimant.py: read the fire-log code source from .git directly, no git spawn (removes a subprocess hop from the fire path).
  • Output contract unchanged: JSON shape and pinned semantics (root = no parentID, activity = time.updated falling back to time.created, finished = time.idle or a top-level outcome) preserved — claimant.py cap counting still delegates to poll.py pinned functions (opencode-claimant(poll/claimant): snapshot rewrite dropped poll.py's test-pinned cap API (36/36 tests error) and inverted cap_room — idle reads as saturated, busy launches unbounded #6609).
  • Tests: new test_poll.py coverage plus bench_poll_timing.py harness.

Verification

  • Hermetic suite green: cd pm-stack/opencode-claimant && python3 -I run_hermetic_tests.py via remote dispatch — https://github.com/developing-today/fleet/actions/runs/45159877756 (conclusion: success).
  • Note: fleet queue dispatch from this seat currently fails with invalid peer certificate: UnknownIssuer (seat fleet binary predates the platform-verifier fix, code#13122); dispatched via the documented raw-workflow fallback gh workflow run fleet-command.yml --repo developing-today/fleet instead. The relay-proxy route was tried and hung.

Remaining acceptance items (post-merge follow-up)

  • poll.py timed over 10 runs on the laptop: p99 wall < 30s, all runs exit 0 (bench_poll_timing.py).
  • A live claimant fire using the sped-up poll passes the gate and the fire log shows the reduced poll duration.
{
  "direct_parent": null,
  "links": [],
  "lineage": {
    "design": null,
    "roadmap_item": null,
    "priority": null
  },
  "pm_meta": 1,
  "provenance": {
    "queue_id": null,
    "scheduled_start": null,
    "picked_up_at": null,
    "work_started_at": null,
    "created_at": "2026-11-23T10:57:36Z",
    "session_id": null,
    "lane": null,
    "host": "htch-runtime",
    "worktree": "/home/hatch",
    "model": null,
    "lane_start_issues": [],
    "workspace_ref": {
      "kind": "worktree",
      "id": "/home/hatch",
      "repo": "developing-today/code",
      "branch": "main",
      "sha": "bbfc8aa3a3b4f3e3d399b7e76beb6962c0daa5b9"
    },
    "auth_subject": "xaltha",
    "stamped_by": "fleet 0.1.0 (native)"
  }
}

Start Proof
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

…nd each with a slow-read note (#13135)

main() ran every external read strictly sequentially: the paginated
session list, the server's active set, 8 broker /list reads and the
turso-exec ledger SELECT summed to 43-100s of wall per poll. The
reads are independent, so they now run concurrently on a thread
pool; the ledger read still waits for the candidate-shaped ids but
starts the moment the queue reads land, overlapping any session
read still in flight. Results are consumed in the original QUEUES
order, so the printed JSON is byte-compatible (pinned #6609
semantics untouched).

Each read is bounded at its transport under a named constant
(SERVER_READ_TIMEOUT_S 15, BROKER_READ_TIMEOUT_S 30,
LEDGER_READ_TIMEOUT_S 60 — the historical values), and _timed_read
records a slow-read note (stderr + slow_reads()) for any read over
SLOW_READ_MS, so a slow backend degrades the poll visibly instead
of silently eating the gate budget. Timed-out reads keep their
existing fail-closed shapes (None / [] + read_errors / ledger
None).

Tests: read-timeout constants, _timed_read note semantics, and a
main() integration test pinning the output shape, the overlap and
fail-closed cap behaviour with all fetches stubbed.
bench_poll_timing.py is the runnable timing acceptance: 10 poll.py
runs against fixture backends calibrated to the production read
shape (28k-session store, 3s broker reads, 5s ledger SELECT).
… no git spawn (#13135)

TestCodeSourceFireLog failed under run_hermetic_tests.py's audit guard
for two reasons, not one: the _make_clone fixture spawned git, and
read_code_source() itself spawned git rev-parse twice. A vendored
fixture alone would still fail — the guard turns the rev-parse calls
into RuntimeError, which the fail-open handler reports as
'unreadable', failing the state == 'ok' assertions.

read_code_source() now resolves HEAD plus loose/packed refs with
plain file reads (worktree .git files followed via 'gitdir:'), so the
fire path never forks for its own provenance and the read stays
usable under the no-subprocess guard. Semantics preserved: detached
HEAD reports branch 'HEAD', any unreadable layout still yields
state 'unreadable', result still cached per process. _make_clone
builds the same static .git layout with file writes instead of
git init/add/commit, so the two tests exercise the real production
read hermetically.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T11:01:24.858632Z 607e16e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 18 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c924ef6d-0a80-4f2a-99c8-c6809e3493e5
Commits

Reviewing files that changed from the base of the PR and between 0ca8ed6 and 607e16e.

Files selected for processing: 5

  • pm-stack/opencode-claimant/bench_poll_timing.py
  • pm-stack/opencode-claimant/claimant.py
  • pm-stack/opencode-claimant/poll.py
  • pm-stack/opencode-claimant/test_claimant.py
  • pm-stack/opencode-claimant/test_poll.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 607e16ecef

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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 👍 / 👎.

Comment on lines +1059 to +1061
_timed_read, "active session ids", fetch_active_ids
)
row_futures = {

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 Read the active set after completing the session census

If a previously finished root resumes while the paginated session census is running, this concurrent active-set read can finish before the resume and omit its ID. Resumed sessions retain their previous idle/outcome markers, so _active_root_state then classifies that running root as finished even if its census entry was fetched after the resume. The previous ordering fetched active IDs after the entire census and therefore recognized this case. This manufactures cap_room in poll output, which prompt.md step 3 explicitly uses as its launch budget. Keep the broker and ledger reads concurrent, but fetch or refresh active IDs after the census completes.

Useful? React with 👍 / 👎.

Comment on lines +765 to +769
_SLOW_READS.append({"read": name, "elapsed_ms": elapsed_ms})
print(
f"Note: slow read {name} took {elapsed_ms}ms "
f"(slow-read threshold {SLOW_READ_MS}ms)",
file=sys.stderr,

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 Propagate slow-read diagnostics to the claimant process

During a normal claimant fire, these slow-read notes never reach an operator or the fire log: claimant.run_poll() runs this script with capture_output=True and uses stderr only to extract phase markers, discarding the notes even on success. _SLOW_READS also remains confined to the child process, and its accessor has no production callers. Consequently, a backend exceeding the new threshold produces no persistent degradation signal in the production path this instrumentation is intended to diagnose. Pass structured timing notes back to the claimant and record them, or explicitly forward the sanitized slow-read messages.

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(opencode-claimant): cut poll.py end-to-end latency (parallelize + bound its sequential external reads)

1 participant