Skip to content

Native-crash diagnosability and native-boundary thread-safety audit for the PRISM coordinator - #91

Merged
RobertClarke merged 1 commit into
1.x.xfrom
prism-crash-audit
Jul 25, 2026
Merged

RobertClarke merged 1 commit into
1.x.xfrom
prism-crash-audit

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Context

The mainnet PRISM coordinator (rev 05ee96b, ~100 threads) died 2026-07-25 10:04:51Z from a native segfault with zero Python-level output:

kernel: python3[4146041]: segfault at 5f9b901e0f30 ip 00007f9d80aca1ea sp 00007f9d5e3cd170 error 4 in libpython3.12.so.1.0[1d91ea,...]

App logs were normal through 10:04:51 and docker's on-failure policy restarted the container in 1s. This is the first native crash in the system's history, ~35h after the #83/#87/#89/#90 locking-rework era began. A user-mode read fault (error 4) inside libpython3.12.so is the classic downstream signature of heap corruption introduced earlier by any misused native boundary — the faulting instruction is usually the allocator tripping over a corrupted arena, not the culprit. This PR therefore does two things:

  1. Diagnosability — make the next occurrence produce evidence (all-thread Python stacks + a core dump).
  2. Audit — walk every native boundary in the coordinator process for thread-safety violations that can corrupt memory, and record the findings here even where no defect was found, so the next investigation starts from a verified baseline instead of re-deriving it.

Changes

faulthandler at the entrypoint (lab/prism/prism_coordinator.py, top of main()):

  • faulthandler.enable(all_threads=True) — SIGSEGV/SIGABRT/SIGBUS/SIGFPE now print every thread's stack to stderr (visible in docker logs) regardless of whether PYTHONFAULTHANDLER is set in the deployment environment. Enabled before PrismCoordinator() construction so startup crashes are covered too.
  • faulthandler.register(signal.SIGUSR2, all_threads=True) — on-demand all-thread dump of the live process (docker kill -s USR2 prism-coordinator) for hang/pre-crash triage. SIGUSR2 was previously unused; the existing SIGTERM/SIGINT handlers are untouched, and faulthandler's handlers run at the C level so they fire even with the GIL held by a wedged thread.

Core dumps (compose.yaml, prism-coordinator service): ulimits.core soft/hard -1 (unlimited), with an inline comment documenting retrieval: the host's /proc/sys/kernel/core_pattern decides placement (it is not namespaced) — a relative pattern writes into the crashed process's cwd inside the container (/app for this image; restart: on-failure reuses the same container so the file survives the restart — docker cp <container>:/app/core), while a pipe pattern (|systemd-coredump, apport) delivers to that handler on the host (coredumpctl). compose.production.yaml only overrides image/restart/volumes for this service, so mainnet inherits the stanza on redeploy.

No behavioral change to the coordinator itself; both are pure instrumentation.

Audit

Scope, per the incident review: the boundaries through which a ~100-thread CPython 3.12 process can corrupt native memory — psycopg/libpq, signal-handler use, ctypes/cffi, subprocess pipe handling, and the thread-identity assumptions in the #83/#89 lock rework. No concrete violation was found; consistent with the "regression test only for a concrete violation, no speculative refactors" scope, no test or refactor accompanies this audit. Notes below record what was verified and where, plus the benign observations worth keeping on file.

1. share_ledger native psycopg pool — SOUND

_NativePostgresClient (lab/prism/share_ledger.py, connection() / run_json() / run_script() / close()), used by PsqlShareLedger when PRISM_POSTGRES_NATIVE_CLIENT resolves to the psycopg backend (mainnet does; the Dockerfile installs psycopg[binary]==3.2.*).

  • One-connection-one-thread invariant holds. A connection is either in _idle (owned by the pool) or held by exactly one borrower: connection() pops under _idle_lock, and the only re-entry to _idle is the single append in the same borrower's success path. The BoundedSemaphore(pool_size) bounds concurrent borrows; exclusivity itself comes from the pop-under-lock, so even a caller that bypassed the read semaphore could not share a live connection with another thread.
  • Error paths discard, never return. On any BaseException out of the borrow body the connection is close()d by the borrowing thread and never re-enters _idle, so a connection that raised mid-cursor cannot be handed to another thread with a cursor still pending. The semaphore is released exactly once in finally.
  • No cursor or connection escapes the borrow. run_json() executes and fetchone()s inside the with; run_script() likewise. Nothing else in the process touches .connection(), _idle, or raw cursors — grep over the coordinator, public_api, and the CTV daemon shows all database access funnels through PsqlShareLedger methods, and import psycopg appears nowhere outside share_ledger.py. Cursor objects that survive in exception tracebacks reference an already-closed connection; psycopg client-side cursor finalization does not touch libpq, so cross-thread GC of those is inert.
  • Writer path. append() / append_batch() serialize under the ledger's _lock and run through _run_json() → native.run_json(sql) with no retry_safe, so a mutation is never re-executed after an ambiguous OperationalError (the retry-once path is reserved for statements the caller classified as reads: _run_retry_safe_read_json). Pool sizing (read_concurrency + 1) matches the one-serialized-writer + N-readers design; reads go through _read_semaphore or hold _lock, and the one bare _run_retry_safe_read_json call site is _carry_forward_audit_head_locked, which per the _locked suffix runs under _lock from its only caller. Either way this affects slot partitioning fairness only, not exclusivity.
  • close() races. close() closes only idle (unborrowed) connections under _idle_lock and flips _closed; a concurrent borrower observes _closed on return and closes its own connection itself. No path closes a connection another thread is using — which matters because that (PQfinish racing attribute reads/exec on the same PGconn) is the one psycopg misuse class that segfaults rather than degrades.
  • Library-level backstop (verified in psycopg 3.2.13 source): the sync Connection holds an internal threading.Lock and Cursor.execute() wraps the whole libpq exchange in it, so even a hypothetical double-borrow would serialize rather than corrupt libpq state. The corruption-grade windows (close() vs concurrent use) are exactly the ones the pool structurally excludes.
  • Lease acquisition retry (_ensure_writer_lease) sleeps between attempts without holding a connection; each attempt is its own borrow.

