Skip to content

Bound accepted-preview publication latency during dense accepted-tip cadence - #230

Merged
kiwidream merged 9 commits into
2.x.xfrom
issue-224/epic
Sep 4, 2026
Merged

kiwidream merged 9 commits into
2.x.xfrom
issue-224/epic

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • remove the full payout-window oracle rebuild from the successful accepted-preview reconciliation path by reusing the exact accepted-share window and rereading only live prior balances
  • retain the conservative reconcile_invalidation full rescan for unknown or ambiguous post-mutation outcomes
  • attribute definitive acceptance through visible preview publication across landing phases, reconciliation steps, full-rescan reasons, and ledger admission versus SQL execution with fixed-cardinality metrics
  • add deterministic dense accepted-tip cadence coverage and a real-PostgreSQL identity gate proving reconciliation-owned mutations do not rewrite qbit_share_ledger
  • document rolling-hour 4-second/5-second breach queries, bounded diagnostic correlation, and staged testnet/mainnet rollout criteria

Why

Union mainnet recorded 17 accepted-preview publications above 4 seconds and eight above the 5-second accepted-parent wait budget during a healthy, forward-progressing coordinator epoch. The slow samples correlated with landing-triggered reconcile_invalidation payout-window rebuilds, but the existing telemetry could not attribute the latency to a specific phase.

The confirmed reconciliation outcomes do not invalidate the accepted-share window: maturation, inactive quarantine, and reactivation mutate payout/current-balance state while leaving the share ledger intact. This change keeps the exact window and refreshes the balance input needed to publish an exact snapshot, removing the repeated O(window) oracle read from the normal accepted-preview critical path.

Safety

  • unknown or lost mutation results still fail closed through a true reconcile_invalidation full rescan
  • genuine window invalidations, daemon loss, late-visible appends, anchor/weight changes, and periodic oracle checks keep their conservative behavior
  • payout exactness, publication ordinals, accepted-parent fencing, restart/replay convergence, and stale-candidate fairness are unchanged
  • metric label values come only from frozen vocabularies; block identity stays in bounded diagnostics and structured logs
  • neither the 4-second alert threshold nor the 5-second child wait budget changes

Verification

  • final integrated 2.x.x: bound accepted-preview publication latency during dense accepted-tip cadence #224 telemetry/cadence/core/landing/ledger/metrics suites: 135 tests passed
  • final adjacent reconciliation/payout/finalization/candidate/share-ledger suites: 595 tests passed
  • full Linux unit discovery: 3,164 tests passed, two skipped
  • real PostgreSQL 16 ledger gate: all five gates passed, including share-ledger-identity=inactive+reactivate+mature
  • python3 -m compileall -q lab tests, bash -n test/test-prism-postgres-ledger.sh, and git diff --check origin/2.x.x...HEAD: passed

Rollout gates

The testnet cadence validation and Union mainnet soak are intentionally not claimed by this PR run. The operator guide now defines the exact shipped metrics, rolling-hour breach-count queries, and pass/fail criteria to use before and after rollout. A failed gate calls for rollback/escalation, not a higher threshold, longer wait, weaker payout exactness, or disabled conservative rescans.

Closes #224


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

kiwidream and others added 7 commits September 3, 2026 16:22
Issue #224, Wave 0. Union mainnet's accepted-preview publication tail
crosses the 4 s warning and 5 s child wait budget without anything on
/metrics naming the landing stretch that owns a sample. Three lanes will
instrument the core landing path, landing attribution and ledger
attribution in parallel; this commit is the shared surface they record
into, behavior-neutral and mergeable on its own.

lab/prism/accepted_preview_telemetry.py freezes the closed vocabularies
(landing sub-phases; reconcile callers and steps, spelled to join the
existing lookup family; payout-window full-rescan reasons mirrored from
payout_state's literals plus an ``other`` fold, and the daemon versus
in-process pipeline path; the ledger read operation names), a
thread-safe sum/count/max owner with context-manager timers, a bounded
per-publication diagnostic record and ring where a hash or height may
appear, ``fold_ledger_read_stats`` for the existing operation label, and
``ensure_accepted_preview_telemetry`` so every lane and the renderer
share one owner per coordinator without touching prism_coordinator.py.
The module docstring records the verified invariant: reconciliation
mutates pool-block and payout balance state but never qbit_share_ledger,
which the later reread-instead-of-rescan optimization relies on and this
wave does not implement.

