Repository navigation
Attribute in-process lease-monitor stalls and decide the lateness response (#227) - #233
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b900ab799
ℹ️ 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".
|
|
||
| def window_max_seconds(self, now: float) -> float: | ||
| """Largest lateness observed inside the trailing window.""" | ||
| oldest = int(now // self._slice_seconds) - len(self._slice_max) + 1 |
There was a problem hiding this comment.
Keep the oldest partial slice in the rolling window
When now crosses a 10-second slice boundary, the + 1 excludes the entire slice 29 positions behind even though most observations in that slice are still less than 300 seconds old. For example, an observation at 0.1 disappears at 300.0 while it is only 299.9 seconds old, so the advertised trailing-300-second maximum can clear up to one slice early and briefly hide a recent stall.
Useful? React with 👍 / 👎.
| or now - self._window_started >= self.window_seconds | ||
| ): | ||
| self._window_started = now | ||
| self._admitted = 0 |
There was a problem hiding this comment.
Enforce the rate limit over a sliding window
Resetting the counter at the fixed-window boundary does not enforce the documented limit of three samples in any 60-second interval. For example, admissions at 0, 59.8, and 59.9 seconds allow another three immediately after 60 seconds, producing five stack walks and warning threads in a sub-second burst; this can amplify the stall the limiter is intended to contain.
Useful? React with 👍 / 👎.
| stacks: str | None = None | ||
| if probe_admitted: | ||
| stacks = self.stall_probe.capture(now=now, wake_delay_seconds=wake_delay) |
There was a problem hiding this comment.
Avoid attributing a deferred stack snapshot to the past stall
For a transient GIL-holding operation that finishes before the monitor wakes, this capture runs even later on a newly scheduled diagnostics thread, after the suspected thread has resumed and may have left the responsible frame. The resulting stacks therefore cannot reliably identify what held the interpreter during the measured delay and may misdirect incident diagnosis; this needs an independent sampler or must be exposed as a post-wake snapshot rather than stall attribution.
Useful? React with 👍 / 👎.
…ponse (#227) `PrismWriterLeaseMonitorWakeDelayHigh` fired on mainnet with a 0.648 s monitor wake delay against a 0.50 s scheduler slack, on a host that was 93% idle with PSI near zero. The stall was in-process, and none of the existing telemetry could say so: `guard_sql` is measured client-side, so a GIL stall between PostgreSQL answering and the heartbeat thread resuming was booked as database time (0.714 s, above the 0.50 s server-side statement timeout), while `scheduler_delay` never exceeded 22 microseconds in 645k attempts. Attribution that survives a GIL stall. Both guard statements now return a server-side `clock_timestamp()` delta, so `guard_sql` splits into server execution and client resume and the residual is charged to the scheduler. The split is clamped with `min(statement_span, server_seconds)` so a clock skew cannot manufacture negative client time. The attribution recheck re-runs the same SQL, so a two-statement attempt reports both. A distribution instead of a lifetime high-water mark. The old gauge never reset, so every stall below the record was invisible and the alert could not fire again. Added a fixed-bucket histogram of monitor wake delay, counters of wakes at or above 0.5, 0.8 and 1.0 times the slack, a rolling-window maximum, and the age of the current record. The original gauge is kept for dashboard continuity. The counters are what let the alert be re-expressed on a counter rather than a never-resetting gauge. GC and stall instrumentation. `gc.callbacks` records pause duration per generation as a histogram plus a last-pause gauge, and a rate-limited stall probe samples running threads when a wake exceeds half the slack. The lateness response, and why. Lateness beyond the slack is accepted rather than converted into a tightened server-proven cap for that beat. Tightening would hard-exit healthy coordinators under a transient stall — issue #212 — without moving the exit any earlier on the beat that actually breached, and every effect that could escape during the uncovered interval is already fenced at the row or behind a synchronous exact-session verification. What changes is that the breach is no longer invisible: it is counted, its overrun past `max_guaranteed_monitor_lateness` is kept, one rate-limited structured warning names it, and a stack sample says what held the interpreter. The reasoning is recorded in the `writer_lease_timing` module docstring, which previously presented `cap + monitor_interval + scheduler_slack + exit_margin = 1.95 < 2.00` as if the slack term bounded reality; production exceeded it. The instrument stays off the exit path. Accounting one wake is O(1) arithmetic on the monitor thread; everything that walks frames, formats text or writes a log line is returned as a closure that `monitor_loop` runs only after the exit decision, and drops entirely when the decision is to exit. A measurement that extended the envelope it reports on would consume the very budget it exists to protect. The stack sample walks frame objects directly and never touches `linecache`: `traceback.extract_stack` would stat every file and read every source line for text this sample does not print, and even `StackSummary.extract(lookup_lines=False)` still calls `linecache.checkcache` per file. Safety constraints from #212 are preserved: the heartbeat is not disabled, no failure budget was raised on its own, and PostgreSQL durability is untouched. Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
6b900ab to
df75dac
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df75dac02a
ℹ️ 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".
| thread = threading.Thread( | ||
| target=job, | ||
| name="prism-ledger-lease-monitor-diagnostics", | ||
| daemon=True, | ||
| ) |
There was a problem hiding this comment.
Bound the diagnostics worker count
When the log callback blocks—an explicitly anticipated case for _print_line—each subsequent admitted late wake creates another daemon thread, while the rate limiter caps only creation rate rather than the number of live workers. A sustained log-pipe blockage can therefore accumulate three permanently blocked threads per minute until process resources are exhausted; additionally, Thread.start() waits for the child bootstrap synchronously on the lease monitor, so startup delays are excluded from the next wake-lateness measurement while still postponing its next fencing decision. Use a bounded worker or allow only one in-flight diagnostics job.
Useful? React with 👍 / 👎.
Summary
PrismWriterLeaseMonitorWakeDelayHighfired onunion-mainnetat 2026-09-0410:28Z with a monitor wake delay of 0.648 s against a
scheduler_slackof0.50, on a host that was 93% idle with PSI near zero, steal 0 and
nr_throttled0. The stall was in-process, and nothing on/metricscould sayso. This makes in-process stalls attributable, replaces the lifetime high-water
mark as the primary signal, and settles what the coordinator does when its own
lateness exceeds the slack.
Stacked on #232 (#226 part 1), which is its merge base — that PR's telemetry
module and family-set test are extended here. Review #232 first.
What changed
Attribution that survives a GIL stall. Both guard statements now return a
server-side
clock_timestamp()delta alongside client wall time, soguard_sqlsplits into server execution and client resume and the residual is charged to
the scheduler. The split is clamped with
min(statement_span, server_seconds)so clock skew cannot manufacture negative client time, and the attribution
recheck re-runs the same SQL so a two-statement attempt reports both. The guard
statement stays non-blocking — nothing was added that can queue on the
qbit_ledger_writer_leasetuple lock — and the conservative send-edge stampingthat the exit-before-adoption proof depends on is unchanged.
A distribution instead of a lifetime maximum. A fixed-bucket histogram of
monitor wake delay, counters of wakes at or above 0.5, 0.8 and 1.0 x
scheduler_slack, a rolling-window maximum, and the age of the current record.The original gauge is kept for dashboard continuity.
GC and stall instrumentation.
gc.callbacksrecords pause duration pergeneration as a histogram plus a last-pause gauge; a rate-limited stall probe
samples running threads when a wake exceeds half the slack.
Why, citing the issue's production evidence
Worst phases at capture were
guard_sql0.713834,guard_slot_wait0.000106,
scheduler_delay0.000022, against aguard_statement_timeoutof0.50. A client-measured
guard_sqlabove the server-enforced timeout is onlypossible if time is being counted that PostgreSQL did not spend — and
scheduler_delaynever exceeded 22 microseconds across 645,825 proof attempts,so the existing attribution structurally could not see the stalls the monitor
gauge saw. "Look at PostgreSQL or at the coordinator" was not answerable from the
metrics. It is now.
The gauge was also a lifetime maximum with no timestamp, count or distribution:
after one 0.648 s record, every later stall below it was invisible and the alert
could not fire again.
The safety consequence is the reason this is not merely an observability change.
The inequality in
writer_lease_timing.pyiscap + monitor_interval + scheduler_slack + exit_margin = 1.95 < 2.00. At the observed 0.648 s latenessthe sum is 2.098 > 2.00: for the duration of that stall, exit-before-adoption
was not guaranteed. No guard loss coincided, so nothing happened — but the
assumption the policy rests on was exceeded in production three days after #214
shipped, and that docstring did not say so.
Safety and rollout
The lateness response, and the argument for it. Lateness beyond the slack is
accepted rather than converted into a tightened server-proven cap for that
beat. Tightening would hard-exit healthy coordinators under a transient stall —
exactly issue #212 — without moving the exit any earlier on the beat that
actually breached, and every effect that could escape during the uncovered
interval is already fenced at the row or behind a synchronous exact-session
verification. What changes is that the breach stops being invisible: it is
counted, its overrun past
max_guaranteed_monitor_lateness(slack plus onemonitor interval) is kept, one rate-limited structured warning names it, and a
stack sample says what held the interpreter. The reasoning is recorded in the
writer_lease_timingmodule docstring, which previously presented 1.95 < 2.00as if the slack term bounded reality.
The instrument stays off the exit path. Accounting one wake is O(1)
arithmetic on the monitor thread. Everything that walks frames, formats text or
writes a log line is returned as a closure that
monitor_loopruns only afterthe exit decision, and drops entirely when the decision is to exit. A
measurement that extended the envelope it reports on would consume the budget it
exists to protect. The stack sample walks frame objects directly and never
touches
linecache:traceback.extract_stackstats every file and reads everysource line (~7 ms and ~3.7 MB retained, measured) for text this sample does not
print, and even
StackSummary.extract(lookup_lines=False)still callslinecache.checkcacheper file.Constraints from #212 preserved: the heartbeat is not disabled, no failure
budget was raised on its own, and PostgreSQL durability is untouched.
Operator visibility: all new families are fixed-cardinality and pinned by the
family-set test.
slack_breach_warnings_suppressedis exported, so arate-limited flood is distinguishable from a quiet period.
Review findings addressed
/code-reviewraised five issues; all five are fixed:lease_hard_exit, adding stack walking and a thread spawn to the exit-criticalpath on exactly the late beat they were added to measure;
traceback.extract_stackdefaulted tolookup_lines=True, doing anos.statper frame and full source reads on the monitor thread of a process already at
17.7 GB;
GcPauseTelemetry.recordbumped buckets before_countwhilesnapshotreadbuckets before count, so a scrape could render a
lebucket above+Inf;guard_sqlabove 0.5 s "is no longer possible" was false —the two-statement recheck sums two server times and can reach ~1.0 s;
suppressed_slack_breach_warningswas incremented but exported nowhere.Verification
Run locally on macOS (Darwin 25.4.0, Python 3.14.3) on this branch:
bash -n, shellcheck and compileall clean. The suite is 3223 tests, failures=2errors=3 skipped=4; the five failures are the documented macOS
os.splicesetin
test_prism_job_builder, which pass on Linux CI and are identical to thisbranch's merge base.
The required acceptance test is
test_prism_lease_monitor_stalls: the deterministic harness injects a 0.65 sscheduler stall inside a guard round trip on a virtual clock, and the new
attribution reports it as scheduler time rather than
guard_sql.Not verified here: the #192 storm instrument's worst GC pause was measured on the
worker's Linux host, not this one, and pause absolutes are host-specific — the
mechanism is pinned by test, the number is not a property of the code. Nothing
was run against production.
Follow-ups, not in this PR
on 2.x.x: scope the writer lease per role so a stuck block landing cannot halt the pool #130; it is deliberately not built here.
qbit-prism-lease-monitor-wakeshould be re-expressed on a counter rather than the never-resetting gauge. That
lives in another repository.
Closes #227
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.