Benign observations, no change made: _slots.acquire() sits before the try, so an async exception (KeyboardInterrupt in the main thread) delivered in that instruction window would leak one slot in a process that is exiting anyway; a pool-exhaustion deadlock would require a thread to nest borrows, and no nested borrow exists (run_json/run_script bodies never call back into the ledger).

2. Signal-handler use — SOUND (one liveness-only note)

main() registers SIGTERM/SIGINT → PrismCoordinator.request_shutdown() → CoordinatorShutdownController.request_shutdown() + stop_event.set(). CPython runs Python-level signal handlers as ordinary bytecode in the main thread between instructions — they cannot corrupt native state; the audit questions are reentrancy and deadlock:

  • The controller's condition is explicitly threading.Condition(threading.RLock()), so the handler re-acquiring it while the main thread holds it (e.g. signal lands inside begin_shutdown) recurses instead of deadlocking. The handler body is bounded: state flips + notify_all, no I/O, matching its "signal-safe-sized" docstring.
  • faulthandler's own SIGSEGV/SIGUSR2 handlers (added by this PR) are C-level and async-signal-safe by design; faulthandler.register is used for SIGUSR2 precisely so no Python-level handler is involved.
  • Note (pre-existing, liveness-only, left as-is): threading.Event.set() from a signal handler can in principle self-deadlock if the signal lands while the main thread is inside Event.wait()'s internal non-reentrant lock bookkeeping — a few-bytecode window that would wedge shutdown, not corrupt memory. Recorded for completeness; it cannot produce the observed segfault.

3. ctypes / cffi — ABSENT

grep -rn "ctypes\|cffi" over lab/ and crates/ finds nothing in the coordinator process. The Rust tools are invoked strictly as subprocesses (prism_tool_command binaries), never in-process.

4. Subprocess / builder IPC — SOUND

The audit-bundle builder (subprocess.Popen in _build_audit_bundle, the ~:14051 hot path):

  • No concurrent pipe reads exist. stdout and stderr are temp files (or the canonical output file), not pipes; the parent reads them only after wait() returns. The only pipe is stdin, written by exactly one thread (the builder thread) through _CancelableInput, which writes encoded bytes straight to the fd with os.write after os.set_blocking(fd, False). The TextIOWrapper around process.stdin is never written through in the fd path, so its buffer is empty and the eventual close() flush emits nothing — no double-write interleaving between the raw-fd and buffered layers. BlockingIOError/BrokenPipeError on close are caught.
  • Cross-thread kill is exception-safe. Supersession/watchdog paths (_cancel_obsolete_job_bundle_builds, _register_job_bundle_process) terminate()/kill() a Popen owned by the builder thread. Registration and cancellation handshake under _job_cache_lock (including the registered-after-cancelled case), every signal send is poll()-guarded with ProcessLookupError caught, and only the owning thread reaps. The residual pid-reuse TOCTOU between a foreign reap and os.kill is OS-level, common to all such code, and cannot corrupt this process's memory.
  • verify_bundle's subprocess.run(..., PIPE, PIPE) uses communicate() internally, single-threaded per call. The psql fallback backend (_run_sql) is inert on mainnet (native client active) and is likewise subprocess.run-shaped.

