Skip to content

Export always-on heap and component-cardinality telemetry (#226 part 1) - #232

Merged
kiwidream merged 1 commit into
2.x.xfrom
prism-heap-and-cardinality-telemetry
Sep 4, 2026
Merged

kiwidream merged 1 commit into
2.x.xfrom
prism-heap-and-cardinality-telemetry

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Issue #226 recorded the mainnet coordinator at 17.69 GB RSS after 45 h of ordinary
load, growing about 390 MB/h from a 125-145 MiB startup baseline, with nothing on
/metrics able to say whether that growth is live Python objects, pymalloc
fragmentation, or glibc arena fragmentation. This lands the always-on instrument
that discriminates between those hypotheses, plus the component-cardinality gauge
list.

This is part 1 of 2 for #226, and that split is deliberate. The telemetry lands
first so the census, the allocator experiment and the eventual fix (part 2) build on
a settled metrics.py and a settled family-set test, and so the concurrent
monitor-stall work for #227 extends the same reference test rather than racing it.
Expect a second PR against #226.

These gauges are also the acceptance instrument #185 asked for: its component list
is covered in full, item by item, in docs/prism-capacity-readiness.md.

What changed

lab/prism/process_telemetry.py (new) collects sys.getallocatedblocks(),
gc.get_count() and gc.get_stats() per generation, threading.active_count(),
and glibc mallinfo2 arena / in-use / free / mmapped bytes through ctypes. The
binding resolves once per collector; an absent or call-time-broken symbol is
remembered and never re-probed or logged. The collector never walks the heap — no
gc.get_objects(), no tracemalloc — which is pinned by a test that patches both
to raise.

The older int-typed mallinfo is deliberately not used as a fallback: its
32-bit fields wrap on a multi-gigabyte heap, which is precisely this issue's heap.

lab/prism/metrics.py renders 13 new families: 11 process families (only the GC
ones carry a label, the closed three-value generation set) and
qbit_prism_component_entries / qbit_prism_component_bytes over a closed
component label set. Component reads are direct attribute loads on the shipped
owners, so a renamed field fails a test loudly instead of reporting a silent zero.

lab/prism/coordinator_config.py adds PRISM_MALLOC_TELEMETRY (default on, strict
boolean, validated at startup) gating only the mallinfo2 call. compose.yaml
passes it through and .env.example documents it.

Why, citing the issue's production evidence

The map shape in #226 — 943 anonymous regions totalling 23.4 GB, of which 658 are
in the 4-64 MiB band
across 64 threads, plus one 3.9 GB [heap] — is the
glibc per-thread-arena signature (HEAP_MAX_SIZE is 64 MiB), not a few large
buffers. Neither the image nor the deployment sets MALLOC_ARENA_MAX or
PYTHONMALLOC. Distinguishing that from ordinary retention needs arena bytes next
to in-use bytes and a live allocation count, which is exactly what the heap block
exports; docs/prism-capacity-readiness.md gives the four-step reading order.

qbit_prism_process_allocated_blocks rising with RSS is retention;
arena_bytes - in_use_bytes rising with a high thread count is glibc arena
fragmentation, the shape #226 captured.

Safety and rollout

  • Default on, and cheap by construction: every reading is a counter load except
    mallinfo2, which is the sole reason the switch exists.
  • Fixed cardinality. No label carries a job id, tip hash, generation or worker
    name. A test grows jobs, tips, candidate hashes, generations and workers by five
    each and asserts the series set is byte-identical before and after.
  • Degrades cleanly off glibc. macOS, musl and glibc before 2.33 render
    qbit_prism_process_malloc_info_available 0 with all four byte gauges at -1,
    never 0 — a zero arena on a 17 GB process is a lie an operator would act on. The
    family set is identical on every platform so one dashboard serves both. Verified
    on macOS, which genuinely lacks the symbol.
  • Fail-safe switch read. The renderer resolves PRISM_MALLOC_TELEMETRY once at
    construction and falls back to the shipped default if the value has become invalid
    since startup. The strict reader exits the process, which is right at startup and
    wrong on a metrics thread: an observability knob must not be able to cause an
    outage.
  • No coordinator changes. Every component size was reachable through existing
    accessors, so prism_coordinator.py is untouched.
  • Operator note: the mainnet deployment sets the coordinator's environment from
    its own configuration rather than from .env, so turning the switch off there
    needs the same variable added on that side.

Review findings addressed

/code-review raised seven issues on the first draft; all seven are fixed in this
branch. The substantive ones:

  • Double-counted payout window. A mirror-backed window was reported under both
    payout_window_* and daemon_window_mirror_*, so summing
    qbit_prism_component_bytes for RSS attribution counted the window twice — on the
    Rust path, which is what mainnet runs. The window is now accounted exactly once,
    and the property is pinned as a sum so a future backing cannot reintroduce it.
    Which pair is non-zero is now also how an operator reads the active backing.
  • SystemExit reachable from the metrics thread on an invalid switch value —
    fixed as described above.
  • On-disk spool reported as resident bytes. share_window_serialization_spool
    is a temporary file, not RSS; HELP text and docs now say so.
  • A tolerant getattr that broke the fail-loudly promise, a docstring claiming O(1)
    reads where one is O(pages), and the switch missing from .env.example and the
    compose allowlist.

Refuted during implementation

There is no in-process hashrate rollup buffer to gauge, so no gauge was invented
for one. hashrate_rollup_maintenance_loop folds each batch inside PostgreSQL
through advance_hashrate_rollups and retains nothing between passes; the public
hashrate series cache from #218/#219 lives in a separate process. The docs record
why the family is absent.

Two registries stand out as census targets for part 2 and were deliberately not
changed here: _block_candidate_terminal_outcomes, whose own docstring records
312,000 entries after one testnet4 storm and describes its bound as a target rather
than a ceiling, and _accepted_block_preview_acceptance_monotonic, which keeps a
tombstone per observed hash by design. Both are now exported.

Verification

Run locally on macOS (Darwin 25.4.0, Python 3.14.3), on this branch rebased onto
c3ca8bb (#225, itself on top of #230):

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 are clean. The suite is 3191 tests, failures=2
errors=3 skipped=4
: the five failures are the documented macOS os.splice set in
test_prism_job_builder (test_daemon_splice_failure_poisons_spool_and_one_shot_recovers,
test_mid_stream_splice_failure_poisons_spool_for_later_builds,
test_splice_failure_poisons_spool_and_falls_back_to_pipe,
test_spool_creation_failure_falls_back_to_pipe_writes,
test_spool_feeds_builder_and_is_written_once_per_generation), which pass on Linux
CI and are identical to this branch's merge base. Two of the four skips are the
glibc-only collector tests skipping correctly on macOS.

Independently checked beyond the suite: the rendered family count goes 240 to 253
with nothing removed, and a macOS render shows malloc_info_available 0 with all
four byte gauges at -1 while the interpreter gauges stay real.

Not verified here: behaviour on musl; the cost of mallinfo2 on a fragmented
multi-gigabyte heap with 64 arenas (the pinned test asserts the mechanism, not a
duration, because timing absolutes are host-specific); and any value on a live
coordinator — nothing in this change was run against production.

Closes #226

2.x.x is not the default branch, so this will not auto-close. #226 needs closing
by hand after merge, and only once part 2 has landed.

@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-04T18:21:51.299496Z e8f5e60 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: 8c87e72fb0

ℹ️ 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/metrics.py
Comment on lines +287 to +290
enabled = getattr(port, "malloc_telemetry_enabled", None)
if enabled is None:
try:
enabled = env_malloc_telemetry()

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 Read the validated malloc switch from the config snapshot

When PrismCoordinator is constructed with an explicit CoordinatorConfig, the validated value exists only at config.lifecycle.malloc_telemetry_enabled; the coordinator never copies it to malloc_telemetry_enabled. Consequently this lookup falls through to the ambient process environment, so a caller passing a snapshot with telemetry disabled can still execute mallinfo2 (and a valid environment change between startup and the first render overrides the startup-validated value). Read the lifecycle snapshot through port.config or publish that value on the coordinator.

Useful? React with 👍 / 👎.

Comment thread lab/prism/metrics.py Outdated
Comment on lines +986 to +990
"# HELP qbit_prism_process_gc_pending_objects Objects tracked by the cyclic collector since its generation was last collected (gc.get_count), by generation.",
"# TYPE qbit_prism_process_gc_pending_objects gauge",
*[
f'qbit_prism_process_gc_pending_objects{{generation="{generation}"}} {int(count)}'
for generation, count in zip(PRISM_GC_GENERATIONS, sample.gc_pending)

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 Do not report GC collection counts as pending objects

In the shipped Python 3.14 image, gc.get_count() exposes collection-trigger counters—principally allocations minus deallocations—not the number of objects tracked in each generation; Python 3.14 also no longer has generation 1. Labeling these samples gc_pending_objects{generation=...} makes the operational guidance interpret internal trigger state as retained objects and recommends using the generation-2 value as a backlog signal, which can produce incorrect heap-leak conclusions. Rename and document the values according to their actual collection-counter semantics.

Useful? React with 👍 / 👎.

@kiwidream
kiwidream force-pushed the prism-heap-and-cardinality-telemetry branch from 8c87e72 to cbd5696 Compare September 4, 2026 16:43

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

ℹ️ 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 docs/prism-capacity-readiness.md Outdated
Comment on lines +244 to +247
`qbit_prism_process_malloc_in_use_bytes` against
`qbit_prism_process_resident_memory_bytes`. All three rising together is
retention: something is holding objects. RSS rising while allocated blocks
and in-use bytes stay flat is fragmentation.

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 Include mmapped allocations in the retention check

When a retained allocation is large enough for glibc to serve it via mmap (for example, a native buffer that grows in place), mallinfo2 records its bytes in hblkhd, exported here as qbit_prism_process_malloc_mmapped_bytes, rather than in uordblks/qbit_prism_process_malloc_in_use_bytes. RSS can therefore rise while both quantities recommended here remain flat, causing this runbook to diagnose fragmentation—or later blame pymalloc/the child—even though this process is retaining mmapped chunks. Include the mmapped gauge in this decision before drawing that conclusion.

Useful? React with 👍 / 👎.

Issue #226 recorded a coordinator growing about 390 MB/h of RSS across 45 h
with a memory map shaped like glibc per-thread arenas over 64 threads, and
nothing on /metrics could say whether that was live Python objects, pymalloc
fragmentation, or glibc arena fragmentation. This lands the cheap, fixed
cardinality instrument for that question, and the component gauge list #185
asked for, ahead of the census and allocator work in the second part.

lab/prism/process_telemetry.py (new) collects sys.getallocatedblocks(),
gc.get_count() and gc.get_stats() per generation, threading.active_count(),
and glibc mallinfo2 arena/in-use/free/mmapped bytes through ctypes. The
mallinfo2 binding is resolved once per collector and an absent or broken
symbol is remembered without logging; it renders as an availability gauge at
0 with every byte gauge at -1, never as zero bytes, so musl, macOS, and
pre-2.33 glibc read as unavailable rather than empty. The older int-typed
mallinfo is deliberately not used as a fallback: its 32-bit fields wrap on a
multi-gigabyte heap, which is exactly this issue's heap. The collector never
walks the heap: no gc.get_objects(), no tracemalloc.

lab/prism/metrics.py renders eleven process families (only the GC families
carry a label, the closed three-value generation set) and two component
families, qbit_prism_component_entries and qbit_prism_component_bytes, over a
closed component label set covering the payout window and its serialization
cache, job contexts and the bundle cache, the evicted-job graveyard, the
candidate lanes and every hash-keyed candidate registry, reconcile flights,
the pending-share floor, and the daemon mirror. Component reads are direct
attribute loads on the shipped owners so a renamed field fails loudly. There
is no hashrate-rollup gauge: the rollup folds in PostgreSQL and retains no
in-process buffer.

The cached payout window is accounted exactly once so the byte family can be
summed for attribution. Its two backings are mutually exclusive, so a
mirror-backed window (the Rust path, which is what mainnet runs) reports only
under daemon_window_mirror_*, and a page-backed window only under
payout_window_*. Which pair is non-zero is how an operator reads the active
backing. share_window_serialization_spool is labelled in HELP and in the docs
as an on-disk temporary file rather than resident bytes, so it is not mistaken
for RSS.

lab/prism/coordinator_config.py adds PRISM_MALLOC_TELEMETRY (default on,
strict boolean validated at startup through LifecycleConfig) gating only the
mallinfo2 call, which walks glibc free lists under each arena lock and is the
one reading that is not a plain counter load. The renderer resolves it once at
construction and falls back to the shipped default if the value has become
invalid since startup: a telemetry switch must not be able to take the
coordinator down from a metrics thread. compose.yaml passes it through and
.env.example documents it, so the compose stack can turn it off with a
restart.

tests/test_prism_metrics.py pins the exact family sequences, the unavailable
rendering, the shipped-owner reads, the closed label set under growth, the
no-double-count property stated as a sum, and the no-heap-walk contract, and
extends the frozen parity reference in the same commit.
tests/test_prism_process_telemetry.py pins the collector and the switch.
docs/prism-capacity-readiness.md documents the families, the glibc-only
statement, the switch and how to set it in each deployment, the single
accounting of the window, and what to read first when RSS climbs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@kiwidream
kiwidream force-pushed the prism-heap-and-cardinality-telemetry branch from cbd5696 to e8f5e60 Compare September 4, 2026 18:17

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

ℹ️ 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 +252 to +253
the shape #226 captured. Arena flat while RSS rises points at pymalloc or at
the Rust daemon child, which this process's gauges do not see.

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 Remove the child daemon from coordinator RSS diagnosis

When the coordinator's RSS rises while its arena gauge stays flat, the Rust daemon child cannot explain that rise: process_resource_metrics() reads /proc/self/statm, which includes only the coordinator process, while the daemon is launched as a separate subprocess.Popen. This guidance can therefore send an incident investigation toward a process that is provably outside the plotted RSS; recommend checking the child only against its own RSS metric or removing it from this branch of the diagnosis.

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.

2 participants