Skip to content

Commit bbc292a

Browse files
fix(durable): keep await deadlines independent of status polls (#4508)
## AgentScope-Java Version 2.1.0-SNAPSHOT ## Description Fixes #4507. A blocked status read can occupy the observer pool and prevent DurableTurn.await(timeout) from settling. An inline timeout callback can also stall subsequent waits if it runs on the deadline scheduler. Use a Runtime-owned deadline scheduler to dispatch timeout completions to a separate elastic executor. The elapsed wait completes exceptionally with a TimeoutException containing its Thread/Turn identity. Status polling stays on the observer pool. Runtime close shuts both new executors down. An admitted Turn can still be queried after the wait ends. The two regressions cover a blocked backend poll and an earlier non-async completion callback held on a latch. In both scenarios the wait times out while the blockage is held. ## Verification - The blocked-read and blocked-callback regressions fail on main at 9cfeaad. The blocked-callback case also fails on the previous PR head d5fccbe, which completed directly on its deadline thread. - Ran `mvn -B -T1C -pl agentscope-durable/durable-runtime -am clean verify` on the updated branch. All 50 tests passed without skips on Windows/Java 17. - The targeted Harness test that previously timed out in Windows CI passed all ten parameter sets on this head. Full repository checks are running again in CI. - Spotless, git diff checks, all 20 documentation tests, and Mintlify validation passed. The link checker reported the same 2,754 source/target entries on main and this branch. AI assistance was used for investigation, implementation, and verification. ## Checklist - [x] Code has been formatted with `mvn spotless:apply` - [ ] All tests are passing (`mvn test`) - [x] Javadoc comments follow project conventions - [x] Related documentation has been updated - [x] Code is ready for review
1 parent 1cf8060 commit bbc292a

4 files changed

Lines changed: 115 additions & 12 deletions

File tree

‎agentscope-durable/durable-runtime/src/main/java/io/agentscope/durable/DurableRuntime.java‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ public record Registration(String harness, String definitionVersion, HarnessAdap
129129
private final ScheduledThreadPoolExecutor heartbeats;
130130
private final ExecutorService workers;
131131
private final ScheduledThreadPoolExecutor observers;
132+
private final ScheduledThreadPoolExecutor awaitDeadlines;
133+
private final ExecutorService awaitCompletions;
132134
private final Set<SessionEventSubscription> subscriptions = ConcurrentHashMap.newKeySet();
133135
private final AtomicBoolean started = new AtomicBoolean();
134136
private final AtomicBoolean closed = new AtomicBoolean();
@@ -318,6 +320,11 @@ private DurableRuntime(Builder b) {
318320
b.observerParallelism, r -> daemon(r, "durable-observer"));
319321
observers.setRemoveOnCancelPolicy(true);
320322
observers.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
323+
awaitDeadlines =
324+
new ScheduledThreadPoolExecutor(1, r -> daemon(r, "durable-await-deadline"));
325+
awaitDeadlines.setRemoveOnCancelPolicy(true);
326+
awaitCompletions =
327+
ExecutionThreads.create(0, "durable-await-completion", this::trackThread);
321328
}
322329

323330
public static Builder builder() {
@@ -497,6 +504,14 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
497504
var result = new CompletableFuture<TurnView>();
498505
waits.add(result);
499506
var enqueued = new AtomicBoolean();
507+
Runnable expire =
508+
() ->
509+
result.completeExceptionally(
510+
new TimeoutException(
511+
"Timed out observing Turn "
512+
+ session.key()
513+
+ "/"
514+
+ turnId));
500515
Runnable check =
501516
() -> {
502517
if (result.isDone()) return;
@@ -515,13 +530,6 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
515530
return;
516531
}
517532
}
518-
if (System.nanoTime() - deadline >= 0)
519-
result.completeExceptionally(
520-
new TimeoutException(
521-
"Timed out observing Turn "
522-
+ session.key()
523-
+ "/"
524-
+ turnId));
525533
};
526534
AutoCloseable notification = observeWait(session.key().session(), result, enqueued, check);
527535
result.whenComplete(
@@ -538,9 +546,12 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
538546
observers.scheduleWithFixedDelay(
539547
check, 0, observationInterval.toMillis(), TimeUnit.MILLISECONDS);
540548
result.whenComplete((view, error) -> scheduled.cancel(false));
549+
// Status reads and inline future callbacks can both block.
541550
var expiration =
542-
observers.schedule(
543-
check, Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
551+
awaitDeadlines.schedule(
552+
() -> awaitCompletions.execute(expire),
553+
Math.max(0, deadline - System.nanoTime()),
554+
TimeUnit.NANOSECONDS);
544555
result.whenComplete((view, error) -> expiration.cancel(false));
545556
} catch (RejectedExecutionException error) {
546557
result.completeExceptionally(error);
@@ -1262,6 +1273,8 @@ public void close() {
12621273
waits.forEach(
12631274
wait -> wait.completeExceptionally(new IllegalStateException("Runtime closed")));
12641275
observers.shutdownNow();
1276+
awaitDeadlines.shutdownNow();
1277+
awaitCompletions.shutdownNow();
12651278
active.values()
12661279
.forEach(
12671280
a -> {
@@ -1283,7 +1296,14 @@ public void close() {
12831296
if (!ownedThreads.contains(Thread.currentThread())) {
12841297
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
12851298
try {
1286-
for (var executor : List.of(observers, timer, heartbeats, workers))
1299+
for (var executor :
1300+
List.of(
1301+
observers,
1302+
awaitDeadlines,
1303+
awaitCompletions,
1304+
timer,
1305+
heartbeats,
1306+
workers))
12871307
executor.awaitTermination(
12881308
Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
12891309
} catch (InterruptedException interrupted) {

‎agentscope-durable/durable-runtime/src/test/java/io/agentscope/durable/DurableRuntimeTest.java‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package io.agentscope.durable;
1818

1919
import static org.junit.jupiter.api.Assertions.assertEquals;
20+
import static org.junit.jupiter.api.Assertions.assertFalse;
2021
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
2122
import static org.junit.jupiter.api.Assertions.assertThrows;
2223
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -35,6 +36,7 @@
3536
import io.agentscope.durable.DurableTypes.TurnStatus;
3637
import io.agentscope.durable.DurableTypes.TurnView;
3738
import java.time.Duration;
39+
import java.util.concurrent.CountDownLatch;
3840
import java.util.concurrent.ExecutionException;
3941
import java.util.concurrent.TimeUnit;
4042
import java.util.concurrent.TimeoutException;
@@ -87,6 +89,85 @@ void awaitTimesOutInsteadOfFailingWhenPollsKeepFailingUntilTheDeadline() {
8789
}
8890
}
8991

92+
@Test
93+
void awaitTimesOutWhileAnObservationIsBlocked() throws Exception {
94+
var backend = backend();
95+
var pollEntered = new CountDownLatch(1);
96+
var unblockPoll = new CountDownLatch(1);
97+
when(backend.turn(thread, "turn-1"))
98+
.thenAnswer(
99+
invocation -> {
100+
pollEntered.countDown();
101+
if (!unblockPoll.await(8, TimeUnit.SECONDS)) {
102+
throw new AssertionError("Test did not release the backend poll");
103+
}
104+
return succeeded();
105+
});
106+
try (var runtime =
107+
DurableRuntime.builder()
108+
.backend(backend)
109+
.definition("agent", "v1", "1")
110+
.observerParallelism(1)
111+
.build()) {
112+
var turn = runtime.createSession(key, "agent").submit("r1", "input");
113+
try {
114+
var future = turn.await(Duration.ofMillis(500)).toCompletableFuture();
115+
assertTrue(pollEntered.await(2, TimeUnit.SECONDS));
116+
var error =
117+
assertThrows(
118+
ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
119+
assertInstanceOf(TimeoutException.class, error.getCause());
120+
assertTrue(error.getCause().getMessage().contains("turn-1"));
121+
} finally {
122+
unblockPoll.countDown();
123+
}
124+
assertEquals(TurnStatus.SUCCEEDED, turn.status().status());
125+
}
126+
}
127+
128+
@Test
129+
void awaitTimeoutIsIndependentOfAnEarlierTimeoutCallback() throws Exception {
130+
var backend = backend();
131+
when(backend.turn(thread, "turn-1")).thenReturn(running());
132+
var callbackEntered = new CountDownLatch(1);
133+
var unblockCallback = new CountDownLatch(1);
134+
try (var runtime =
135+
DurableRuntime.builder()
136+
.backend(backend)
137+
.definition("agent", "v1", "1")
138+
.observerParallelism(1)
139+
.build()) {
140+
var turn = runtime.createSession(key, "agent").submit("r1", "input");
141+
try {
142+
var first = turn.await(Duration.ofSeconds(1)).toCompletableFuture();
143+
var callback =
144+
first.whenComplete(
145+
(view, failure) -> {
146+
callbackEntered.countDown();
147+
try {
148+
if (!unblockCallback.await(8, TimeUnit.SECONDS)) {
149+
throw new AssertionError(
150+
"Test did not release callback");
151+
}
152+
} catch (InterruptedException interrupted) {
153+
Thread.currentThread().interrupt();
154+
throw new AssertionError(interrupted);
155+
}
156+
});
157+
assertTrue(callbackEntered.await(5, TimeUnit.SECONDS));
158+
var second = turn.await(Duration.ofMillis(250)).toCompletableFuture();
159+
var error =
160+
assertThrows(
161+
ExecutionException.class, () -> second.get(3, TimeUnit.SECONDS));
162+
assertInstanceOf(TimeoutException.class, error.getCause());
163+
assertTrue(error.getCause().getMessage().contains("turn-1"));
164+
assertFalse(callback.isDone(), "The first callback must still be blocked");
165+
} finally {
166+
unblockCallback.countDown();
167+
}
168+
}
169+
}
170+
90171
/** Minimal Backend whose user operations answer with schema-valid canned views. */
91172
private SessionBackend backend() {
92173
var backend = mock(SessionBackend.class);

‎docs/dev/en/docs/harness/durable.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,8 +376,9 @@ the actual output, and UNKNOWN remains until the outcome is explicitly reconcile
376376
delivery, subscribe or open the event stream before `submit`; this preserves live previews even for
377377
a fast Agent.
378378
Retries use the same requestId; observing an existing Turn never resubmits. Timeout errors
379-
include Thread/Turn identity. Closing a subscription, cancelling a Future or closing
380-
Runtime never cancels durable work; cancellation is explicit. Short operations can
379+
include Thread/Turn identity. A status read or an earlier timeout callback can still be
380+
in progress when another wait expires. Closing a subscription, cancelling a Future or
381+
closing Runtime never cancels durable work; cancellation is explicit. Short operations can
381382
perform database/network I/O; Web hosts must call them off event-loop threads.
382383

383384
## Separate API hosts and HTTP

‎docs/dev/zh/docs/harness/durable.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ Run/Step 更换而改变;重新调用模型时增加 attempt,重放已提交
323323
`session.call(requestId, input, timeout)` 是 submit + await,返回 CompletionStage。消费事件时应先
324324
订阅或打开事件流,再调用 `submit`,以便接收快速完成的 Agent 的实时预览。
325325
同一 requestId 可安全重试;重复观察原 Turn 不重复提交。超时错误包含 Thread/Turn 身份。
326+
即使状态读取或上一次等待的超时回调仍在进行,另一次等待也可以按截止时间结束。
326327
关闭订阅、取消 Future 或关闭 Runtime 都不会取消持久任务,只有显式 cancel 才会发起取消。
327328
这些短操作可能访问数据库/网络,Web 宿主须在非事件循环线程调用。
328329

0 commit comments

Comments
 (0)