WIP: [RFC] ipc: add Events interface for chain and mempool notifications

bitcoin/bitcoin: PR #36985

1 major finding · 5 minor findings · 5 suggestions

Findings

Link

[major] · Asynchronous Events teardown can outlive ValidationSignals

An IPC client retaining an Events capability during shutdown can leave ~EventsImpl() running after or concurrently with node.validation_signals.reset(), causing an assertion failure or use-after-free.

Location: src/node/interfaces.cpp:1162 (head).

Details and suggested fix

A client need only retain the capability without calling destroy. Shutdown() calls disconnectIncoming(), but its EventLoop::sync() covers connection erasure, not the impl.reset() cleanup queued on capnp-async. Shutdown then clears validation subscribers and resets node.validation_signals. The new destructor still calls validation_signals().UnregisterSharedValidationInterface(m_queue) through an unconditional Assert(m_node.validation_signals). Cleanup after the reset aborts even in release builds; overlapping cleanup can access a ValidationSignals being destroyed. UnregisterAllValidationInterfaces() only clears registrations and does not detach this reference. Drain IPC implementation cleanup before resetting validation state, or synchronously detach subscriptions and make later destruction a no-op. A null check alone does not synchronize the access. This is a scheduling-dependent, late-shutdown failure after chainstate flushing, not evidence of data loss.


Link

[minor] · NaN timeouts bypass the waitNext clamps

A NaN timeout reaches the timed wait for an empty subscription; no in-tree caller sends it, and the resulting undefined behavior has no confirmed runtime symptom.

Location: src/node/interfaces.cpp:1169 (head).

Details and suggested fix

The schema accepts Float64, and libmultiprocess constructs MillisecondsDouble directly from the wire value. Both timeout < 0ms and timeout > std::chrono::years{100} are false for NaN, so deadline construction preserves it. When the queue is empty and neither interruption nor shutdown is set, wait_until receives that deadline. Timed-wait implementations convert it to integral clock ticks, where converting NaN is undefined behavior; the resulting symptom depends on the standard library. Reject std::isnan(timeout.count()) before constructing the deadline and add an IPC test sending float('nan') to an empty subscription. The existing clamps already handle positive and negative infinity.


Link

[minor] · MAX_BATCH_BYTES does not bound metadata-only replies

With a large maxEvents, metadata-only subscriptions bypass MAX_BATCH_BYTES and can return their entire backlog; the default maxEvents=1000 avoids this case.

Location: src/node/interfaces.cpp:1189 (head).

Details and suggested fix

SerializedSize() returns zero without include_data, and the batch loop adds only that value. Retention still charges sizeof(Event) per entry, so the default 128 MiB buffer can accumulate a large metadata backlog whose identifiers and fixed fields require substantial wire space. Copying the whole backlog also holds m_events_mutex, blocking validation callbacks that need to append events. If the reply exceeds a client's traversal limit, retrying the same arguments repeats the failure until the client lowers maxEvents; the exact reader threshold and a resulting failure are unconfirmed. Charge a conservative encoded per-event overhead in the batch budget, or impose a server-side event-count ceiling. Add a metadata-only backlog test with a large maxEvents; the existing batching test counts only transaction payload bytes.


Link

[minor] · Disconnected clients leave waitNext workers and subscriptions alive

A disconnected client's empty, default-timeout waitNext retains its worker and subscription until a matching event, normal node shutdown, or the 100-year timeout expires.

Location: src/node/interfaces.cpp:1179 (head).

Details and suggested fix

For example, a blockDisconnected-only subscription can remain blocked indefinitely during ordinary chain extension. Connection::~Connection() cancels the IPC request, but the cancellation callback only sets request_canceled; waitNext checks only its queue, m_interrupt, and the shutdown signal. The call's self capability keeps the server, EventsImpl, and its registered queue alive until the method returns. Repeated client crashes and reconnects can therefore accumulate workers and subscribers even though the old connections no longer count against the connection limit. Connect IPC cancellation or disconnect to a subscription-local stop flag, set it under m_events_mutex, include it in the predicate, and notify the condition variable. Test disconnecting with an empty blockDisconnected-only wait pending.


Link

[minor] · Interrupt() does not stop Events waits after initialization failure

An IPC client entering waitNext before a later initialization failure can leave process exit hanging because Interrupt() does not change the wait predicate; no occurrence has been confirmed.

Location: src/init.cpp:300 (head).

Details and suggested fix

IPC listeners accept clients before checks such as -onlynet parsing can fail. If initialization fails without a shutdown request, main() skips shutdown_signal->wait() and calls Interrupt() and Shutdown() without setting that signal. The new notify_all() wakes an empty waitNext, but its predicate remains false, so it sleeps again. Disconnect cancellation does not interrupt the method either. The pending call retains its server and EventLoopRef, preventing EventLoop::done() and leaving ~CapnpProtocol() blocked in its thread join. Set a persistent Events stop flag under m_events_mutex in Interrupt() and include it in the predicate so both existing and newly arriving waits return during initialization unwind.


