Skip to content

Attribute in-process lease-monitor stalls and decide the lateness response (#227) - #233

Merged
kiwidream merged 1 commit into
2.x.xfrom
attribute-lease-monitor-stalls
Sep 4, 2026
Merged

kiwidream merged 1 commit into
2.x.xfrom
attribute-lease-monitor-stalls

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Summary

PrismWriterLeaseMonitorWakeDelayHigh fired on union-mainnet at 2026-09-04
10:28Z with a monitor wake delay of 0.648 s against a scheduler_slack of
0.50, on a host that was 93% idle with PSI near zero, steal 0 and
nr_throttled 0. The stall was in-process, and nothing on /metrics could say
so. 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, 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 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_lease tuple lock — and the conservative send-edge stamping
that 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.callbacks records pause duration per
generation 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_sql 0.713834, guard_slot_wait
0.000106, scheduler_delay 0.000022, against a guard_statement_timeout of
0.50. A client-measured guard_sql above the server-enforced timeout is only
possible if time is being counted that PostgreSQL did not spend — and
scheduler_delay never 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.py is cap + monitor_interval + scheduler_slack + exit_margin = 1.95 < 2.00. At the observed 0.648 s lateness
the 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 one
monitor 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_timing module docstring
, which previously presented 1.95 < 2.00
as 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_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 budget it
exists to protect. The stack sample walks frame objects directly and never
touches linecache: traceback.extract_stack stats every file and reads every
source line (~7 ms and ~3.7 MB retained, measured) for text this sample does not
print, and even StackSummary.extract(lookup_lines=False) still calls
linecache.checkcache per 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_suppressed is exported, so a
rate-limited flood is distinguishable from a quiet period.

Review findings addressed

/code-review raised five issues; all five are fixed:

  • the stall probe and breach warning ran before the staleness check and
    lease_hard_exit, adding stack walking and a thread spawn to the exit-critical
    path on exactly the late beat they were added to measure;
  • traceback.extract_stack defaulted to lookup_lines=True, doing an os.stat
    per frame and full source reads on the monitor thread of a process already at
    17.7 GB;
  • GcPauseTelemetry.record bumped buckets before _count while snapshot read
    buckets before count, so a scrape could render a le bucket above +Inf;
  • a docs claim that guard_sql above 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_warnings was incremented but exported nowhere.

Verification

Run locally on macOS (Darwin 25.4.0, Python 3.14.3) on this branch:

touch .env
git ls-files '*.sh' | xargs bash -n
git ls-files '*.sh' | xargs docker run --rm -v "$PWD:/mnt:ro" -w /mnt \
    koalaman/shellcheck:stable -x
python3 -m compileall -q docker lab tests examples scripts
GIT_CONFIG_GLOBAL=/dev/null python3 -m unittest discover -s tests -p 'test_*.py'

bash -n, shellcheck and compileall clean. The suite is 3223 tests, failures=2
errors=3 skipped=4
; the five failures are the documented macOS os.splice set
in test_prism_job_builder, which pass on Linux CI and are identical to this
branch's merge base.

The required acceptance test is
test_prism_lease_monitor_stalls: the deterministic harness injects a 0.65 s
scheduler 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

Closes #227

2.x.x is not the default branch, so this will not auto-close. #227 needs
closing by hand after merge.


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

@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-04T19:24:41.091876Z df75dac New commits
ℹ️ 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: 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

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

Comment on lines +645 to +648
or now - self._window_started >= self.window_seconds
):
self._window_started = now
self._admitted = 0

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

Comment on lines +1940 to +1942
stacks: str | None = None
if probe_admitted:
stacks = self.stall_probe.capture(now=now, wake_delay_seconds=wake_delay)

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 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]>
@kiwidream
kiwidream force-pushed the attribute-lease-monitor-stalls branch from 6b900ab to df75dac Compare September 4, 2026 19:20

@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: 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".

Comment on lines +1895 to +1899
thread = threading.Thread(
target=job,
name="prism-ledger-lease-monitor-diagnostics",
daemon=True,
)

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

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