The renderer appends four summary families -- landing phase, reconcile
pass, reconcile step, payout-window full rescan -- from an empty owner,
so every cell renders at zero from process start, and folds out-of-
contract ledger read operations into ``other``. Every pre-existing line
of the metrics document is unchanged: the base render is an exact prefix
of the new one. The frozen reference, parity seed and needles cover the
new families and the fold; a direct test module pins the vocabularies,
parses payout_state for reason drift, and checks the recorder, ring,
owner sharing and rendered labels.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GFRhW6iq62pKU8pGZSJskw
…iation

Issue #224: a reconcile pass that matured payouts, marked a pool block
inactive, or reactivated one answered with force_full_window_rescan, so the
accepted-preview landing paid an O(window) oracle read under the writer lock
for a window that had not changed. Reconciliation mutates pool-block, payout
and carry state but never qbit_share_ledger (the invariant recorded in
accepted_preview_telemetry), so at a fixed anchor the accepted-share window
stays exact and only the prior balances need a live read.

Core fix (Option A):
- Add a distinct force_prior_balances_read intent through
  _prepared_payout_state_candidate and _build_payout_ledger_artifact. It
  disables published-balance reuse and reads the carry aggregate live while
  the window goes through the normal debounce/delta path. It is never a
  full rescan and never records one.
- The reconciler's confirmed-mutation path now requests that reread
  (ReorgReconcilerService._candidate_intent); the intent keyword is only
  forwarded when set so pre-existing preparation and build seams keep
  their exact signatures.
- force_full_window_rescan keeps its whole meaning everywhere else: cold
  and cache invalidation, late-visible append, anchor/weight regression,
  daemon and incremental fallbacks, the periodic oracle, accepted-preview
  withdrawal, and the error-after-possible-commit path, which still
  republishes against a forced full rescan (and therefore fresh balances).

Attribution (fixed telemetry contract only):
- ReorgPorts gains an optional accepted_preview_telemetry owner; the
  coordinator wires ensure_accepted_preview_telemetry(self). Ports without
  one get a private owner.
- reconcile records qbit_prism_reorg_reconcile_pass_seconds{caller} on
  every exit and the step family (admission_wait, watch_query, chain_probe,
  mutations, candidate_prepare, publish) around the calls themselves.
- Callers are stamped per thread by the entry points -- landing (the
  flight-bypassing ensure_tip), post_confirm (forced publication),
  job_build (ensure_current), tip_refresh (the prefetch lane) and other --
  so the reconcile_with_admission / reconcile_serialized / ensure_tip seams
  keep their kwargs. Optional _caller keywords are accepted by the
  coordinator entry points for explicit attribution.
- payout_state records qbit_prism_payout_window_full_rescan_seconds
  {reason,path} only where the whole-window oracle actually runs: the full
  materialization (daemon vs in_process by which pipeline folded) and the
  periodic self-check.

Tests: tests/test_prism_issue_224_core.py covers the intent split, the
fail-closed paths, pass/step/caller observations on success and failure
exits, rescan reason/path recording, seam compatibility, and the
end-to-end coordinator path (maturation reuses the window, rereads and
publishes fresh balances, records no reconcile_invalidation rescan). The
two reconciler assertions that pinned the #112 forced rescan on the
confirmed-mutation path now assert the reread intent.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MgytztiBedDJPHGxnWnAqg
The publication histogram proves an acceptance-to-preview tail exists, but
nothing on /metrics said which stretch of the landing owned a sample above
the 4 s warning or the 5 s child wait budget. This instruments the existing
definitive-acceptance-to-publication path against the Wave 0 contract,
changing no payout, finalization, candidate, lock, retry, timeout or
publication behaviour.

The seven fixed phases are recorded where they actually run: lane_wait from
the acceptance stamp to the lane starting the landing task, balance_lock_wait
around the serializer acquisition (the plain `with` becomes an ExitStack so
only the acquisition is timed and the release point is unchanged), reconcile
around both inline ensure_reorg_reconciled_for_tip stretches,
prior_balances_check around the bracketed reread and the live
current_prior_balances comparison, chain_probe around pool-block-state,
tip-height-rpc and _block_candidate_chain_probe, preview_prepare around both
preview materializations, and preview_publish from entering the publish call
to the instant the preview becomes visible.

Per-hash state lives beside B1's acceptance stamps, under the same leaf lock
and bounded by the same cap with the same oldest-first eviction, and is
discarded on terminal abandonment and collapse withdrawal. It accumulates
only while a hash's interval is open, so a stretch that ran before definitive
acceptance and a retry's stretch after the interval closed reach the
process-wide family without ever being claimed by a landing's diagnostic.
The first publication -- published or degraded -- is the single point that
closes the interval, so it pops the record, builds one
AcceptedPreviewPublicationDiagnostic with reconcile caller=landing, and emits
one bounded JSON lifecycle line in the payout-artifact style, both outside
the leaf lock. Rescan and ledger totals stay at the contract's neutral
values: no per-landing causal evidence for either is available here without
a process-wide delta read that would claim another lane's work as this
block's. Hash and height appear in that diagnostic and log only; every
metric label is a fixed phase name.

