Skip to content

Fix SessionConnection.reconnect() self-closing transport when enableRedirection is false - #19543

Open
JackieTien97 wants to merge 5 commits into
masterfrom
ty/fix-session-reconnect-self-close
Open

JackieTien97 wants to merge 5 commits into
masterfrom
ty/fix-session-reconnect-self-close

Conversation

@JackieTien97

@JackieTien97 JackieTien97 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #19542

Root Cause

  1. In SessionConnection.reconnect(), after init() opens a fresh transport, session.removeBrokenSessionConnection(this) is called, followed by unconditionally initializing/updating session.endPointToSessionConnection.compute(session.defaultEndPoint, ...) which closes any open v without checking v != this (introduced in Fix Session reconnection increase connection number #15677).
  2. In Session.removeBrokenSessionConnection(SessionConnection), cleanup of endPointToSessionConnection was gated behind if (enableRedirection). However, Session.open() populates endPointToSessionConnection whenever enableRedirection || enableQueryRedirection (and nodeUrls != null sets enableQueryRedirection = true), and reconnect() unconditionally created endPointToSessionConnection even when both flags were false.
  3. Consequently, when enableRedirection == false, removeBrokenSessionConnection(this) left defaultEndPoint -> this in endPointToSessionConnection. compute() then received v == this, observed v.transport.isOpen() == true (the newly reopened transport), and immediately invoked v.close() (this.close()), setting Thrift's outputStream_ to null while returning true. Every subsequent retry then failed immediately with TTransportException: Cannot write to null outputStream.

Fix

  • Session.registerReconnectedConnection() removes old endpoint mappings, publishes the recovered connection as the default, and tracks any distinct connection it displaced until cleanup finishes. Tree and table device routes are invalidated only when write redirection is enabled.
  • Graceful close and the reconnect handshake synchronize on the individual connection. This lets closeSession use the session ID returned by the completed handshake. Each connection retains the close state from its own open(). A delayed reconnect releases its transport even if the caller has already reopened the same Session. forceClose() can still interrupt a blocked transport, including one waiting for a close reply.
  • Enabling query redirection on an open session initializes its endpoint cache with the current default connection's actual endpoint. New connections and retried query RPCs use the current redirection setting. With both redirection flags off, queries use the default connection, including after reopening the session.

Regression coverage

  • With write and query redirection disabled, two failed insertTablet attempts are followed by a successful third attempt. With only query redirection enabled, a single failed insert succeeds on its first retry.
  • Local Thrift servers hold the handshake or the closeSession reply open to exercise graceful and forced shutdown before and after reconnect registration. The tests check the session ID received by the server, the number of close RPCs, the open transport, and whether the client replayed the operation.
  • Two-node tests check the endpoint that actually received each query, its enableRedirectQuery flag, and the number of server sessions opened across a redirection toggle, a failover, and a session reopen.

Verification

  • mvn clean test -pl iotdb-client/session -am passed all 372 Session and 162 Service-RPC tests. Ten regression cases failed on 8647809f with the same test code.
  • Eight close/reconnect race tests each passed 50 consecutive runs against local Thrift servers.
  • mvn spotless:check -pl iotdb-client/session passed. The full reactor passed mvn test-compile package -DskipTests in the default locale and with -P with-zh-locale.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The two default-connection retry tests reproduce the original failure on the base revision and pass on this commit. I reproduced the three cases below with two local Thrift servers.

Entry<TEndPoint, SessionConnection> entry = it.next();
if (entry.getValue().equals(sessionConnection)) {
removedEndPoints.add(entry.getKey());
it.remove();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Keep a reconnecting query connection visible to forceClose().

With only query redirection enabled, a query on non-default connection B can reopen its transport and remove B here before reconnect() makes B the default. A concurrent forceClose() then sees only A. I paused the reconnect in this window. B received the retried query after forceClose() returned and still had one open socket. On the base revision the retry stopped and both nodes had zero open sockets.

Please coordinate registration of the reopened connection with the session's close state so that a close in this window releases the new transport and stops the retry.

it.hasNext(); ) {
Entry<String, TEndPoint> entry = it.next();
if (removedEndPoints.contains(entry.getValue())) {
it.remove();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Guard device-route cleanup with enableRedirection.

Session.open(..., deviceIdToEndpoint, nodesSupplier) accepts a caller-supplied map. With write redirection disabled and query redirection enabled, I passed a read-only view containing a route to A and made a query fail over to B. B accepted the connection, then it.remove() threw UnsupportedOperationException before B received the query. The same query also deletes a route from a mutable map shared with writers.

Please keep the endpoint-to-connection cleanup independent of the write flag and only invalidate the tree and table device-route caches when write redirection is enabled.

logger.warn(SessionMessages.CLOSE_CONNECTION_FAILED, e.getMessage());
if (session.endPointToSessionConnection != null
|| session.enableRedirection
|| session.enableQueryRedirection) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P3] Initialize the endpoint cache when enabling query redirection on an open session.

If the session fails over from A to B while both redirection flags are off, the cache stays null. A later setEnableQueryRedirection(true) only changes the flag, so getQuerySessionConnection() keeps returning B even when the node supplier selects A. With A healthy again and the SDK's round-robin policy, the next four queries all went to B. On the base revision each node received two.

Please initialize the cache and register the current default connection when query redirection is enabled on an already-open session.

@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.61404% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 51.00%. Comparing base (c4e0c8b) to head (8647809).

Files with missing lines Patch % Lines
...rc/main/java/org/apache/iotdb/session/Session.java 95.23% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19543      +/-   ##
============================================
+ Coverage     50.99%   51.00%   +0.01%     
  Complexity      145      145              
============================================
  Files          5797     5797              
  Lines        430347   430409      +62     
  Branches      57344    57364      +20     
============================================
+ Hits         219459   219550      +91     
+ Misses       210888   210859      -29     

☔ 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.

…vice route cleanup, init cache on setEnableQueryRedirection

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I reran the three scenarios from the previous review on 88e8cb16. All three pass. The inline comments cover two additional client regressions and the failure in the new force-close test.

if (endPointToSessionConnection == null) {
endPointToSessionConnection = new ConcurrentHashMap<>();
}
SessionConnection previous = endPointToSessionConnection.put(newEndPoint, connection);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Keep the displaced connection reachable by forceClose() until its transport closes.

When a query on B reconnects to A, this put() replaces the original connection to A before staleConnection.close() waits for the closeSession reply. If forceClose() runs during that wait, its snapshot contains only the replacement. I delayed A's reply with the default socket timeout. forceClose() returned with the old transport still open, and the query thread kept waiting until A replied. On 35c48c7c, forceClose() closed the old transport and the query exited while the reply was still pending.

Please keep connections awaiting close in the force-close snapshot until their transports are released. The blocking closeSession RPC can still run outside connectionStateLock.

this.enableQueryRedirection = enableQueryRedirection;
if (enableQueryRedirection && !isClosed && !closing) {
if (defaultSessionConnection != null) {
defaultSessionConnection.setEnableRedirect(true);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Propagate false to open connections when query redirection is disabled.

On a session opened with redirection off, I called setEnableQueryRedirection(true) and then setEnableQueryRedirection(false). The public getter returned false, but the next query RPC to the default node still carried enableRedirectQuery=true. When the test server honored that flag and returned a redirect, the client threw StatementExecutionException. On 35c48c7c, the same RPC carried false and the query succeeded.

Please propagate both flag values to existing connections that can serve queries. An enable-then-disable test that checks the flag received by the server would cover this case.

testSession.open(false, 1000, Collections.emptyMap(), nodeSupplier);
Assert.assertFalse(testSession.enableRedirection);
Assert.assertTrue(testSession.enableQueryRedirection);
Assert.assertEquals(bothNodes.get(0), testSession.defaultEndPoint);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Make A the deterministic initial connection in this test.

Session shuffles nodeUrls before opening, so B can be the default when both nodes are seeds. The assertion then fails before the query or forceClose() runs. I saw this exact failure in 11 of 20 local runs and in both CI jobs. Windows unit tests · Sonar-Codecov

Please use A as the only initial seed and keep the node supplier pointed at B for queries and reconnects. That eliminated this endpoint assertion failure over 431 local runs. Two runs still failed elsewhere, including one that timed out waiting for registration. Reporting the query future's exception if it has already completed when the latch times out would help diagnose that failure.

… for forceClose, propagate query redirection flag, stabilize test seed

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The six scenarios from the previous two reviews pass on a0bc99ec, including 500 consecutive runs of the non-default reconnect test. I found one regression in graceful close and one gap in the new force-close regression test.

if (defaultSessionConnection != null && seen.add(defaultSessionConnection)) {
connections.add(defaultSessionConnection);
}
for (SessionConnection sessionConnection : closingConnections) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Avoid a second closeSession attempt on a connection already closing.

Both Session.close() and forceClose() use this snapshot. When a query on B reconnects to A, the reconnect thread can already be waiting for A to acknowledge closeSession on the displaced connection. A single application call to Session.close() then picks up that same connection here and tries to close it again. Once A acknowledges the first call, the second attempt can hit the closed transport and make Session.close() throw IoTDBConnectionException. This happened in all three runs on a0bc99ec. The same three runs on 88e8cb16 returned normally.

Please keep displaced connections visible to forceClose() and give the in-progress graceful close sole ownership of its closeSession RPC. If ordinary close() needs to wait for it, it can join that operation.

testSession.forceClose();

try {
queryFuture.get(5, TimeUnit.SECONDS);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P3] Assert that forceClose() closes the displaced transport before the server replies.

The client has a one-second socket timeout from open(false, 1000, ...). If forceClose() misses the old transport, the blocked closeSession RPC can time out on its own, and the query can still throw the expected exception within this five-second wait. I ran this test three times against 88e8cb16, which leaves the socket open when forceClose() returns. It passed all three times.

Please capture the original transport before failover, disable the client read timeout for this test, and hold the server reply until after asserting that the transport is closed immediately on return from forceClose(). Release the server latch in finally as well. With those changes the test failed 3/3 times on 88e8cb16 and passed 3/3 times on a0bc99ec.

@sonarqubecloud

sonarqubecloud Bot commented Dec 5, 2026

Copy link
Copy Markdown

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed 8647809f for correctness, concurrency, performance, and memory footprint.

  • The #19542 self-closing bug when enableRedirection == false is resolved, steady-state read/write hot paths have no lock/CPU regression, and moving staleConnection.close() outside ConcurrentHashMap bucket locks improves reconnect concurrency.
  • However, I reproduced 1 P1 regression in graceful Session.close(), several P2 consistency gaps in setEnableQueryRedirection / registerReconnectedConnection, and 1 P3 per-Session memory overhead (~304 B eager IdentityHashMap) — see inline comments.
  • PR description nit: The ### Fix section in the PR description still describes the initial 35c48c7c implementation (compute() with v != this, and un-gated deviceIdToEndpoint cleanup) rather than registerReconnectedConnection(), the if (!enableRedirection) route-cleanup guard, and the updated setEnableQueryRedirection(boolean) behavior.

session.endPointToSessionConnection = new ConcurrentHashMap<>();
if (forceClosed || session.isClosing()) {
forceCloseTransport();
return false;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P1] Do not call forceCloseTransport() during graceful Session.close() when racing with reconnect().

Session.closing is set to true by both graceful Session.close() and Session.forceClose(), and reconnect() now calls forceCloseTransport() whenever session.isClosing() is true (L1281, L1299 via !registerReconnectedConnection(...), and L1303). When this is already reachable in Session (or has just been registered by registerReconnectedConnection returning true before L1303), a concurrent graceful Session.close() snapshots this in connectionsToClose and starts this.close() (client.closeSession(req)). The reconnect thread then sees session.isClosing() == true and invokes this.forceCloseTransport(), closing this.transport underneath the in-flight closeSession RPC and causing graceful Session.close() to throw IoTDBConnectionException(CLOSE_SESSION_ERROR) (while also skipping TSCloseSessionReq if Session.close() has not yet reached or already passed this).

I reproduced this failure deterministically in both windows (post-registration at L1303 and pre-registration at L1281/L1299).

Suggestions:

  1. Separate closing (graceful) from forceClosing (immediate abort): once registerReconnectedConnection returns true, L1303 must not forceCloseTransport() on graceful closing (Session.close() / forceClose() is already guaranteed to observe this under connectionStateLock).
  2. Coordinate ownership for a connection inside init() so graceful Session.close() does not race with forceCloseTransport(), and gracefully close any newly opened session if Session.close() already snapshotted past it.
  3. Also check session != null && session.isClosing() in callWithRetry (L990) and callWithRetryAndReconnect (L1072; note L1106 ignores reconnect()'s return value) so retries stop promptly on graceful close.

}
endPointToSessionConnection = connections;
} else if (defaultEndPoint != null && defaultSessionConnection != null) {
endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Fix endpoint-map corruption and enableRedirect / cache lifecycle inconsistencies around setEnableQueryRedirection(boolean).

Three issues reproduced with two local Thrift servers:

  1. Wrong endpoint -> connection mapping after handleQueryRedirection() (L4906-L4912): handleQueryRedirection(endPoint) (L1792) updates defaultSessionConnection (e.g. connB on epB) without updating defaultEndPoint (still epA). If epA's broken connection was removed from endPointToSessionConnection, calling setEnableQueryRedirection(true) executes putIfAbsent(defaultEndPoint, defaultSessionConnection), inserting epA -> connB (connected to epB) and leaving connB under two keys (epA and epB), which misroutes epA traffic and allows two concurrent failovers to displace and close connB twice. Prefer defaultSessionConnection.getEndPoint() != null ? defaultSessionConnection.getEndPoint() : defaultEndPoint.
  2. Newly created query connections and post-failover default connections lose enableRedirect = true (L1160, L1565): getQuerySessionConnection() (L1160) constructs new SessionConnection instances with enableRedirect == false instead of calling newConnection.setEnableRedirect(enableQueryRedirection) (even in testEnableQueryRedirectionOnOpenSessionAfterFailoverRoutesAcrossNodes, serverA receives enableRedirectQuery=false). Worse, if such a connection (or one created by handleRedirection()) later fails over via reconnect(), registerReconnectedConnection() replaces defaultSessionConnection with it without calling connection.setEnableRedirect(enableQueryRedirection), silently flipping defaultSessionConnection.isEnableRedirect() to false while session.isEnableQueryRedirection() remains true. Also consider making SessionConnection.enableRedirect, Session.enableQueryRedirection, and Session.defaultSessionConnection volatile since SessionPool.setEnableQueryRedirection() mutates borrowed sessions from another thread.
  3. Toggling true -> false when enableRedirection == false leaks multi-node routing and duplicates connections on reopen (L1148, L583/L666/L715, L819): Toggling setEnableQueryRedirection(true) then false leaves endPointToSessionConnection non-null; because getQuerySessionConnection() (L1148) only checks endPointToSessionConnection == null, subsequent queries still round-robin via availableNodes.getQueryEndPoint() and open new connections across cluster nodes when both redirection flags are false. Furthermore, after close() (finishClose() sets an empty ConcurrentHashMap) followed by open(), open() skips initialization when both flags are false without resetting endPointToSessionConnection = null, causing the next query to open a second duplicate connection to defaultEndPoint.

if (staleConnection.transport != null && staleConnection.transport.isOpen()) {
try {
staleConnection.close();
} catch (IoTDBConnectionException e) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P2] Catch RuntimeException around staleConnection.close() and exclude closingConnections from getSessionConnections(false).

  1. Session.close() (L744) and forceCloseTransport() catch RuntimeException, whereas staleConnection.close() here only catches IoTDBConnectionException. When a concurrent forceClose() closes AutoScalingBufferReadTransport (resetting temporaryBuffer = null; pos = 0; limit = 0 without synchronization) while staleConnection.close() is reading the reply, an uncaught RuntimeException can escape registerReconnectedConnection() instead of logging and returning cleanly.
  2. In getSessionConnections(boolean) (L791-L812), when !includeClosingConnections, seen is not pre-seeded with closingConnections.keySet(). Because handleQueryRedirection() (L1792) calls setDefaultSessionConnection(connection) outside connectionStateLock, an interleaving query redirect can write a displaced staleConnection back into defaultSessionConnection while its close is in progress, causing Session.close() to pick it up and close it a second time. Pre-seeding seen.addAll(closingConnections.keySet()) when !includeClosingConnections, coordinating handleQueryRedirection's setDefaultSessionConnection under connectionStateLock, and using closingConnections.remove(staleConnection, staleCloseLatch) at L1589 closes this gap.

private boolean isClosed = true;
private volatile boolean closing;
private final Object connectionStateLock = new Object();
private final Map<SessionConnection, CountDownLatch> closingConnections = new IdentityHashMap<>();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[P3] Lazily initialize closingConnections to avoid ~304 B eager allocation per Session.

new IdentityHashMap<>() eagerly allocates Object[64] (~304 B per Session with compressed OOPs) on every Session construction, even though closingConnections is only populated in the rare failover collision case and all accesses are already guarded by synchronized (connectionStateLock). Keeping closingConnections = null until staleConnection != null (and initializing with new IdentityHashMap<>(4)) avoids this per-session memory footprint in large SessionPool deployments. (Similarly, removedEndPoints in removeBrokenSessionConnection at L1603 can be lazily allocated on first match.)

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.

[Bug] SessionConnection.reconnect() closes itself when enableRedirection is false, causing TTransportException: Cannot write to null outputStream

1 participant