Skip to content

[ISSUE #11602] Close streams on failure paths and keep RocksDB shutdo… - #11606

Open
RLDE26 wants to merge 2 commits into
apache:developfrom
RLDE26:fix/issue-11602-resource-leak
Open

RLDE26 wants to merge 2 commits into
apache:developfrom
RLDE26:fix/issue-11602-resource-leak

Conversation

@RLDE26

@RLDE26 RLDE26 commented Nov 25, 2026

Copy link
Copy Markdown

Which Issue(s) This PR Fixes

Brief Description

1. Config file streams (ControllerStartup, NamesrvStartup)
in.close() sat at the end of a straight-line block. Any exception in properties.load() or the following properties2Object() calls skipped it, leaking the file handle. Both are now wrapped in try-with-resources.

2. TLS key material (TlsHelper)
The certificate and private key streams were created inline as arguments to keyManager(...) / forServer(...), so no reference survived the call and they were never closed. Both are now declared inside a try-with-resources block. Note that decryptPrivateKey() also returns an InputStream, so up to four streams leaked, not two.

keyManager(InputStream, InputStream, String) consumes both streams synchronously (SslContext.toX509Certificates / toPrivateKey) and SslContextBuilder keeps no InputStream field, so closing them once keyManager returns is safe. This is one step earlier than the Javadoc wording ("close after build() has been called"); the reasoning rests on the method body, not on undocumented state.

3. RocksIterator (RocksDBConfigToJsonCommand)
The iterator was created before the try, so if iterator() itself threw, the finally { shutdown(path); } never ran. Moving the declaration into the resource block fixes that, and try (R) B finally F guarantees the iterator is closed before the DB is shut down.

4. Zstd stream (ZstdCompressor)
outputStream.close() inside the try was skipped when write() threw. It is now managed by try-with-resources. toByteArray() had to move out of the try block: ZstdOutputStream.close() is what flushes the frame, so reading the array before the block exits returns a truncated result. The old finally block also closed the ByteArrayOutputStream, whose close() is a no-op in the JDK and holds no native resource, so it is dropped.

5. RocksDB shutdown sequence (AbstractRocksDBStorage#shutdown)
The release steps run in a straight line, so a failure in one call jumped to the trailing catch and skipped db.closeE(). The three calls that can throw — awaitTermination (InterruptedException), pauseBackgroundWork (RocksDBException) and preShutdown() (abstract, reaches JNI in one subclass) — are now wrapped in local try-catch blocks, so the handles, the options and db.closeE() are always reached.

How Did You Test This Change?

  • mvn -pl common,remoting,client,srvutil,proto,auth,tools,controller,namesrv -am -DskipTests compile — all modules SUCCESS, including checkstyle (bound to the validate phase).
  • mvn -pl common -Dtest=ZstdCompressorTest test — 5 tests, 0 failures.
  • Negative check on the Zstd change: moving toByteArray() back inside the try block makes testCompressAndDecompress fail with Read error or truncated stream, confirming the ordering requirement is actually covered by that test.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 16.32653% with 41 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.46%. Comparing base (d4a0881) to head (7b6b254).
⚠️ Report is 3 commits behind head on develop.

Files with missing lines Patch % Lines
...va/org/apache/rocketmq/namesrv/NamesrvStartup.java 0.00% 14 Missing ⚠️
...rocketmq/common/config/AbstractRocksDBStorage.java 0.00% 13 Missing ⚠️
.../apache/rocketmq/controller/ControllerStartup.java 0.00% 8 Missing ⚠️
.../org/apache/rocketmq/remoting/netty/TlsHelper.java 60.00% 0 Missing and 4 partials ⚠️
...s/command/metadata/RocksDBConfigToJsonCommand.java 0.00% 2 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             develop   #11606      +/-   ##
=============================================
+ Coverage      50.42%   50.46%   +0.03%     
- Complexity     14687    14700      +13     
=============================================
  Files           1391     1391              
  Lines         103619   103625       +6     
  Branches       13591    13591              
=============================================
+ Hits           52251    52291      +40     
+ Misses         45100    45080      -20     
+ Partials        6268     6254      -14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ShannonDing ShannonDing 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.

The try-with-resources changes for configuration streams, TLS key material, RocksIterator, and Zstd look correct. However, the new interruption handling in RocksDB shutdown introduces a cleanup race that needs to be fixed before merge.

Review baseline: this PR applied to develop@1f083ebea. Code links below are pinned to PR head 7b6b254.

[P1, production blocker] Restoring the interrupt flag before the remaining cleanup can skip the flush-thread join and allow RocksDB to close while that thread is still running

Changed code: AbstractRocksDBStorage.java, lines 518-523.

The new catch block immediately calls Thread.currentThread().interrupt() after awaitTermination() is interrupted, then continues cleanup. There is still a blocking shutdown operation later in this call chain:

  1. For V2 configuration storage, ConfigStorage.preShutdown() calls flushSyncService.shutdown().
  2. ServiceThread.shutdown() uses Thread.join() to wait for the service thread. With the caller's interrupt flag already set, the join throws InterruptedException rather than waiting for the live worker. The method logs the exception and returns.
  3. The storage shutdown then continues releasing handles, calling db.closeE(), clearing db, and marking the storage unloaded, while FlushSyncService can still perform a WAL operation or its final flush during exit.

Minimal triggering scenario: start V2 ConfigStorage with its flush thread still active, then interrupt the shutdown caller before or during the compaction executor's termination wait. A latch holding the flush thread just before a WAL operation makes the lost shutdown ordering observable.

This creates a race between DB release and Java-side WAL access: the worker may observe a null db, or retain a reference whose native handle has already been released. cancelAllBackgroundWork(true) does not join RocketMQ's Java flush thread; it waits for RocksDB's own native background work. The shutdown can also return success even though the worker has not exited.

This is a newly reachable failure path: previously, interruption of this awaitTermination() reached the outer catch and returned false without proceeding to release the DB. The PR now restores the interrupt flag and continues into the downstream join.

Validation boundary: a focused latch-controlled reproduction using the actual ServiceThread confirmed that this sequence returns with the worker still alive and the caller's interrupt flag cleared by the interrupted join. Deferring restoration until after the join produced the expected worker-exited/interrupt-preserved result. This establishes the shutdown synchronization problem; it is not a claim that a full Broker native crash was reproduced.

Required changes:

  • Record the interruption rather than restoring the flag before cleanup steps that still need to wait or join. Restore it in the outermost cleanup finally, after those steps have completed.
  • Ensure the Java flush thread has actually exited before releasing the DB and its dependent resources. Merely catching the join interruption and continuing is not sufficient.
  • Add a deterministic V2 storage shutdown regression with a barrier-controlled flush thread. Assert worker exit precedes handle/DB closure, and verify the caller's interrupt status is preserved at the end.

Additional test gaps, not separate demonstrated production defects

There are no new failure-path tests in this PR. It would also be useful to cover pauseBackgroundWork()/preShutdown() failures, iterator creation and iteration failures with iterator-before-DB closure, TLS second-stream acquisition failure, and Zstd write/flush failure cleanup. These are validation gaps, distinct from the production race above; low patch coverage alone is not the reason for requesting changes.

I did not find another blocking issue in the other resource changes. In particular, the current Netty version parses the supplied key material synchronously, so closing those streams before build() is safe here, and reading the Zstd output only after the wrapper has closed correctly preserves the completed frame.

…shutdown reachable

The config-file streams, the RocksIterator and the Zstd stream are now managed by try-with-resources, so they are released when an earlier call throws. In shutdown(), the three calls that can fail are contained locally so db.closeE() is always reached; the interrupt flag is restored in the outermost finally so downstream joins still wait for their workers, and loaded keeps its original assignment site so the automatic reload retry path is unchanged.
@RLDE26
RLDE26 force-pushed the fix/issue-11602-resource-leak branch from 7b6b254 to 49355e5 Compare November 26, 2026 03:30
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.

[Enhancement] Avoid potential resource leaks on some paths

3 participants