Skip to content

Reduce PRISM shared tip-refresh bundle latency - #58

Merged
kiwidream merged 2 commits into
1.x.xfrom
optimize-tip-refresh-bundle
Jul 18, 2026
Merged

kiwidream merged 2 commits into
1.x.xfrom
optimize-tip-refresh-bundle

Conversation

@kiwidream

@kiwidream kiwidream commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

Summary

  • precompute an immutable ledger/payout artifact and publish it atomically with its exact payout generation, so a valid artifact removes PostgreSQL snapshot and balance work from the timed tip-specific path
  • keep shared builds keyed by template fingerprint, previous block hash, template/artifact/payout generations, mode, and collection identity; use keyed single-flight preparation so a newer work identity never queues behind an obsolete global build
  • terminate and reap audit builders when their tip or payout generation is superseded, and fail closed on timeout, crash, stale artifact, or stale result
  • replace the job-summary subprocess payload with an identity-interned compact representation while retaining the canonical full-input path and byte-for-byte job-summary parity
  • reduce the PostgreSQL reward-window cutoff query from one recursive row per share to bounded 4,096-row pages, while preserving the exact cutoff row and canonical ordering
  • expose bounded phase, queue, inflight, single-flight, supersession, worker failure/restart, and IPC byte metrics

Why this design

Profiling a 1,000,000-share refresh showed that serialization/copying dominated: the old builder input was 380.7 MB. The compact job-summary representation reduces that input to 70.8 MB. The deterministic Rust stage is already isolated behind an exec-style subprocess; adding another long-lived multiprocessing layer would retain the copying cost and expand key access. This patch therefore keeps signing behavior and the existing process boundary unchanged, explicitly closes inherited file descriptors, and adds a fail-closed timeout instead of introducing another worker pool.

The keyed flight implementation admits different work identities independently. Identical requests still coalesce, while a new tip/template/payout generation can start immediately and cancels the obsolete subprocess. Artifact preparation is bounded to one thread and one latest-generation request slot.

Benchmarks

All runs used the release Rust builder, 16 clients, the benchmark's production-derived injected I/O latencies, and 128 payout identities routed through CTV settlement.

Dataset Base 1.x.x This change Result
132,000 shares, 3 runs, full refresh p50 1.7877 s 1.4386 s 19.5% faster
1,000,000 shares, no injected I/O, full refresh 7.4395 s 4.2850 s 42.4% faster
1,000,000-share builder input 380.7 MB 70.8 MB 81.4% less IPC input

Target-sized prepared-artifact validation used 21,868 shares, 128 CTV payout identities, and five independent runs:

  • full refresh p50: 0.9386 s
  • tip-to-first-delivery p50: 0.9325 s
  • tip-to-last-delivery p50: 0.9335 s
  • builder IPC: 1,526,043 input bytes / 1,869 output bytes

Every target-sized sample completed under one second. Supersession tests additionally prove that a blocked old generation is canceled and cannot publish or retain a result.

Correctness and safety

  • compact and full CLI inputs produce the exact same golden job-summary bytes
  • prepared-artifact and inline paths produce the same base job, coinbase manifest, share window, prior balances, and found-block data
  • accepted-share counts fence artifact preparation and artifact use; any concurrent ledger mutation discards the artifact/result
  • cache and flight keys include all consensus-relevant template, tip, payout, artifact, mode, and collection-worker inputs
  • completed bundles are revalidated against current tip, template generation, payout generation, artifact identity, readiness mode, and delivery admission before cache or delivery
  • builder children receive only serialized immutable inputs, run with close_fds=True, and never receive coordinator sockets, locks, clients, or database objects
  • no disconnect, connection-limit, vardiff, stale-grace, block-acceptance, payout-delivery, signing, settlement, or canonical-audit behavior is changed

