Repository navigation
Add coreSize and maxIdleTime conf for SessionPool and TableSessionPool - #19424
Conversation
# Conflicts: # iotdb-client/session/src/main/java/org/apache/iotdb/session/pool/SessionPool.java
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
- 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
left a comment
There was a problem hiding this comment.
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:
- Restore the
if (closed)check ingetSession()that appears to have been dropped during merge-conflict resolution. - Switch idle timestamps from
System.currentTimeMillis()to monotonicSystem.nanoTime()so clock jumps cannot block or prematurely trigger eviction. - Isolate idle eviction from
NodesSupplier's single-threadedexecutorServiceand guard the scheduled task against uncaughtThrowable. - Please also fill in the PR description with a concrete usage example and expected behavior (per
AGENTS.mdfor user-visible features).
| if (closed) { | ||
| throw new IoTDBConnectionException(SESSION_POOL_IS_CLOSED); | ||
| } |
There was a problem hiding this comment.
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).
| 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); | ||
| } |
There was a problem hiding this comment.
Several issues with scheduling idle eviction here:
- Head-of-line blocking on the single-threaded
executorService:initThreadPool()creates a single-thread executor namedPeriodicalUpdateDNListshared withNodesSupplier.evictIdleSessions()callscloseSession(), which sends a synchronousclient.closeSessionThrift RPC (with defaultconnectionTimeoutInMs = 0, i.e., no socket timeout). A stalled/blackholed DataNode during eviction will block that single thread and freezeNodesSupplier's periodic refresh andrequestRefresh()failover; conversely,NodesSupplier.run()(60s RPC timeout per candidate) can starve eviction. Using a dedicated single-thread scheduled executor (e.g.SessionPoolIdleEvictor, shut down inclose()) isolates the two and also avoids a misleading thread name whenenableAutoFetch == false. - Uncaught
Throwablepermanently cancels the periodic task:@SuppressWarnings("unsafeThreadSchedule")is placed on the whole constructor to bypass checkstyle, whileevictIdleSessions()has no outertry { ... } catch (Throwable t)guard (closeSessiononly catchesException). Any uncaughtRuntimeException/Errorwill silently kill all future eviction runs. Please wrap the scheduled runnable with aThrowablecatch + log, and narrow@SuppressWarnings("unsafeThreadSchedule")to a small helper method (also note that schedulingthis::evictIdleSessionsinside a non-finalclass constructor publishesthisbefore subclass constructors complete—cf.NodesSupplier.createNodeSupplier). - Skip scheduling when
coreSize == maxSize: Guard withif (maxIdleTimeInMs > 0 && coreSize < maxSize)so we don't spawn a background thread and run no-op ticks whensizecan never exceedcoreSize. - Eviction delay up to ~
2 * maxIdleTimeInMs: WithcheckIntervalInMs = Math.max(1_000L, Math.min(maxIdleTimeInMs, 60_000L)), formaxIdleTimeInMsin(1s, 60s]a session returned just after a tick can stay idle for nearly2 * maxIdleTimeInMsbefore eviction. Using e.g.Math.max(1_000L, Math.min(maxIdleTimeInMs / 2, 60_000L))(or documenting the periodic check cadence) would tighten this.
| long now = System.currentTimeMillis(); | ||
| while (size > coreSize) { | ||
| IdleSession idleSession = queue.peekLast(); | ||
| if (idleSession == null || now - idleSession.idleSince <= maxIdleTimeInMs) { | ||
| break; | ||
| } |
There was a problem hiding this comment.
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).
| 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)); | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| private int coreSize = SessionConfig.DEFAULT_SESSION_POOL_CORE_SIZE; | ||
| private long maxIdleTimeInMs = SessionConfig.DEFAULT_SESSION_POOL_MAX_IDLE_TIME_IN_MS; |
There was a problem hiding this comment.
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.
| /** | ||
| * 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; | ||
| } |
There was a problem hiding this comment.
Suggest clarifying in both SessionPool.Builder#coreSize and TableSessionPoolBuilder#coreSize Javadocs that:
- Sessions are still created lazily on demand (not pre-warmed to
coreSizeat construction time). coreSizeonly takes effect whenmaxIdleTimeInMs > 0.coreSizebounds 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); |
There was a problem hiding this comment.
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.
| 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(); | ||
| } | ||
| } |
There was a problem hiding this comment.
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<= maxIdleTimeInMsearly-break branch). - Borrowed/occupied sessions + idle sessions when
size > coreSize(exercising theidleSession == nullbreak and verifyingcoreSizecounts total sessions). coreSize == 0evicting all idle sessions down to 0.evictIdleSessions()being a no-op afterpool.close().- Scheduled background eviction firing end-to-end and stopping cleanly on
close(), plus invalid-argument tests forTableSessionPoolBuilder.
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
|



No description provided.