5. #83/#89 lock rework thread-identity assumptions — SOUND

  • Per-client locks (ClientState.vardiff_lock, job_update_lock, send_lock): all acquired via with blocks, so acquire/release is same-thread by construction; the RLocks' reentrancy is used for same-thread helper nesting (authorize/retarget → maybe_send_job), and a cross-thread RLock release would raise RuntimeError rather than corrupt. The ordering contract is written at the field definitions (share handlers drop vardiff_lock before job_update_lock/coordinator lock; coordinator lock only under job_update_lock, never reverse) and the audited hot-path call sites conform.
  • Lazy lock initialization (_client_vardiff_lock, _ensure_share_hot_path_state, disposition-registry backfill): double-checked pattern under the module-level _HOT_PATH_LOCK_INITIALIZATION_LOCK, so two threads cannot mint distinct locks for the same state (which would silently void mutual exclusion). The unlocked fast-path attribute read is GIL-atomic and can only mis-see None, which routes to the guarded path.
  • _ObservedRLock delegates to one real threading.RLock; the non-blocking contention probe composes with reentrancy (an owner's probe succeeds), and metrics live under their own plain lock.
  • Writer-admission tokens (CoordinatorShutdownController): enter_writer/exit_writer pair same-thread inside the _writer_operation context manager. Queued shares use the deliberately transferable reserve_writer token — counted in active_writers under the controller condition, finished idempotently (token.finished flag checked under the lock) by either the enqueueing client thread (queue-full path) or the group-commit writer (commit finally). The threading.local writer depth is advisory (classifies inherited admissions) and is only ever touched by the thread it belongs to; a leaked token degrades into the bounded quiescence timeout, not corruption.
  • Fix stale abandon of accepted PRISM blocks #89 same-hash disposition flights: refcounted registry (users under the registry lock), the hash-specific flight.lock is never awaited while holding the registry lock, and cleanup pops only after an identity check (registry.get(key) is flight), so a replacement flight can't be evicted by a stale finisher.

6. Other native boundaries checked in passing

  • hashlib: every use is one-shot (hashlib.sha256(data).digest()-shaped); no hasher object is stored or shared, so the GIL-released-update-on-shared-OpenSSL-context hazard (CPython releases the GIL for large buffers) has no instance.
  • ssl: not imported anywhere in lab/prism; Stratum and qbitd RPC are plaintext.
  • qbitd RPC: http.client.HTTPConnection is not thread-safe and is correctly isolated one-per-thread via threading.local (commented at the definition).
  • Sockets: one reader thread per client (sock.makefile("r") in the handler loop); all writes serialized under the per-client send_lock (ClientState.send/send_batch). Cross-thread close() on disconnect can race a blocked recv into an exception, which CPython handles at the fd level — not a memory-safety issue.
  • Decimal contexts (benign observation, no change): direct_stratum sets getcontext().prec = 40 at import time, which binds only the importing thread's context; worker threads created later compute vardiff Decimal math at the default prec 28. At mining-difficulty magnitudes both precisions are exact for the quantities involved, so this is a consistency note, not a defect.

Where does that leave the segfault?

The audited in-process boundaries do not show a corruption path, and Python-level races (which the GIL renders memory-safe) cannot produce a native fault. The remaining candidate space is below the application: a latent bug in psycopg_binary/bundled libpq (the image floats across 3.2.* patch releases at build time — worth pinning the exact wheel when the next investigation starts, so the binary under test is known), glibc, or CPython 3.12.x itself. That is exactly the space where this PR's instrumentation pays off: the next occurrence yields every thread's Python stack at the faulting instant plus a full core against known binaries, instead of a bare kernel line.

Testing

  • python3 -m py_compile lab/prism/prism_coordinator.py
  • python3 -m unittest tests.test_prism_hot_path tests.test_prism_share_ledger tests.test_prism_coordinator_vardiff — 421 tests, all pass (the Isolate PRISM share hot-path locking #83/Fix stale abandon of accepted PRISM blocks #89-era lock and ledger suites)
  • compose.yaml YAML-parse validated (docker CLI unavailable in this environment); production overlay confirmed not to override the coordinator's ulimits

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


Note

Low Risk
Diagnostics-only changes (faulthandler and core ulimits); no changes to coordinator business logic, auth, or data paths.

Overview
Adds instrumentation only so a future native segfault in the PRISM coordinator produces usable forensics instead of a silent kernel line.

In prism_coordinator.py, main() now enables faulthandler for all threads before PrismCoordinator() is built, so SIGSEGV/SIGABRT/SIGBUS/SIGFPE dump Python stacks to stderr (visible in docker logs) even when PYTHONFAULTHANDLER is unset. SIGUSR2 is registered for on-demand all-thread dumps (docker kill -s USR2) without changing existing SIGTERM/SIGINT shutdown handlers.

In compose.yaml, the prism-coordinator service sets ulimits.core soft/hard to unlimited, with comments on how host core_pattern affects retrieval (docker cp vs coredumpctl). Coordinator mining/stratum behavior is unchanged.

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

Enable faulthandler (plus a SIGUSR2 all-thread dump) at the entrypoint
and allow unlimited core dumps for the prism-coordinator service, so the
next native fault produces per-thread stacks and a retrievable core
instead of a bare kernel segfault line.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke
RobertClarke merged commit b49b0fd into 1.x.x Jul 25, 2026
9 checks passed
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