Link

[minor] · Large -ipceventsbuffer values can silently reduce the buffer limit

On a 32-bit IPC build, operator-supplied -ipceventsbuffer=4096 becomes a zero-byte limit rather than being rejected; no affected deployment has been confirmed.

Location: src/node/interfaces.cpp:1156 (head).

Details and suggested fix

GetIntArg(...) * 1_MiB uses unsigned 64-bit arithmetic because the byte-unit literal returns uint64_t, then passes the result to a size_t parameter. Initialization checks only the lower bound. On a 32-bit build, 4096 MiB becomes 2^32 bytes and narrows to zero; 4097 becomes only 1 MiB. With a zero limit, push() evicts until only the newest event remains, producing gaps whenever more than one event accumulates between acknowledgements. Reject values above std::numeric_limits<size_t>::max() >> 20 before multiplication, or use checked conversion.


Optional improvements

Link

[suggestion] · Per-subscription budgets leave aggregate event buffering uncapped

Even with a connection limit, trusted clients can create arbitrarily many independently buffered Events objects, so -ipceventsbuffer is not an aggregate memory bound.

Location: src/init.cpp:756 (head).

Details and suggested fix

Every makeEvents call registers a queue with the full configured budget, and buffering begins even if the client never calls waitNext. A client leaking capability handles can therefore accumulate separately allocated queues on a single connection. Shared block and transaction references reduce duplication of payload memory, but queue entries and their accounting remain per subscription. Consider capping subscriptions per connection to make the aggregate buffering allowance predictable. If unlimited subscriptions are intentional, document explicitly that the operator must size for the number of live handles and that the option supplies no node-wide ceiling.


Link

[suggestion] · -ipceventsbuffer measures serialized bytes, not retained memory

The help text describes a MiB maximum, but queues charge serialized payload bytes plus fixed overhead while retaining decoded objects whose memory use can be higher.

Location: src/node/interfaces.cpp:1065 (head).

Details and suggested fix

With include_data, the queue keeps shared pointers to decoded CBlock and CTransaction objects. Their input/output vectors, scripts, witness stacks, and allocation overhead are not represented by GetSerializeSize() or ComputeTotalSize(). This distinction matters when sizing a block backlog during IBD. Shared ownership can also make summed per-subscription charges exceed the additional memory actually allocated, and the ratio has not been measured. Describe the option in its help text as a serialized-size budget plus fixed event overhead, warning that actual retained memory can be higher, rather than presenting it as a hard RAM maximum.


Link

[suggestion] · Unrelated Events subscriptions share wakeups and lock contention

Each subscription push broadcasts to all Events waiters, and batch copies hold a node-wide lock; the cost is unmeasured and likely small at low subscription counts.

Location: src/node/interfaces.cpp:1128 (head).

Details and suggested fix

One validation event delivered to several subscribed queues causes a separate notify_all() for each queue, potentially waking waiters repeatedly before their own queues receive data. Even subscriptions selecting unrelated event types wake and recheck false predicates. Meanwhile, waitNext copies its batch while holding the same mutex that every producer needs on the validation callback thread. Consider a mutex and condition variable per subscription, with a registry that Interrupt() and shutdown can use to mark and wake live subscriptions. This preserves callback ordering and queue consistency while avoiding unrelated wakeups and cross-subscription batch contention.


Link

[suggestion] · The shutdown test does not establish a blocked waitNext

The fixed sleep permits the shutdown test to pass without a server-side wait, so removing Interrupt()'s notification can go undetected.

Location: test/functional/interface_ipc_events.py:344 (head).

Details and suggested fix

After sending waitNext, the test sleeps for 100 ms and stops the node. If dispatch happens only after the shutdown signal is set, the initial predicate succeeds without needing a notification. Cancellation before dispatch can also produce the accepted KjException. Synchronize on an observable server-side point establishing that the empty-queue wait has entered, using a hook or log point coordinated with m_events_mutex, before calling stop_node. Keep the existing empty-result/disconnect allowance and bounded-shutdown check.


Link

[suggestion] · Mined-removal sequence tests miss interleaved conflicts

The tests would still accept consecutively assigned mined-removal sequences even when a block's conflict removals consume intervening values.

Location: src/txmempool.cpp:418 (head).

Details and suggested fix

removeForBlock() removes each mined transaction and then calls removeConflicts() before proceeding to the next block transaction. Conflict removals consume sequences and signal immediately, while mined removals are reported later through MempoolTransactionsRemovedForBlock(), so delivery order can differ from mutation order. The test checks one mined removal's sequence, but the multi-block reorg case does not check sequences and the conflict case contains no mined mempool transaction. Add a block containing a mempool transaction, an independent transaction that evicts a mempool conflict, and another mempool transaction. Record the starting sequence and assert the exact mempoolSequence for each removal, including the intervening conflict, rather than accepting consecutive values for the two mined removals.


Coverage details

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