Checks: tests.test_prism_block_finalization, tests.test_prism_block_candidates,
tests.test_prism_accepted_preview_telemetry, tests.test_prism_metrics,
tests.test_prism_issue_224_landing, the full `unittest discover -s tests`
suite (3107 tests, 2 pre-existing skips), compileall, and diff --check.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EgdzHvd8NL26qjYnmJncAn
The accepted-preview latency alert fired while the coordinator stayed
healthy, and nothing on /metrics said which stretch of the landing owned
the sample. Four ledger reads sit in that stretch, and each can be slow
for either of two unrelated reasons: coordinator-local admission behind
an accounting write, or PostgreSQL execution. One duration covering both
cannot tell an operator which -- the same ambiguity that misdiagnosed
#211 on the enumeration path before it was split.

Route those four through the attributed read helper the enumeration
already uses, under the operation names Wave 0 froze:

  snapshot_at_job_issue            -> payout_window_snapshot
  snapshot_between_job_issues      -> payout_window_delta
  current_prior_balances           -> current_prior_balances
  prior_balances_after_pool_block  -> prior_balances_after_pool_block

The helper was hard-wired to the read semaphore, so it is generalized
over the gate the caller already takes. That is the invariant most at
risk here: the prior-balances reread stays on the *writer lock*, where
it must observe the fenced state a payout mutation leaves behind, and
the other three stay on the bounded read slot. gate_name is the string
_operation_gate would have been given, so an expired admission still
names the primitive it was waiting for. No SQL text, result parsing,
thread, connection, retry, lock nesting or label value changes.

The legacy qbit_prism_prior_balances_* aggregate is left exactly as it
was -- one duration over admission and execution, recorded only on
success. It duplicates part of the new per-operation sample on purpose:
an operator comparing that existing series across this upgrade must not
find its meaning quietly redefined.

Operation names stay bare string literals at each call site because
tests.test_prism_accepted_preview_telemetry harvests them from this
file's source to fail on a name outside the closed vocabulary; imported
constants would leave that check with nothing to read.

tests/test_prism_issue_224_ledger.py drives the new module against real
Lock/BoundedSemaphore primitives behind a recording wrapper and a
scripted clock, so recorded seconds are exact and a released gate is a
fact about a primitive rather than a counter. It pins the fixed
operation per read, the gate each read keeps (proved from both sides,
including a refusing writer gate the read-slot reads never touch),
gate wait separated from execution, admission expiry as a gate timeout
with no execution sample, statement expiry as an execution timeout,
release-and-preserve on failure exits, a differential against the
pre-change admission body for byte-identical SQL and results, and the
fold that keeps an out-of-contract name from growing a series.

The two existing tests that call the helper directly gained the now
explicit gate arguments; their scenarios are unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GQRKR6tm627cizwNTZ81h2
Wave 1 answers a confirmed payout mutation with a live prior-balances
reread over the still-exact accepted-share window instead of the
O(window) oracle rescan. Its tests pin one mutation at a time; the alert
hour was a dense accepted-tip cadence.

tests/test_prism_issue_224_cadence.py drives consecutive trusted passes
through the real coordinator adapters over one frozen-anchor window while
the carry aggregate moves through a maturation, an inactive marking and a
reactivation, interleaved with quiet passes and with the post-confirm and
landing entry points. Per pass it records the preparation intent, the
ledger artifact, the published balances and the ledger reads, and pins
them against each other and against the fixed-cardinality telemetry:
mutating passes forward force_prior_balances_read=True with
force_full_window_rescan=False, reuse the very armed window object and
publish the live balances after exactly one attributed
current_prior_balances read; quiet passes prepare, read and publish
nothing; the rendered families carry only closed-vocabulary labels. A
lost maturation response mid-cadence still fails closed to the
reconcile_invalidation full rescan. The Wave 1 fixture gains an optional
ledger parameter so the cadence module reuses its setup.

test/test-prism-postgres-ledger.sh captures the exact identity of
qbit_share_ledger (every row in sequence order with ctid and xmin, plus
the sequence allocator) before block 66's reconciliation-owned mutations
and requires it back after each inactive quarantine, maturation sweep
and reactivation, while the owed balance proves each transition landed.
Its PASS summary names the invariant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SSg1LisJpnfCju56WjZrpM
…undaries