Validation

  • 302 focused coordinator, startup delivery, reconnect backpressure, tip refresh, immutable artifact, CTV priority, and ledger tests
  • 181 qbit-prism Rust tests across all targets
  • PostgreSQL ledger integration with both the psql fallback and production psycopg client
  • Dockerized ShellCheck, bash syntax, and Python compilation
  • all Docker Compose profiles validate
  • Rust formatting passes

Deterministic coverage includes identical single-flight deduplication, blocked-old/new-generation supersession, obsolete-result rejection, compact/full and artifact/inline parity, subprocess crash/timeout recovery, inherited-socket rejection, repeated supersession bounds, and immediate first delivery from a valid prepared artifact.


Note

Medium Risk
Changes sit on the payout/job-build hot path (ledger snapshots, subprocess signing, cache keys, and supersession) where bugs could delay work or serve stale bundles, but parity tests and fail-closed fencing aim to preserve deterministic audit output.

Overview
This PR targets PRISM ready-pool tip refresh latency by moving ledger work off the critical path and making shared bundle builds cheaper and easier to abandon when tips or payout generations move.

The coordinator can precompute and publish a PayoutLedgerArtifact (bounded share window + prior balances, fenced by accepted-share counts) and stamp job-bundle cache keys with tip hash, payout generation, and artifact generation. Valid artifacts skip PostgreSQL snapshot/balance work during timed refreshes; a single-threaded preparer keeps scheduling bounded.

Shared bundle preparation now uses per-identity single-flight with subprocess cancel/terminate on superseded tip or payout generation, PRISM_BUNDLE_BUILD_TIMEOUT_SECONDS fail-closed timeouts, close_fds on audit-builder children, and stricter discard rules before cache or delivery. Job-summary builds send a compact, identity-interned share payload to qbit-prism-build-audit-bundle (full canonical input unchanged); the Rust CLI adds --phase-metrics and profile_audit_build phase timings fed back into coordinator metrics.

PostgreSQL reward-window selection switches from per-share recursive probes to 4,096-row pages with the same cutoff semantics. Rust compute_prism_window uses HashSet duplicate detection and an O(n) reverse when shares are already ascending. Observability expands with tip-refresh build phase histograms, queue/inflight/single-flight/supersession counters, and builder IPC byte totals; the job-build benchmark gains miners, CTV settlement, and precompute-artifact modes.

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


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

@kiwidream
kiwidream merged commit 0dc8a61 into 1.x.x Jul 18, 2026
9 checks passed

@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: df3332d517

ℹ️ 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 on lines +9594 to +9596
record_phase_metrics = bool(
getattr(self._job_build_phase_local, "tip_refresh_metrics", False)
)

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 Initialize job-build state before reading metrics scope

When build_audit_bundle() is called on focused/alternate coordinator instances that have not gone through __init__ or _ensure_job_cache_state() yet, this new direct access to _job_build_phase_local raises AttributeError before the builder subprocess is invoked. That breaks the existing __new__-based tests and any lightweight coordinator path that previously could call build_audit_bundle() directly; call _ensure_job_cache_state() first or guard the attribute lookup.

Useful? React with 👍 / 👎.

RobertClarke pushed a commit that referenced this pull request Jul 18, 2026
Reconcile the tip publication boundary (build/validate before submit
authority moves) with 1.x.x's short publication lane (#58), bounded
build supersession (#57), superseded-vs-blocked budget taxonomy (#56),
and delivery priorities:

- keep construction outside the publication lane, then run the PR's
  final validation and atomic prepared publication inside it
- drop the base's early tip publication before template fetch; the
  poll now only records a detection there
- compare build-pipeline supersession gates against the newest
  detected tip so a replacement build for a detected-but-unpublished
  tip can cache and publish itself
- cancel obsolete bundle/job builds at detection time
- clear retained ready bundles when publication flips the tip
- classify prepared-publication races as TemplateRefreshSuperseded so
  coordination churn cannot arm the restart budget
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