Repository navigation
Fix SessionConnection.reconnect() self-closing transport when enableRedirection is false - #19543
JackieTien97 wants to merge 5 commits into
Conversation
…edirection is false
JackieTien97
left a comment
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
[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(); |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
…vice route cleanup, init cache on setEnableQueryRedirection
JackieTien97
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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.
…ose() and strengthen forceClose test
|
JackieTien97
left a comment
There was a problem hiding this comment.
Reviewed 8647809f for correctness, concurrency, performance, and memory footprint.
- The
#19542self-closing bug whenenableRedirection == falseis resolved, steady-state read/write hot paths have no lock/CPU regression, and movingstaleConnection.close()outsideConcurrentHashMapbucket locks improves reconnect concurrency. - However, I reproduced 1 P1 regression in graceful
Session.close(), several P2 consistency gaps insetEnableQueryRedirection/registerReconnectedConnection, and 1 P3 per-Sessionmemory overhead (~304 B eagerIdentityHashMap) — see inline comments. - PR description nit: The
### Fixsection in the PR description still describes the initial35c48c7cimplementation (compute()withv != this, and un-gateddeviceIdToEndpointcleanup) rather thanregisterReconnectedConnection(), theif (!enableRedirection)route-cleanup guard, and the updatedsetEnableQueryRedirection(boolean)behavior.
| session.endPointToSessionConnection = new ConcurrentHashMap<>(); | ||
| if (forceClosed || session.isClosing()) { | ||
| forceCloseTransport(); | ||
| return false; |
There was a problem hiding this comment.
[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:
- Separate
closing(graceful) fromforceClosing(immediate abort): onceregisterReconnectedConnectionreturnstrue,L1303must notforceCloseTransport()on gracefulclosing(Session.close()/forceClose()is already guaranteed to observethisunderconnectionStateLock). - Coordinate ownership for a connection inside
init()so gracefulSession.close()does not race withforceCloseTransport(), and gracefully close any newly opened session ifSession.close()already snapshotted past it. - Also check
session != null && session.isClosing()incallWithRetry(L990) andcallWithRetryAndReconnect(L1072; noteL1106ignoresreconnect()'s return value) so retries stop promptly on graceful close.
| } | ||
| endPointToSessionConnection = connections; | ||
| } else if (defaultEndPoint != null && defaultSessionConnection != null) { | ||
| endPointToSessionConnection.putIfAbsent(defaultEndPoint, defaultSessionConnection); |
There was a problem hiding this comment.
[P2] Fix endpoint-map corruption and enableRedirect / cache lifecycle inconsistencies around setEnableQueryRedirection(boolean).
Three issues reproduced with two local Thrift servers:
- Wrong endpoint -> connection mapping after
handleQueryRedirection()(L4906-L4912):handleQueryRedirection(endPoint)(L1792) updatesdefaultSessionConnection(e.g.connBonepB) without updatingdefaultEndPoint(stillepA). IfepA's broken connection was removed fromendPointToSessionConnection, callingsetEnableQueryRedirection(true)executesputIfAbsent(defaultEndPoint, defaultSessionConnection), insertingepA -> connB(connected toepB) and leavingconnBunder two keys (epAandepB), which misroutesepAtraffic and allows two concurrent failovers to displace and closeconnBtwice. PreferdefaultSessionConnection.getEndPoint() != null ? defaultSessionConnection.getEndPoint() : defaultEndPoint. - Newly created query connections and post-failover default connections lose
enableRedirect = true(L1160,L1565):getQuerySessionConnection()(L1160) constructs newSessionConnectioninstances withenableRedirect == falseinstead of callingnewConnection.setEnableRedirect(enableQueryRedirection)(even intestEnableQueryRedirectionOnOpenSessionAfterFailoverRoutesAcrossNodes,serverAreceivesenableRedirectQuery=false). Worse, if such a connection (or one created byhandleRedirection()) later fails over viareconnect(),registerReconnectedConnection()replacesdefaultSessionConnectionwith it without callingconnection.setEnableRedirect(enableQueryRedirection), silently flippingdefaultSessionConnection.isEnableRedirect()tofalsewhilesession.isEnableQueryRedirection()remainstrue. Also consider makingSessionConnection.enableRedirect,Session.enableQueryRedirection, andSession.defaultSessionConnectionvolatilesinceSessionPool.setEnableQueryRedirection()mutates borrowed sessions from another thread. - Toggling
true -> falsewhenenableRedirection == falseleaks multi-node routing and duplicates connections on reopen (L1148,L583/L666/L715,L819): TogglingsetEnableQueryRedirection(true)thenfalseleavesendPointToSessionConnectionnon-null; becausegetQuerySessionConnection()(L1148) only checksendPointToSessionConnection == null, subsequent queries still round-robin viaavailableNodes.getQueryEndPoint()and open new connections across cluster nodes when both redirection flags arefalse. Furthermore, afterclose()(finishClose()sets an emptyConcurrentHashMap) followed byopen(),open()skips initialization when both flags arefalsewithout resettingendPointToSessionConnection = null, causing the next query to open a second duplicate connection todefaultEndPoint.
| if (staleConnection.transport != null && staleConnection.transport.isOpen()) { | ||
| try { | ||
| staleConnection.close(); | ||
| } catch (IoTDBConnectionException e) { |
There was a problem hiding this comment.
[P2] Catch RuntimeException around staleConnection.close() and exclude closingConnections from getSessionConnections(false).
Session.close()(L744) andforceCloseTransport()catchRuntimeException, whereasstaleConnection.close()here only catchesIoTDBConnectionException. When a concurrentforceClose()closesAutoScalingBufferReadTransport(resettingtemporaryBuffer = null; pos = 0; limit = 0without synchronization) whilestaleConnection.close()is reading the reply, an uncaughtRuntimeExceptioncan escaperegisterReconnectedConnection()instead of logging and returning cleanly.- In
getSessionConnections(boolean)(L791-L812), when!includeClosingConnections,seenis not pre-seeded withclosingConnections.keySet(). BecausehandleQueryRedirection()(L1792) callssetDefaultSessionConnection(connection)outsideconnectionStateLock, an interleaving query redirect can write a displacedstaleConnectionback intodefaultSessionConnectionwhile its close is in progress, causingSession.close()to pick it up and close it a second time. Pre-seedingseen.addAll(closingConnections.keySet())when!includeClosingConnections, coordinatinghandleQueryRedirection'ssetDefaultSessionConnectionunderconnectionStateLock, and usingclosingConnections.remove(staleConnection, staleCloseLatch)atL1589closes this gap.
| private boolean isClosed = true; | ||
| private volatile boolean closing; | ||
| private final Object connectionStateLock = new Object(); | ||
| private final Map<SessionConnection, CountDownLatch> closingConnections = new IdentityHashMap<>(); |
There was a problem hiding this comment.
[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.)



Closes #19542
Root Cause
SessionConnection.reconnect(), afterinit()opens a fresh transport,session.removeBrokenSessionConnection(this)is called, followed by unconditionally initializing/updatingsession.endPointToSessionConnection.compute(session.defaultEndPoint, ...)which closes any openvwithout checkingv != this(introduced in Fix Session reconnection increase connection number #15677).Session.removeBrokenSessionConnection(SessionConnection), cleanup ofendPointToSessionConnectionwas gated behindif (enableRedirection). However,Session.open()populatesendPointToSessionConnectionwheneverenableRedirection || enableQueryRedirection(andnodeUrls != nullsetsenableQueryRedirection = true), andreconnect()unconditionally createdendPointToSessionConnectioneven when both flags werefalse.enableRedirection == false,removeBrokenSessionConnection(this)leftdefaultEndPoint -> thisinendPointToSessionConnection.compute()then receivedv == this, observedv.transport.isOpen() == true(the newly reopened transport), and immediately invokedv.close()(this.close()), setting Thrift'soutputStream_tonullwhile returningtrue. Every subsequent retry then failed immediately withTTransportException: 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.closeSessionuse the session ID returned by the completed handshake. Each connection retains the close state from its ownopen(). A delayed reconnect releases its transport even if the caller has already reopened the sameSession.forceClose()can still interrupt a blocked transport, including one waiting for a close reply.Regression coverage
insertTabletattempts are followed by a successful third attempt. With only query redirection enabled, a single failed insert succeeds on its first retry.closeSessionreply 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.enableRedirectQueryflag, 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 -ampassed all 372 Session and 162 Service-RPC tests. Ten regression cases failed on8647809fwith the same test code.mvn spotless:check -pl iotdb-client/sessionpassed. The full reactor passedmvn test-compile package -DskipTestsin the default locale and with-P with-zh-locale.