Validation notifications deliberately provide generation-order delivery and serial execution for each subscriber, allowing a later callback to depend on work completed by an earlier callback without additional synchronization. This is not an ordering guarantee between different subscribers.

The proposed EventsQueue is one validation subscriber covering both chain and mempool callbacks, matching the scope of this existing contract. Earlier interface work explicitly sought joint ordering for listeners interested in both validation and mempool events; independently consumed notification channels do not inherit an equivalent cross-channel guarantee.

Source 1 · Source 2

A shared snapshot/event sequence was motivated by a concrete synchronization problem: polling getrawmempool while consuming notifications without a common sequence boundary can misclassify additions and removals. Separate notification connections introduce additional ordering ambiguity.

The historical discussion proposed bootstrapping from a snapshot and then maintaining a mirror from notifications, with another snapshot after detected message loss. At the pinned base, getrawmempool captures transaction IDs and the mempool sequence under the same lock. This supports the proposed stream’s snapshot-alignment purpose, but snapshot alignment and transport-loss detection remain distinct contracts.

Source 1

Historical attempts to build a mempool tracker found that legacy transaction notifications were not a mempool-membership feed: they also reported block appearances, while eviction notifications omitted mined removals. A separately labelled feed covering entry and exit was proposed to make membership tracking understandable, particularly across reorgs.

This directly motivates distinguishing txAddedToMempool from transactions merely present in connected or disconnected blocks, and attaching mutation sequences to mined removals. The same discussion raised compatibility concerns about changing existing notification messages, supporting the historical reason for treating a richer stream as a separate interface rather than assuming legacy topic semantics can change transparently.

Source 1 · Source 2 · Source 3

Assumeutxo notification work explicitly restricted ZMQ notifications to the active chainstate and excluded historical blocks connected by background validation.

The proposed role.historical filter follows an established distinction between active-chain progress and historical verification. Background validation is not a second sequence of active-chain advances to expose to ordinary chain followers. This exclusion is separate from whether active-chain blocks should be reported during IBD.

Source 1

Earlier IPC resource discussions recognized that remotely retained objects keep server-side data alive, including transaction references that can outlive their mempool entries. Object lifetime therefore creates a memory-management obligation even when initial data sharing is inexpensive.

An Events subscription similarly retains block and transaction references until acknowledgement, eviction, or object cleanup. The pinned IPC design documents server-owned capabilities, shared connections for multiple interfaces, and an explicit destroy operation that synchronously resets the wrapped object. These explain why subscription lifetime and retained-data accounting matter independently of network connection limits.

Source 1

Ralph's inferences

An ordered stream must preserve callback-generation order rather than impose an intuitive block-by-block grouping. The base contract permits removals associated with several connected blocks to precede those blocks’ BlockConnected callbacks, while UpdatedBlockTip may report only the final tip.

This supports using BlockConnected for every intermediate connection and one subscriber for the combined stream. It does not support interpreting every block connection as immediately preceded only by that block’s removals, or equating callback order with a fresh synchronous view of current node state.

The mempool mutation counter and the subscription delivery counter serve different purposes. Every removal already consumes a mempool sequence, including mined removals that do not generate an individual TransactionRemovedFromMempool callback; consequently, gaps in observed mempool sequences alone do not establish lost notifications.

Preserving each mined removal’s consumed sequence supplies information relevant to the atomic getrawmempool snapshot boundary. The separate Event.sequence can instead describe positions and losses in the selected subscription’s delivered stream. Neither counter should be treated as a substitute for the other.

IBD exclusion is callback-specific, not a guarantee that mempool mutations stop during IBD. ConnectTip still removes mined and conflicting transactions, but suppresses MempoolTransactionsRemovedForBlock while IBD is active.

The proposed stream inherits that producer-side omission for mined removals while independently exposing active-chain BlockConnected callbacks. Historical-chainstate filtering and IBD filtering therefore express different boundaries; a consumer cannot infer complete mined-removal coverage during IBD from the existence of block events.

The inspected guarantees support the foundations of an ordered, loss-detectable stream with bounded retained history, but not durable or unlimited replay. Replay at the PR head is repeat delivery of still-buffered, unacknowledged events within one subscription.

waitNext retains returned events until acknowledged, and queue eviction removes older events while advancing the subscription sequence. Shared validation registration also preserves callback-object lifetime through outstanding notifications, but unregistration is nonblocking. These are useful foundations, not proof of crash persistence, reconnect replay, aggregate IPC memory bounds, or completion of pending calls during shutdown.

Unresolved disagreements

The inspected IPC memory-management discussion does not establish a universal overflow policy. Its initial proposal favored client-controlled retention combined with accounting, refusal, and eventual eviction; another participant favored retaining recent, economically useful templates rather than attempting broad retention.

Although that discussion concerned mining templates rather than event subscriptions, it exposes the same retention-versus-resource tradeoff. It should not be treated as an existing resolution endorsing the proposed per-subscription oldest-event eviction policy or its scope of accounting.

Source 1 · Source 2