Skip to content

Add coreSize and maxIdleTime conf for SessionPool and TableSessionPool - #19424

Merged
JackieTien97 merged 4 commits into
masterfrom
poolConf
Nov 27, 2026
Merged

JackieTien97 merged 4 commits into
masterfrom
poolConf

Conversation

@Wei-hao-Li

Copy link
Copy Markdown
Collaborator

No description provided.

Signed-off-by: Weihao Li <18110526956@163.com>
# Conflicts:
#	iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.42857% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.62%. Comparing base (3d643e7) to head (54668eb).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...ava/org/apache/iotdb/session/pool/SessionPool.java 90.90% 9 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19424      +/-   ##
============================================
+ Coverage     50.61%   50.62%   +0.01%     
  Complexity      133      133              
============================================
  Files          5786     5786              
  Lines        427094   427181      +87     
  Branches      56761    56775      +14     
============================================
+ Hits         216179   216273      +94     
+ Misses       210915   210908       -7     

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

- Extract coreSize/maxIdleTimeInMs validation into validateIdleConfig to
  keep the builder constructor within the cognitive complexity limit
  (java:S3776)
- Use notifyAll instead of notify when eviction frees pool capacity so
  every waiting borrower can re-check size < maxSize (java:S2446)

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for adding idle session eviction support for SessionPool and TableSessionPool. Keeping coreSize = 0 and maxIdleTimeInMs = 0 by default preserves backward compatibility, evicting from the tail of the LIFO queue naturally ages out cold connections, and closing evicted sessions outside synchronized (this) avoids holding the monitor during I/O.

Please address the inline comments before merging—in particular:

  1. Restore the if (closed) check in getSession() that appears to have been dropped during merge-conflict resolution.
  2. Switch idle timestamps from System.currentTimeMillis() to monotonic System.nanoTime() so clock jumps cannot block or prematurely trigger eviction.
  3. Isolate idle eviction from NodesSupplier's single-threaded executorService and guard the scheduled task against uncaught Throwable.
  4. Please also fill in the PR description with a concrete usage example and expected behavior (per AGENTS.md for user-visible features).

Comment on lines -771 to -773
if (closed) {
throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This if (closed) check looks like it was accidentally dropped while resolving the merge conflict in be6a34a462. Without it, a waiter woken up by close() performs an unnecessary queue.poll() and this.notify() before re-entering the loop to observe closed—and if queue.poll() ever yields a session as closed becomes true (e.g., via a monitor-releasing test hook like BlockingAfterPollDeque), the loop exits and returns a session from a closed pool. Please restore it (and consider checking if (closed) right after this.wait(1000) before polling as well).

Comment on lines +600 to +607
if (maxIdleTimeInMs > 0) {
if (executorService == null) {
initThreadPool();
}
long checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 60_000L));
executorService.scheduleWithFixedDelay(
this::evictIdleSessions, checkIntervalInMs, checkIntervalInMs, TimeUnit.MILLISECONDS);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Several issues with scheduling idle eviction here:

  1. Head-of-line blocking on the single-threaded executorService: initThreadPool() creates a single-thread executor named PeriodicalUpdateDNList shared with NodesSupplier. evictIdleSessions() calls closeSession(), which sends a synchronous client.closeSession Thrift RPC (with default connectionTimeoutInMs = 0, i.e., no socket timeout). A stalled/blackholed DataNode during eviction will block that single thread and freeze NodesSupplier's periodic refresh and requestRefresh() failover; conversely, NodesSupplier.run() (60s RPC timeout per candidate) can starve eviction. Using a dedicated single-thread scheduled executor (e.g. SessionPoolIdleEvictor, shut down in close()) isolates the two and also avoids a misleading thread name when enableAutoFetch == false.
  2. Uncaught Throwable permanently cancels the periodic task: @SuppressWarnings("unsafeThreadSchedule") is placed on the whole constructor to bypass checkstyle, while evictIdleSessions() has no outer try { ... } catch (Throwable t) guard (closeSession only catches Exception). Any uncaught RuntimeException/Error will silently kill all future eviction runs. Please wrap the scheduled runnable with a Throwable catch + log, and narrow @SuppressWarnings("unsafeThreadSchedule") to a small helper method (also note that scheduling this::evictIdleSessions inside a non-final class constructor publishes this before subclass constructors complete—cf. NodesSupplier.createNodeSupplier).
  3. Skip scheduling when coreSize == maxSize: Guard with if (maxIdleTimeInMs > 0 && coreSize < maxSize) so we don't spawn a background thread and run no-op ticks when size can never exceed coreSize.
  4. Eviction delay up to ~2 * maxIdleTimeInMs: With checkIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 60_000L)), for maxIdleTimeInMs in (1s, 60s] a session returned just after a tick can stay idle for nearly 2 * maxIdleTimeInMs before eviction. Using e.g. Math.max(1_000L, Math.min(maxIdleTimeInMs / 2, 60_000L)) (or documenting the periodic check cadence) would tighten this.

