Skip to content

fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle - #5942

Open
songgaoye wants to merge 25 commits into
cometbft:mainfrom
songgaoye:song/fix_app_mempool_issues
Open

songgaoye wants to merge 25 commits into
cometbft:mainfrom
songgaoye:song/fix_app_mempool_issues

Conversation

@songgaoye

@songgaoye songgaoye commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

AppMempool proxies txs to the app over ABCI (InsertTx, CheckTx, ReapTxs) and tracks seen txs in a TTL guard cache. This PR fixes robustness bugs in that path.

Changes

  • Nil ABCI responses (no more panics, correct semantics):
    • ReapTxs: nil response skipped instead of dereferencing res.Txs.
    • InsertTx: nil response with no error is an invariant violation — now panics.
    • CheckTx:
      • On ABCI client error: forgetTx and callback were both skipped — tx stuck in cache, RPC caller hung; now fires the callback with a synthetic error response. Tx stays in seen cache (no retry) to avoid DDoS vector.
      • On nil response (no error): callback(nil) was called causing a downstream panic; now fires the callback with a synthetic error response. Tx stays in seen cache (no retry) to avoid DDoS vector.
  • CheckTx callback/cleanup: move forgetTx before the callback so a panicking callback can't skip cleanup.
  • InsertTx error path: transport errors no longer clear the seen cache to avoid DDoS vector.
  • Metrics: retryable codes no longer inflate RejectedTxs.
  • Lifecycle: add AppMempool.Close() to stop the guard's background goroutine and call it from AppReactor.OnStop() (was leaking on shutdown).

PR checklist

  • Tests written/updated
  • Changelog entry added in CHANGELOG.md
  • Updated relevant documentation (docs/ or spec/) and code comments

@songgaoye
songgaoye requested a review from a team as a code owner June 22, 2026 10:47
@greptile-apps

greptile-apps Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

PR author is not in the allowed authors list.

@swift1337 swift1337 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What problem does this PR solve?

@songgaoye
songgaoye marked this pull request as draft June 22, 2026 12:29
@songgaoye
songgaoye force-pushed the song/fix_app_mempool_issues branch from 29742fa to 08b0f8c Compare June 22, 2026 13:50
@songgaoye
songgaoye marked this pull request as ready for review June 22, 2026 14:08
@songgaoye songgaoye changed the title fix(mempool): prevent re-gossip of txs and close echo-back window in reapTxs fix(mempool): app-side ABCI response handling, callback/cleanup, and lifecycle Jun 22, 2026
@songgaoye

Copy link
Copy Markdown
Contributor Author

What problem does this PR solve?

Sorry, I'd opened this without a description — I've just updated it with the full context. In short: it fixes several robustness bugs in the app-side mempool's ABCI response handling — panics on nil InsertTx/CheckTx/ReapTxs responses, a nil InsertTx response being silently treated as success, RPC callbacks/seen-cache cleanup being skipped on app errors and callback panics, retryable codes inflating RejectedTxs, and a guard goroutine leaking on shutdown. Details in the updated PR description above.

@songgaoye songgaoye changed the title fix(mempool): app-side ABCI response handling, callback/cleanup, and lifecycle fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle Jun 22, 2026
@songgaoye
songgaoye requested a review from swift1337 June 22, 2026 14:24
Comment thread mempool/app_mempool.go Resolved
@songgaoye
songgaoye requested a review from thomas-nguy July 7, 2026 11:03
Comment thread mempool/app_mempool.go Resolved
Comment thread mempool/app_mempool.go Resolved
Comment thread mempool/app_mempool.go Resolved
Comment thread mempool/app_mempool.go Resolved
@songgaoye
songgaoye requested a review from swift1337 July 9, 2026 02:06
JayT106 added a commit to JayT106/cometbft that referenced this pull request Jul 14, 2026
… vector

