Skip to content

Commit a63c625

Browse files
authored
fix(harness): evict idle turn gates and make the lease idempotent (#3533)
## Description Fixes #3532 Two defects live in the lease that `LocalSessionTurnGate.acquire(String)` returns. The issue reports the first; the second is in the same three lines and is arguably worse, because it breaks the gate's own contract. **1. Idle keys are never evicted.** `acquire` inserted a `Semaphore` with `computeIfAbsent` and the lease only called `release()`, so every key ever seen stayed in the map and its semaphore could never be collected. **2. `close()` is not idempotent, and `TurnLease` says it must be.** `TurnLease` carries "Implementations must be idempotent: calling `close()` more than once must be safe", but the lease was a bare `semaphore::release`. Every repeated close leaves one more permit behind, so the next two acquirers for that key can hold it **at the same time**, and `isRunning(key)` then reports `false` while a turn is in flight. That is not only a theoretical contract. `HarnessGateway.withGatedTurn` builds its `AtomicReference<TurnLease>` **outside** the `Mono.defer(...)`, so a second subscription of the returned `Mono` runs `doFinally` twice against the same lease object.
1 parent bc41f1b commit a63c625

2 files changed

Lines changed: 143 additions & 6 deletions

File tree

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/gateway/LocalSessionTurnGate.java‎

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.util.concurrent.ConcurrentHashMap;
1919
import java.util.concurrent.Semaphore;
20+
import java.util.concurrent.atomic.AtomicBoolean;
2021

2122
/**
2223
* Process-local fair per-key mutual exclusion for gateway turns.
@@ -26,18 +27,66 @@
2627
*/
2728
public final class LocalSessionTurnGate implements SessionTurnGate {
2829

29-
private final ConcurrentHashMap<String, Semaphore> gates = new ConcurrentHashMap<>();
30+
private final ConcurrentHashMap<String, Gate> gates = new ConcurrentHashMap<>();
3031

3132
@Override
3233
public TurnLease acquire(String key) throws InterruptedException {
33-
Semaphore semaphore = gates.computeIfAbsent(key, k -> new Semaphore(1, true));
34-
semaphore.acquire();
35-
return semaphore::release;
34+
Gate gate =
35+
gates.compute(
36+
key,
37+
(k, existing) -> {
38+
Gate target = existing != null ? existing : new Gate();
39+
target.leases++;
40+
return target;
41+
});
42+
try {
43+
gate.semaphore.acquire();
44+
} catch (InterruptedException e) {
45+
retire(key, gate);
46+
throw e;
47+
}
48+
AtomicBoolean released = new AtomicBoolean();
49+
return () -> {
50+
if (released.compareAndSet(false, true)) {
51+
gate.semaphore.release();
52+
retire(key, gate);
53+
}
54+
};
3655
}
3756

3857
@Override
3958
public boolean isRunning(String key) {
40-
Semaphore semaphore = gates.get(key);
41-
return semaphore != null && semaphore.availablePermits() == 0;
59+
Gate gate = gates.get(key);
60+
return gate != null && gate.semaphore.availablePermits() == 0;
61+
}
62+
63+
/**
64+
* Drops one lease from {@code gate} and evicts the key once no thread holds or waits for it.
65+
*
66+
* <p>The decrement and the removal run inside {@link ConcurrentHashMap#compute}, so they are
67+
* atomic with respect to a concurrent {@link #acquire(String)} on the same key: an acquirer
68+
* either joins the existing gate or, once it is gone, builds a fresh one. It can never obtain
69+
* a second semaphore for a key that still has a holder. The eviction is therefore driven by
70+
* the lease count rather than by {@link Semaphore#getQueueLength()}, which cannot see a thread
71+
* that took a just-released permit without ever entering the queue.
72+
*/
73+
private void retire(String key, Gate gate) {
74+
gates.compute(
75+
key,
76+
(k, existing) -> {
77+
if (existing != gate) {
78+
return existing;
79+
}
80+
return --existing.leases == 0 ? null : existing;
81+
});
82+
}
83+
84+
/** One fair semaphore plus the number of leases currently holding or waiting on it. */
85+
private static final class Gate {
86+
87+
private final Semaphore semaphore = new Semaphore(1, true);
88+
89+
/** Holders plus waiters; mutated only while holding the map's bin lock. */
90+
private int leases;
4291
}
4392
}

‎agentscope-harness/src/test/java/io/agentscope/harness/agent/gateway/LocalSessionTurnGateTest.java‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,11 @@
1919
import static org.junit.jupiter.api.Assertions.assertFalse;
2020
import static org.junit.jupiter.api.Assertions.assertTrue;
2121

22+
import java.lang.reflect.Field;
2223
import java.util.ArrayList;
24+
import java.util.Collections;
2325
import java.util.List;
26+
import java.util.concurrent.ConcurrentHashMap;
2427
import java.util.concurrent.CountDownLatch;
2528
import java.util.concurrent.TimeUnit;
2629
import java.util.concurrent.atomic.AtomicInteger;
@@ -134,4 +137,89 @@ void isRunningReflectsHeldLease() throws Exception {
134137
lease.close();
135138
assertFalse(gate.isRunning(key));
136139
}
140+
141+
@Test
142+
void evictsIdleKeysSoTheMapDoesNotGrowWithoutBound() throws Exception {
143+
LocalSessionTurnGate gate = new LocalSessionTurnGate();
144+
145+
for (int i = 0; i < 50; i++) {
146+
gate.acquire("session-" + i).close();
147+
}
148+
149+
ConcurrentHashMap<?, ?> gates = internalGates(gate);
150+
assertEquals(
151+
0,
152+
gates.size(),
153+
() -> "closed leases must not leave stale gate entries behind: " + gates.size());
154+
}
155+
156+
@Test
157+
void closeIsIdempotentSoARepeatedCloseCannotOpenTheGateTwice() throws Exception {
158+
LocalSessionTurnGate gate = new LocalSessionTurnGate();
159+
String key = "double-close";
160+
161+
TurnLease lease = gate.acquire(key);
162+
lease.close();
163+
// TurnLease documents that close() is idempotent. Each extra release leaves one more
164+
// permit behind, which would let a later acquirer hold the key at the same time.
165+
lease.close();
166+
lease.close();
167+
168+
TurnLease second = gate.acquire(key);
169+
assertTrue(gate.isRunning(key), "the second lease must be the only holder");
170+
second.close();
171+
assertFalse(gate.isRunning(key));
172+
}
173+
174+
@Test
175+
void neverOverlapsTwoHoldersForOneKeyUnderChurn() throws Exception {
176+
LocalSessionTurnGate gate = new LocalSessionTurnGate();
177+
String key = "churn";
178+
int threads = 8;
179+
int rounds = 200;
180+
181+
AtomicInteger inside = new AtomicInteger();
182+
AtomicInteger maxInside = new AtomicInteger();
183+
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
184+
CountDownLatch go = new CountDownLatch(1);
185+
List<Thread> workers = new ArrayList<>();
186+
187+
for (int t = 0; t < threads; t++) {
188+
Thread worker =
189+
new Thread(
190+
() -> {
191+
try {
192+
go.await();
193+
for (int r = 0; r < rounds; r++) {
194+
TurnLease lease = gate.acquire(key);
195+
int now = inside.incrementAndGet();
196+
maxInside.accumulateAndGet(now, Math::max);
197+
Thread.yield();
198+
inside.decrementAndGet();
199+
lease.close();
200+
}
201+
} catch (Throwable e) {
202+
errors.add(e);
203+
}
204+
});
205+
worker.setDaemon(true);
206+
workers.add(worker);
207+
worker.start();
208+
}
209+
210+
go.countDown();
211+
for (Thread worker : workers) {
212+
worker.join(30_000);
213+
}
214+
215+
assertTrue(errors.isEmpty(), errors.toString());
216+
assertEquals(1, maxInside.get(), "at most one holder per key, even under heavy churn");
217+
}
218+
219+
private static ConcurrentHashMap<?, ?> internalGates(LocalSessionTurnGate gate)
220+
throws Exception {
221+
Field field = LocalSessionTurnGate.class.getDeclaredField("gates");
222+
field.setAccessible(true);
223+
return (ConcurrentHashMap<?, ?>) field.get(gate);
224+
}
137225
}

0 commit comments

Comments
 (0)