Comment on lines +1029 to +1034
long now = System.currentTimeMillis();
while (size > coreSize) {
IdleSession idleSession = queue.peekLast();
if (idleSession == null || now - idleSession.idleSince <= maxIdleTimeInMs) {
break;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please use monotonic System.nanoTime() instead of wall-clock System.currentTimeMillis() (here and in putBack / tryConstructNewSession). Because this loop assumes tail-to-head timestamp monotonicity and breaks on the first non-expired tail entry, a backward clock jump (NTP/manual adjustment) leaves a future-stamped entry at the tail that blocks eviction of all newer idle sessions behind it until wall time catches up, while a forward jump prematurely evicts active-recently sessions. Storing idleSinceNanos = System.nanoTime() and comparing (nowNanos - idleSession.idleSinceNanos) > TimeUnit.MILLISECONDS.toNanos(maxIdleTimeInMs) avoids both issues safely (including for Long.MAX_VALUE).

Comment on lines +1006 to +1015
private static void validateIdleConfig(int coreSize, int maxSize, long maxIdleTimeInMs) {
if (coreSize < 0 || coreSize > maxSize) {
throw new IllegalArgumentException(
String.format(SessionMessages.SESSION_POOL_CORE_SIZE_ARG_ILLEGAL, coreSize, maxSize));
}
if (maxIdleTimeInMs < 0) {
throw new IllegalArgumentException(
String.format(SessionMessages.SESSION_POOL_MAX_IDLE_TIME_ARG_ILLEGAL, maxIdleTimeInMs));
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor validation edge case: if a caller passes maxSize <= 0 with the default coreSize = 0, maxSize(-1) throws a confusing message blaming coreSize (the coreSize 0 must be in [0, maxSize(-1)]), and maxSize(0) passes silently and times out on every getSession(). Consider validating maxSize <= 0 explicitly before checking coreSize.

Comment on lines +108 to +109
private int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE;
private long maxIdleTimeInMs = SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SessionPool / ISessionPool provide getters for the other pool settings (getMaxSize(), getWaitToGetSessionTimeoutInMs(), getConnectionTimeoutInMs(), etc.). Consider adding getCoreSize() and getMaxIdleTimeInMs() (as default methods on ISessionPool if exposed on the interface to keep backward compatibility), which would also eliminate the Whitebox.getInternalState reflection in SessionPoolTest. Both fields can also be final if assigned defaults in the non-builder constructors.

Comment on lines +3885 to +3895
/**
* Sets the minimum number of sessions kept in the pool. Idle sessions will not be evicted when
* the total number of sessions reaches this value.
*
* @param coreSize the minimum number of sessions, must be in [0, maxSize]
* @return this builder
*/
public Builder coreSize(int coreSize) {
this.coreSize = coreSize;
return this;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggest clarifying in both SessionPool.Builder#coreSize and TableSessionPoolBuilder#coreSize Javadocs that:

  1. Sessions are still created lazily on demand (not pre-warmed to coreSize at construction time).
  2. coreSize only takes effect when maxIdleTimeInMs > 0.
  3. coreSize bounds the total number of sessions (size, including borrowed and idle sessions), not idle sessions alone.

ConcurrentLinkedDeque<ISession> queue = new ConcurrentLinkedDeque<>();
queue.add(session);
Whitebox.setInternalState(sessionPool, "queue", queue);
((SessionPool) sessionPool).putBack(session);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

setUp() already calls ((SessionPool) sessionPool).putBack(session). Previously this test replaced the queue field with a fresh 1-element deque; calling putBack(session) here now pushes a second duplicate entry for session into queue. This redundant call can be removed.

Comment on lines +318 to +355
public void testEvictIdleSessions() throws Exception {
SessionPool pool =
new SessionPool.Builder()
.host("localhost")
.port(1234)
.maxSize(10)
.coreSize(2)
.maxIdleTimeInMs(5_000L)
.enableAutoFetch(false)
.build();
try {
List<ISession> sessions = new ArrayList<>();
for (int i = 0; i < 5; i++) {
sessions.add(Mockito.mock(ISession.class));
}
// push puts a session at the head, so sessions.get(0) ends up at the tail (earliest idle)
long idleSince = System.currentTimeMillis() - 20_000L;
for (ISession s : sessions) {
pool.putBack(s);
Whitebox.setInternalState(idleQueueOf(pool).peekFirst(), "idleSince", idleSince);
}
Whitebox.setInternalState(pool, "size", 5);

Whitebox.invokeMethod(pool, "evictIdleSessions");

assertEquals(2, idleQueueOf(pool).size());
int size = Whitebox.getInternalState(pool, "size");
assertEquals(2, size);
// the 3 earliest idle sessions are evicted, the 2 most recently returned ones are kept
Mockito.verify(sessions.get(0)).close();
Mockito.verify(sessions.get(1)).close();
Mockito.verify(sessions.get(2)).close();
Mockito.verify(sessions.get(3), Mockito.never()).close();
Mockito.verify(sessions.get(4), Mockito.never()).close();
} finally {
pool.close();
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggest expanding test coverage for the remaining eviction branches (Codecov also notes 6 uncovered lines in SessionPool.java):

  • Mixed expired and non-expired idle sessions in queue (exercising the <= maxIdleTimeInMs early-break branch).
  • Borrowed/occupied sessions + idle sessions when size > coreSize (exercising the idleSession == null break and verifying coreSize counts total sessions).
  • coreSize == 0 evicting all idle sessions down to 0.
  • evictIdleSessions() being a no-op after pool.close().
  • Scheduled background eviction firing end-to-end and stopping cleanly on close(), plus invalid-argument tests for TableSessionPoolBuilder.

Minor test hygiene: wrap pool.close() / tableSessionPool.close() in try/finally in testBuilderCoreSizeAndMaxIdleTime and testTableSessionPoolBuilderCoreSizeAndMaxIdleTime, and use a larger maxIdleTimeInMs (e.g., 60_000L) in direct evictIdleSessions unit tests so the live background timer cannot race with Whitebox.setInternalState on a slow runner.

- Restore the closed check in getSession() after wait and after poll, and
  close the polled session so it is neither handed out nor leaked when the
  pool is closed concurrently
- Use monotonic System.nanoTime() for idle timestamps so wall-clock jumps
  cannot block or prematurely trigger eviction
- Run idle eviction on a dedicated SessionPoolIdleEvictor scheduler instead
  of the datanode-list updater, guard the periodic task against uncaught
  Throwable, narrow the unsafeThreadSchedule suppression to a helper, and
  skip scheduling when coreSize == maxSize
- Halve the check interval to bound eviction delay at ~maxIdleTimeInMs
- Validate maxSize > 0 before coreSize so the error message points at the
  right parameter
- Add getCoreSize()/getMaxIdleTimeInMs() and use them in tests
- Clarify coreSize javadoc: lazy creation, effective only when
  maxIdleTimeInMs > 0, and it bounds total sessions (borrowed and idle)
- Expand eviction tests: mixed expired/fresh early break, borrowed+idle
  counting towards coreSize, coreSize == 0 draining all, no-op after close,
  scheduled eviction end-to-end, and invalid arguments for
  TableSessionPoolBuilder; drop a redundant putBack in
  SessionPoolExceptionTest
@sonarqubecloud

Copy link
Copy Markdown

@JackieTien97
JackieTien97 merged commit fb2f81d into master Nov 27, 2026
41 of 42 checks passed
@JackieTien97
JackieTien97 deleted the poolConf branch November 27, 2026 11:21
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.

2 participants