Skip to content

Flatten PRISM first-job latency tail for new connections - #92

Merged
RobertClarke merged 6 commits into
1.x.xfrom
prism-first-job-latency
Jul 25, 2026
Merged

RobertClarke merged 6 commits into
1.x.xfrom
prism-first-job-latency

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Flattens the new-connection first-job latency tail on the PRISM coordinator. Live evidence (2026-07-25): first mining.notify on :3340 measured 8.2s from outside (subscribe 121ms, authorize 170ms) while the highdiff listener delivered in 745ms; sidecar probes on a 4s budget were failing 50–100/hr; qbit_prism_initial_job_requests_total{result="cancelled"} reached 8,983 in ~7h of ~45–150-client churn at a ~47s tip cadence. Root causes were profiled at b002caa and re-located at the current 1.x.x tip.

  • Initial requests ride the priority build instead of defer-then-rebuild. An initial request now probes the bundle cache before routine build admission, so a first job with published work in cache is served immediately instead of waiting out an entire publication-critical build it never contended with. On a cache miss behind such a build, the request subscribes to the in-flight priority build's promise and consumes its bundle at completion (validated against the exact cache key and the same usability checks a cache entry faces), replacing the 0.05s spin-poll for the whole build duration and the cancel→rebuild churn. A new subscribed result is tracked in qbit_prism_initial_job_prepared_work_total.
  • Payout-gate non-admission with a bundle in hand is retryable. _deliver_initial_bundle returning terminal False on gate non-admission disconnected the client mid-handshake; every payout publication turned unlucky joins into a disconnect→reconnect→rebuild loop (the dominant source of the 8,983 cancelled requests). Non-admission now retries with the request's own backoff and deadline; genuine cancellation stays terminal. (Distinct from Fix stale abandon of accepted PRISM blocks #89, which fixed abandon-side preview clearing.)
  • Per-generation share-window serialization cache. The serialized share window — its canonical_json_sha256 and the audit-builder compact payload fragments — only changes per (payout generation, ledger-artifact generation, window), yet was recomputed inside every template-bump build, serializing 100k+ share dicts under the GIL each time. Both are now cached per generation; the builder-subprocess payload is composed from the cached fragment strings without re-encoding the share tree, byte-equivalent JSON to the previous single json.dump (covered by an equivalence test against a captured builder stdin).
  • Worker counts are real env knobs. PRISM_INITIAL_JOB_MAX_WORKERS (default 4) and PRISM_JOB_BUILD_EXECUTOR_WORKERS (default 2) are parsed, validated, wired through Compose/.env.example/PRISM.md, and exposed as configured-worker gauges (qbit_prism_initial_job_delivery_configured_workers, new qbit_prism_job_build_configured_workers). Per Codex review, both knobs are constrained to capacities the pipeline can actually use: the build-executor width is capped at the scheduler's two-flight admission (values above 2 rejected at startup; lowering to 1 remains a real serialization control), and the initial-job worker count is capped at PRISM_STRATUM_MAX_PENDING_INITIAL_JOBS, past which extra workers could never receive a task.
  • Never-served clients lead the tip-refresh wave. PRISM.md already promised "initial delivery outranks new-tip replacement", but the delivery priorities said otherwise (INITIAL=1 sorted after NEW_TIP=0), and bounded fanout submission meant queue priority couldn't help clients not yet submitted. The constants now match the documented ordering and fanout admission itself orders never-served clients first, so first jobs no longer trail the whole fleet wave.

Success metric

p99 first-notify under sustained 20–60s tip churn drops from multi-second to sub-second. In the scaled simulated-load test (SimulatedChurnLatencyTests, 30 clients joining through continuous tip churn at ~1:100 cadence with artificial build cost), measured p99 first-notify is ~1ms against the 1s bound, with zero disconnects and zero poll failures; the same scenario previously parked mid-refresh joiners behind every priority build and disconnected them at payout publications.

Validation

  • python3 -m unittest discover -s tests -p 'test_*.py' — 1,228 tests, OK (3 skipped)
  • New coverage: priority-build subscription wakeup and consumption; cached-bundle fast path during a priority window; retryable gate non-admission with eventual delivery (and cancellation staying terminal); serialization-cache invalidation on generation/payout bumps; builder-payload equivalence with and without the cache; share-count-mismatch fallback; env-knob defaults, wiring, and metric rendering; executor worker-count honoring; fanout ordering (constants and end-to-end wave order); simulated-churn p99 bound
  • python3 -m compileall -q lab tests
  • git diff --check

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
Changes sit on the hot Stratum first-job and job-build paths (payout gate, delivery priorities, build scheduler), which are operationally critical though covered by extensive new regression tests rather than auth or ledger correctness.

Overview
Reduces multi-second first mining.notify tails when clients reconnect during publication-priority job builds and payout publications.

Initial-job delivery now probes the bundle cache before routine build admission, serves cached work immediately during priority builds, and on a miss subscribes to in-flight publication-critical build promises instead of polling the priority window and rebuilding. Payout-gate non-admission with a bundle in hand returns retryable None (within the request deadline) rather than disconnecting the client. Per-generation share-window serialization caches digest and compact audit-builder fragments so template-bump builds avoid repeated GIL-heavy window walks.

