Skip to content

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

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

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

Conversation

@JackieTien97

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

  • SessionConnection.reconnect():
    • Guard v != this in session.endPointToSessionConnection.compute(...) so reconnect() never closes itself while still closing any distinct stale connection mapped to the same endpoint (Fix Session reconnection increase connection number #15677).
    • Only initialize/update session.endPointToSessionConnection when session.endPointToSessionConnection != null || session.enableRedirection || session.enableQueryRedirection.
  • Session.removeBrokenSessionConnection(SessionConnection):
    • Clean all entries matching sessionConnection from endPointToSessionConnection whenever the map is non-null (not gated behind enableRedirection), and remove all corresponding endpoints from deviceIdToEndpoint and tableModelDeviceIdToEndpoint.

Tests

Added unit tests in SessionConnectionTest and SessionTest:

  • testReconnectWithoutRedirectionDoesNotSelfClose: real local TThreadPoolServer with enableRedirection = false and enableQueryRedirection = false, failing 2 consecutive insertTablet calls and succeeding on the 3rd.
  • testReconnectWithQueryRedirectionAndWriteRedirectionDisabledDoesNotSelfClose: real local TThreadPoolServer with nodeUrls (enableQueryRedirection = true) and enableRedirection = false, failing the 1st insertTablet call and succeeding on the 2nd.
  • testReconnectStillClosesDifferentStaleConnectionForSameEndPoint: verifies Fix Session reconnection increase connection number #15677 behavior is preserved when a different open connection is mapped to defaultEndPoint.
  • testRemoveBrokenSessionConnectionWhenRedirectionDisabled: verifies removeBrokenSessionConnection() removes all matching entries from endPointToSessionConnection, deviceIdToEndpoint, and tableModelDeviceIdToEndpoint even when enableRedirection == false.

Verified with:

  • mvn -pl iotdb-client/session spotless:apply && mvn -pl iotdb-client/session spotless:check
  • mvn -pl iotdb-client/session -am test -Dsurefire.failIfNoSpecifiedTests=false -Dtest=SessionConnectionTest,SessionTest,SessionCacheLeaderTest,BrokenSessionConnectionTest,SessionSeedNodeFallbackTest,ThriftConnectionLifecycleTest,SessionPoolTest,SessionPoolCloseTest (324 tests run, 0 failures, 0 errors, 0 skipped)

@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 94.11765% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.99%. Comparing base (c4e0c8b) to head (35c48c7).

Files with missing lines Patch % Lines
...va/org/apache/iotdb/session/SessionConnection.java 80.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             master   #19543   +/-   ##
=========================================
  Coverage     50.99%   50.99%           
  Complexity      145      145           
=========================================
  Files          5797     5797           
  Lines        430347   430348    +1     
  Branches      57344    57345    +1     
=========================================
+ Hits         219459   219465    +6     
+ Misses       210888   210883    -5     

☔ 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
@sonarqubecloud

sonarqubecloud Bot commented Dec 4, 2026

Copy link
Copy Markdown

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