Releasing the tx from the seen-guard on app.CheckTx error/nil-response let
a client cheaply force repeated ABCI round-trips to an already-failing app
by resubmitting the same tx. Upstream flagged this exact pattern in
cometbft#5942 review. Fix: keep the tx marked seen on error so a
repeat submission gets a cheap in-memory ErrSeenTx instead of hitting the
app again; the callback still fires so RPC callers don't block.
@songgaoye
songgaoye force-pushed the song/fix_app_mempool_issues branch from 6c4af44 to f5392da Compare July 15, 2026 04:33
JayT106 pushed a commit to crypto-org-chain/cometbft that referenced this pull request Nov 2, 2026
…d lifecycle (#51)

* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle

* fix(mempool): don't clear seen cache on nil CheckTx response

* update ResponseCheckTx code

Port note (v0.40.0): also folds in the v0.40 review follow-ups: CHANGELOG
entry for upstream cometbft#5942, nil CheckTx response handled through the
client-error path, tests for nil ReapTxs, CheckTx internal code, seen-cache
and AppReactor.OnStop, and stale comment fixes.

(cherry picked from commit 524b896)
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days-before-close if no further activity occurs.

JayT106 pushed a commit to crypto-org-chain/cometbft that referenced this pull request Nov 4, 2026
…d lifecycle (#51)

* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle

* fix(mempool): don't clear seen cache on nil CheckTx response

* update ResponseCheckTx code

Port note (v0.40.0): also folds in the v0.40 review follow-ups: CHANGELOG
entry for upstream cometbft#5942, nil CheckTx response handled through the
client-error path, tests for nil ReapTxs, CheckTx internal code and the
seen cache, and stale comment fixes. The node, which owns the mempool, now
closes the AppMempool seen-cache guard in its OnStop instead of the reactor.

(cherry picked from commit 524b896)
JayT106 pushed a commit to crypto-org-chain/cometbft that referenced this pull request Nov 5, 2026
…d lifecycle (#51)

* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle

* fix(mempool): don't clear seen cache on nil CheckTx response

* update ResponseCheckTx code

Port note (v0.40.0): also folds in the v0.40 review follow-ups: CHANGELOG
entry for upstream cometbft#5942, nil CheckTx response handled through the
client-error path, tests for nil ReapTxs, CheckTx internal code and the
seen cache, and stale comment fixes. The node, which owns the mempool, now
closes the AppMempool seen-cache guard in its OnStop instead of the reactor.

(cherry picked from commit 524b896)
JayT106 added a commit to crypto-org-chain/cometbft that referenced this pull request Nov 5, 2026
* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle (#51)

* fix(mempool): AppMempool ABCI response handling, callback/cleanup, and lifecycle

* fix(mempool): don't clear seen cache on nil CheckTx response

* update ResponseCheckTx code

Port note (v0.40.0): also folds in the v0.40 review follow-ups: CHANGELOG
entry for upstream cometbft#5942, nil CheckTx response handled through the
client-error path, tests for nil ReapTxs, CheckTx internal code and the
seen cache, and stale comment fixes. The node, which owns the mempool, now
closes the AppMempool seen-cache guard in its OnStop instead of the reactor.

(cherry picked from commit 524b896)

* fix(lp2p): cap per-reactor priority queue to prevent memory-exhaustion DoS (#53)

* fix(lp2p): cap per-reactor priority queue to prevent memory-exhaustion DoS

The lp2p handleStream path reads and closes the libp2p stream before
enqueueing the decoded message. Stream and connection limits therefore
provide no backpressure against a fast peer: a slow reactor (e.g.
mempool under load) lets the priority queue grow without bound until
OOM.

Fix: add an optional maxSize cap to PriorityQueue. When the limit is
reached, Push returns ErrQueueFull and the message is dropped.
newReactorPriorityQueue now passes concurrentPoolCapacity (512) as
the cap, matching the downstream inbound channel — total per-reactor
buffer stays bounded at 1024 items before drops begin.

Drops are counted in a new p2p_messages_reactor_dropped metric and
logged at Error level so operators can detect a saturated reactor.

The autoscaler's queue-pressure signal still reads only len(inbound),
which remains correct; the priority queue is upstream pre-staging.

Fixes: unbounded per-reactor priority queue (lp2p memory-exhaustion DoS)
(cherry picked from commit 4894956)

* chore: add CHANGELOG entry for cometbft#5955

(cherry picked from commit f14ca91)

* chore: fix CHANGELOG entry wording for cometbft#5955

(cherry picked from commit 8494170)

* fix(lp2p): raise priority queue cap to 200k and make it configurable

512 was too small: normal mempool traffic from two peers (each sending
hundreds of txs) would fill the queue and drop messages before the
mempool's own deduplication cache could filter them.

Decouple the priority queue max from the pool inbound channel capacity
(which stays at 512). Add MaxQueueSize to LibP2PScaler and
LibP2PScalerOverride so operators can tune per-reactor; default is
200_000 (~200 MB at 1 KB/msg average), matching the budget noted in
review feedback.

0 means unbounded and is reserved for tests.

(cherry picked from commit d7d0c4e)

* refactor(lp2p): simplify scaler config access and fix flood count in test

Use a local scalerCfg alias in newReactorPriorityQueue to avoid
repeating the long access chain — consistent with newReactorScaler.

Raise the queue-full test flood count from 64 to 1000 so it reliably
exceeds the total buffer depth (~inbound cap 512 + workers + pq cap 16)
regardless of goroutine scheduling when run alongside other subtests.

(cherry picked from commit 51f7dea)

* fix(config): expose max_queue_size in config.toml template

max_queue_size was added to LibP2PScaler but missing from the TOML
template, so operators couldn't set it via config.toml.

(cherry picked from commit 1e85cb6)

* chore(config): move MaxQueueSize field comments to toml.go

Config struct fields don't need inline comments; the TOML template
is the right place for operator-facing documentation.

(cherry picked from commit 86115a2)

* chore(lp2p): restore original concurrentPoolCapacity comment

(cherry picked from commit c897ca8)

* chore(config): mention default max_queue_size in toml comment

(cherry picked from commit 04707e9)

* fix(lp2p): log error when priority queue is unbounded

max_queue_size = 0 disables the DoS cap silently. Emit an Error-level
log at reactor startup so operators are warned when the node is
vulnerable to memory-exhaustion from a fast peer.

(cherry picked from commit db36a5b)

* chore(config): use 200000 as example max_queue_size in toml comment

(cherry picked from commit e231e50)

* fix(config): make override MaxQueueSize a pointer to distinguish unset from explicit-unbounded

Backport of the fix from cometbft#5955's follow-up commits.
An override's MaxQueueSize as a plain int can't tell "not set in this
config" apart from "explicitly set to 0 for an unbounded reactor" -
both decode to the same zero value. Switching to *int lets nil mean
"inherit the global cap" while an explicit 0 stays a real choice.

* docs(config): trim LibP2PScalerOverride comment

* fix(autopool): evict lower-priority item instead of rejecting on full priority queue

PriorityQueue.Push capped total depth across all priority levels and
rejected any push once full, regardless of the incoming message's
priority. A burst of low-priority traffic could fill the queue and
then starve out higher-priority admissions.

Push now evicts the oldest strictly-lower-priority item to make room
for a higher-priority one. ErrQueueFull is only returned when no
lower-priority item is queued to evict.

* chore(autopool): trim eviction comments to one line each

* fix(config): preserve unset override max_queue_size across toml write and reload

Rendering an unset override MaxQueueSize as literal 0 in config.toml made it
indistinguishable from an explicit unbounded override. Regenerating the file
(e.g. via `cometbft testnet --config`) silently turned "inherit the global
cap" into "no cap", reopening the queue-exhaustion DoS.

Also move the lp2p changelog entry to the top of BUG FIXES per convention.

* fix(lp2p): count evicted messages in reactor metrics

Push() evicting a lower-priority item to make room silently dropped it:
MessagesReactorInFlight was never decremented and MessagesReactorDropped
never counted it, so eviction-based drops were invisible to metrics. Add
an onEvict callback to PriorityQueue and wire it up in the reactor pool so
evicted messages update both metrics with the evicted message's own
labels.

Also extract the duplicated case-insensitive reactor-override lookup into
a shared helper.

* remove comments

---------

Signed-off-by: JayT106 <[email protected]>

Port note (v0.40.0): synced to upstream cometbft#5955 head
(override inheritance, negative-value validation, eviction). Also folds in
the v0.40 review follow-ups: queue-full drops logged at Debug since peers
can trigger them, shared drop-metric helpers, tests pinning the default cap
and its inheritance, and an unbounded queue for the maxed-out lp2p bench.

(cherry picked from commit 76b16e0)

* ci: run e2e on ubuntu-latest and fix flaky PEX seed test (#64)

Ports the part of fork #64 ("chore: cherry-pick missing upstream v0.39.4
commits") that v0.40.0 still needs. Its upstream backports (cometbft#5813, cometbft#5668,
cometbft#5959) are already in v0.40.0.

- Run e2e-test on ubuntu-latest: the fork has no Depot runner, so
  depot-ubuntu-24.04-4 jobs queue until the 24h timeout.
- Tolerate an already-stopped peer in TestPEXReactorSeedModeFlushStop, since
  the seed may disconnect it first (v0.40 follow-up, not in fork #64).

(cherry picked from commit 14b7b93)

---------

Co-authored-by: songgaoye <[email protected]>
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.

3 participants