Issue #224, Wave 3 closeout. The integrated Wave 0/1/2 stack was reviewed
end to end from origin/2.x.x: confirmed reconciliation mutations request
force_prior_balances_read=True with force_full_window_rescan=False and
reuse the armed window object; the lost-response path still forces the
reconcile_invalidation full rescan; withdrawal, late-visible append,
anchor/weight regression, daemon loss and the periodic self-check keep
their reasons; landing attribution opens only at definitive acceptance,
is popped by the first published/degraded publication under the same
lock that tombstones the stamp, and a retry or republication after that
reaches the process-wide family only; every rendered label is drawn from
a closed vocabulary; the attributed ledger helper keeps each read on the
gate it already took with identical SQL, retry and release ordering; the
flight, fencing and replay paths are wrapped, not changed; and the dense
cadence and PostgreSQL identity proofs assert the successful and
ambiguous paths against distinct balance values and tuple identity. No
production or test defect was demonstrated, so no code changes.

docs/prism-overload-alerts.md gains the operator contract the rollout
needs to judge the 4 s warning and 5 s child-wait boundaries from the
shipped metrics: the verified signal inventory (histogram le="4"/le="5"
labels, the four attribution families, the ledger operation split, the
artifact event counter, the legacy carry aggregate and the backlog
gauges), the two bounded structured log lines that carry block identity,
bucket-derived rolling-hour breach counts with a subquery form for whole
soaks and the reason percentiles cannot prove a count, phase / caller /
step / rescan-reason / admission-versus-execution breakdowns, the
log-correlation recipe, the pre-deploy baseline and post-deploy testnet
cadence and Union mainnet soak checklist, the #224 pass/fail criteria,
and a fail-closed rollback/escalation decision that never raises the
alert, extends the child wait, weakens exactness or disables the
conservative rescan. It distinguishes the deliberate
reconcile_invalidation fallback from a successful balance-only reread and
notes open #207's separate window_daemon_state_lost scope.

docs/prism-ledger-ops.md now lists the four #224 read operations and the
writer-lock gate of current_prior_balances beside the existing read-slot
enumeration paragraph, and points at the new section.

Checks: the two focused unit groups (135 and 595 tests), compileall,
bash -n on the PostgreSQL gate, git diff --check, and the real Docker
PostgreSQL ledger gate (all five gates PASS, including
share-ledger-identity=inactive+reactivate+mature).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_014FMYTWWK1au9ptcu2sB4fq
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-04T15:23:28.128062Z 27aee1d Manual request
ℹ️ 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.

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

ℹ️ 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/block_candidates.py Resolved
Comment thread lab/prism/block_candidates.py Resolved
Codex review of #230 found two ways the attribution reports something the
landing did not do.

The publish span allocated an in-flight record for every publication,
including the startup replays and chain-proven candidates that publish
without an in-process acceptance stamp. The observer returns before it can
pop anything for those, and the span's exit only cleared its token, so each
one stayed in the bounded map as a publication permanently in flight -- and
a large enough replay evicted live landings from the cap before their
diagnostics were ever emitted. The record is now allocated only for an open
interval, and an interval that closed under the publication because its
stamp aged out of the shared cap drops it. The phase family still takes its
sample either way.

lane_wait closed after _mark_block_candidate_attempted, so the landing's own
PostgreSQL write was charged to queue time, and a marker that timed out kept
charging its retry backoff there too: the one stretch that exonerates the
landing grew precisely when the writer was degraded. Both queued paths now
close the lane before the marker write, leaving that write in the
unattributed remainder the operator guide already describes.
@kiwidream

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: 4fc5b111ff

ℹ️ 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/block_candidates.py Resolved
The previous commit moved lane_wait's close above the attempt marker, but
in doing so moved it above _node_submission_for_candidate_or_retained as
well -- and that call is where a fresh candidate gets its definitive
acceptance stamp, inside _submit_block_candidate_to_node. The close then
found no open interval and returned, so every first-pass queued landing
published a diagnostic with no lane_wait sample at all. A zero sample and a
missing sample are indistinguishable in the per-landing diagnostic, so the
loss would only have shown up as the family count trailing the accepted
block count.

Both queued paths now close the lane on either side of the offer.
_close_accepted_landing_lane_wait is already once-per-open-interval, so the
second close is a no-op when the first recorded: a candidate carrying a
retained acceptance keeps the earlier, tighter sample that excludes this
landing's own work, and a fresh candidate reports the zero queue time it
genuinely had. Both closes stay above the attempt marker, so that write is
still outside lane_wait.

The ordering guard now also requires a close after each path's last node
offer, which is what fails against the previous commit.
@kiwidream

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: 27aee1dfa3

ℹ️ 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/payout_state.py Resolved
Comment thread lab/prism/metrics.py Resolved
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