Delivery ordering matches documented behavior: PRISM_DELIVERY_PRIORITY_INITIAL outranks new-tip refresh, and tip-refresh fanout admits never-served clients first. PRISM_INITIAL_JOB_MAX_WORKERS and PRISM_JOB_BUILD_EXECUTOR_WORKERS are validated env knobs (with sensible caps), wired through Compose and docs, and exposed as configured-worker metrics; a new subscribed counter tracks initial jobs that rode a priority build.

Reviewed by Cursor Bugbot for commit 303b9e3. Bugbot is set up for automated code reviews on this repo. Configure here.

Five coordinated changes to the coordinator's initial-delivery path:

- Initial requests probe the bundle cache before routine build admission
  and, on a miss behind a publication-critical build, subscribe to that
  build's promise and consume its result at completion instead of
  0.05s-polling out the priority window and rebuilding from scratch.
- A payout-gate non-admission with a bundle in hand is now retryable
  within the request deadline instead of disconnecting the client,
  ending the disconnect-reconnect-rebuild churn during payout
  publications.
- The serialized share window (canonical sha256 plus the audit-builder
  compact payload fragments) is cached per (payout generation, artifact
  generation, window) and piped to the builder subprocess without
  re-encoding the share tree on every template bump.
- initial_job_max_workers and the shared job-build executor width are
  real env knobs (PRISM_INITIAL_JOB_MAX_WORKERS,
  PRISM_JOB_BUILD_EXECUTOR_WORKERS) with configured-worker gauges.
- Tip-refresh fanout serves never-served clients first: the delivery
  priority constants now match the documented ordering (initial ahead
  of the new-tip wave) and fanout admission itself is ordered.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@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: 3e045bb377

ℹ️ 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".

Comment thread lab/prism/prism_coordinator.py Resolved
The build scheduler admits at most two concurrent flights (one active,
one retiring), so executor threads beyond two can never receive work.
Reject higher settings at startup instead of accepting a silent no-op,
mirroring the PRISM_TIP_REFRESH_MAX_WORKERS precedent; lowering to one
remains a real serialization control for constrained hosts.

Raised by Codex review on #92.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@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: 111f71716c

ℹ️ 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".

Comment thread lab/prism/prism_coordinator.py Resolved
The dedicated first-job executor's queue is bounded by
PRISM_STRATUM_MAX_PENDING_INITIAL_JOBS, so workers beyond that count can
never receive a task, and unbounded values risked partially failed
thread creation leaving blocked workers behind a never-installed
executor. Reject the excess at startup like the other worker knobs.

Raised by Codex review on #92.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 26c5764fb0

ℹ️ 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".

The storm test released its blocked build as soon as the first worker
entered it. A straggling delivery worker still constructing its request
could then find the single-flight lane empty a moment before the winner
published the cache entry and legitimately start a second build,
failing the one-build assertion. The window is milliseconds wide; the
pre-admission cache probe added by this branch widened per-worker
request latency just enough to surface it under full-suite load
(observed at roughly one in four runs; never a coordinator defect).

Hold the release until the other three workers have coalesced onto the
in-flight build, pin the harness template/bundle TTLs past the test
lifetime (an expiry mid-storm forces a legitimate fresh build), and
budget the in-build release wait far past the slowest observed blocked
phase so a timeout cannot fail the flight from inside the executor.

Verified 10/10 consecutive full-suite runs clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

Pushed a test-determinism fix discovered while soak-testing this branch: the 250-client reconnect-storm test released its blocked build on first entry, leaving a milliseconds-wide race where a straggling worker could start a second (legitimate) build before the winner's cache publication — the pre-admission probe in this PR widened per-worker latency enough to surface it roughly once per four full-suite runs locally. The test now holds the release until the other three workers have provably coalesced onto the in-flight build, pins the harness TTLs past the test lifetime, and budgets the in-build wait generously. Coordinator behavior is unchanged; 10/10 consecutive full-suite runs clean after the fix.

@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Unknown error
ℹ️ 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".

@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: 505dd855e0

ℹ️ 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".

Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
Cap the implicit PRISM_INITIAL_JOB_MAX_WORKERS default at the
pending-client bound instead of failing startup for pre-knob
deployments that legitimately bound pending initial jobs below four;
explicit oversized settings still abort with the strict validator.

Serialize share-window cache entry creation under the slot lock so two
concurrent build flights cannot both walk the share tree on a shared
miss; the loser now waits briefly and reuses the winner's digest.

Raised by Codex review on #92.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@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: 347042e99c

ℹ️ 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".

Comment thread compose.yaml Resolved
Interpolating a default of 4 made every Compose deployment an explicit
setting, so the strict validator aborted startup for pending bounds
below four -- exactly the pre-knob configurations the implicit
min(default, pending) cap exists to keep booting. Pass the variable
through unset/empty; the coordinator treats empty as unset and resolves
the backward-compatible implicit default itself.

Raised by Codex review on #92.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 303b9e39e3

ℹ️ 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".

@RobertClarke
RobertClarke merged commit d3f8e95 into 1.x.x Jul 25, 2026
9 checks passed
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.

1 participant