Repository navigation
Native-crash diagnosability and native-boundary thread-safety audit for the PRISM coordinator - #91
Merged
Merged
Conversation
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
App logs were normal through 10:04:51 and docker's
on-failurepolicy 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) insidelibpython3.12.sois 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:Changes
faulthandlerat the entrypoint (lab/prism/prism_coordinator.py, top ofmain()):faulthandler.enable(all_threads=True)— SIGSEGV/SIGABRT/SIGBUS/SIGFPE now print every thread's stack to stderr (visible indocker logs) regardless of whetherPYTHONFAULTHANDLERis set in the deployment environment. Enabled beforePrismCoordinator()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-coordinatorservice):ulimits.coresoft/hard-1(unlimited), with an inline comment documenting retrieval: the host's/proc/sys/kernel/core_patterndecides placement (it is not namespaced) — a relative pattern writes into the crashed process's cwd inside the container (/appfor this image;restart: on-failurereuses 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.yamlonly overridesimage/restart/volumesfor 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_ledgernative psycopg pool — SOUND_NativePostgresClient(lab/prism/share_ledger.py,connection()/run_json()/run_script()/close()), used byPsqlShareLedgerwhenPRISM_POSTGRES_NATIVE_CLIENTresolves to the psycopg backend (mainnet does; the Dockerfile installspsycopg[binary]==3.2.*)._idle(owned by the pool) or held by exactly one borrower:connection()pops under_idle_lock, and the only re-entry to_idleis the single append in the same borrower's success path. TheBoundedSemaphore(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.BaseExceptionout of the borrow body the connection isclose()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 infinally.run_json()executes andfetchone()s inside thewith;run_script()likewise. Nothing else in the process touches.connection(),_idle, or raw cursors —grepover the coordinator,public_api, and the CTV daemon shows all database access funnels throughPsqlShareLedgermethods, andimport psycopgappears nowhere outsideshare_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.append()/append_batch()serialize under the ledger's_lockand run through_run_json()→native.run_json(sql)with noretry_safe, so a mutation is never re-executed after an ambiguousOperationalError(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_semaphoreor hold_lock, and the one bare_run_retry_safe_read_jsoncall site is_carry_forward_audit_head_locked, which per the_lockedsuffix runs under_lockfrom its only caller. Either way this affects slot partitioning fairness only, not exclusivity.close()races.close()closes only idle (unborrowed) connections under_idle_lockand flips_closed; a concurrent borrower observes_closedon return and closes its own connection itself. No path closes a connection another thread is using — which matters because that (PQfinishracing attribute reads/exec on the samePGconn) is the one psycopg misuse class that segfaults rather than degrades.Connectionholds an internalthreading.LockandCursor.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._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 thetry, 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_scriptbodies 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:conditionis explicitlythreading.Condition(threading.RLock()), so the handler re-acquiring it while the main thread holds it (e.g. signal lands insidebegin_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.registeris used for SIGUSR2 precisely so no Python-level handler is involved.threading.Event.set()from a signal handler can in principle self-deadlock if the signal lands while the main thread is insideEvent.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"overlab/andcrates/finds nothing in the coordinator process. The Rust tools are invoked strictly as subprocesses (prism_tool_commandbinaries), never in-process.4. Subprocess / builder IPC — SOUND
The audit-bundle builder (
subprocess.Popenin_build_audit_bundle, the ~:14051 hot path):stdoutandstderrare temp files (or the canonical output file), not pipes; the parent reads them only afterwait()returns. The only pipe is stdin, written by exactly one thread (the builder thread) through_CancelableInput, which writes encoded bytes straight to the fd withos.writeafteros.set_blocking(fd, False). TheTextIOWrapperaroundprocess.stdinis never written through in the fd path, so its buffer is empty and the eventualclose()flush emits nothing — no double-write interleaving between the raw-fd and buffered layers.BlockingIOError/BrokenPipeErroron close are caught._cancel_obsolete_job_bundle_builds,_register_job_bundle_process)terminate()/kill()aPopenowned by the builder thread. Registration and cancellation handshake under_job_cache_lock(including the registered-after-cancelled case), every signal send ispoll()-guarded withProcessLookupErrorcaught, and only the owning thread reaps. The residual pid-reuse TOCTOU between a foreign reap andos.killis OS-level, common to all such code, and cannot corrupt this process's memory.verify_bundle'ssubprocess.run(..., PIPE, PIPE)usescommunicate()internally, single-threaded per call. The psql fallback backend (_run_sql) is inert on mainnet (native client active) and is likewisesubprocess.run-shaped.5. #83/#89 lock rework thread-identity assumptions — SOUND
ClientState.vardiff_lock,job_update_lock,send_lock): all acquired viawithblocks, 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 raiseRuntimeErrorrather than corrupt. The ordering contract is written at the field definitions (share handlers dropvardiff_lockbeforejob_update_lock/coordinator lock; coordinator lock only underjob_update_lock, never reverse) and the audited hot-path call sites conform._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-seeNone, which routes to the guarded path._ObservedRLockdelegates to one realthreading.RLock; the non-blocking contention probe composes with reentrancy (an owner's probe succeeds), and metrics live under their own plain lock.CoordinatorShutdownController):enter_writer/exit_writerpair same-thread inside the_writer_operationcontext manager. Queued shares use the deliberately transferablereserve_writertoken — counted inactive_writersunder the controller condition, finished idempotently (token.finishedflag checked under the lock) by either the enqueueing client thread (queue-full path) or the group-commit writer (commitfinally). Thethreading.localwriter depth is advisory (classifiesinheritedadmissions) and is only ever touched by the thread it belongs to; a leaked token degrades into the bounded quiescence timeout, not corruption.usersunder the registry lock), the hash-specificflight.lockis 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.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.lab/prism; Stratum and qbitd RPC are plaintext.http.client.HTTPConnectionis not thread-safe and is correctly isolated one-per-thread viathreading.local(commented at the definition).sock.makefile("r")in the handler loop); all writes serialized under the per-clientsend_lock(ClientState.send/send_batch). Cross-threadclose()on disconnect can race a blockedrecvinto an exception, which CPython handles at the fd level — not a memory-safety issue.direct_stratumsetsgetcontext().prec = 40at import time, which binds only the importing thread's context; worker threads created later compute vardiffDecimalmath 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 across3.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.pypython3 -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.yamlYAML-parse validated (docker CLI unavailable in this environment); production overlay confirmed not to override the coordinator'sulimitsNeed help on this PR? Tag
@codesmith-botwith 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 enablesfaulthandlerfor all threads beforePrismCoordinator()is built, so SIGSEGV/SIGABRT/SIGBUS/SIGFPE dump Python stacks to stderr (visible indocker logs) even whenPYTHONFAULTHANDLERis unset. SIGUSR2 is registered for on-demand all-thread dumps (docker kill -s USR2) without changing existing SIGTERM/SIGINT shutdown handlers.In
compose.yaml, theprism-coordinatorservice setsulimits.coresoft/hard to unlimited, with comments on how hostcore_patternaffects retrieval (docker cpvscoredumpctl). 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.