Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ public record Registration(String harness, String definitionVersion, HarnessAdap
Executors.newScheduledThreadPool(2, r -> daemon(r, "durable-timer"));
private final ExecutorService workers;
private final ScheduledThreadPoolExecutor observers;
private final ScheduledThreadPoolExecutor awaitDeadlines;
private final Set<SessionEventSubscription> subscriptions = ConcurrentHashMap.newKeySet();
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
Expand Down Expand Up @@ -224,6 +225,9 @@ private DurableRuntime(Builder b) {
b.observerParallelism, r -> daemon(r, "durable-observer"));
observers.setRemoveOnCancelPolicy(true);
observers.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
awaitDeadlines =
new ScheduledThreadPoolExecutor(1, r -> daemon(r, "durable-await-deadline"));
awaitDeadlines.setRemoveOnCancelPolicy(true);
}

public static Builder builder() {
Expand Down Expand Up @@ -403,6 +407,14 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
var result = new CompletableFuture<TurnView>();
waits.add(result);
var enqueued = new AtomicBoolean();
Runnable expire =
() ->
result.completeExceptionally(
new TimeoutException(
"Timed out observing Turn "
+ session.key()
+ "/"
+ turnId));
Runnable check =
() -> {
if (result.isDone()) return;
Expand All @@ -421,13 +433,6 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
return;
}
}
if (System.nanoTime() - deadline >= 0)
result.completeExceptionally(
new TimeoutException(
"Timed out observing Turn "
+ session.key()
+ "/"
+ turnId));
};
AutoCloseable notification = observeWait(session.key().session(), result, enqueued, check);
result.whenComplete(
Expand All @@ -444,9 +449,12 @@ CompletionStage<TurnView> await(DurableThread session, String turnId, Duration t
observers.scheduleWithFixedDelay(
check, 0, observationInterval.toMillis(), TimeUnit.MILLISECONDS);
result.whenComplete((view, error) -> scheduled.cancel(false));
// A status read can occupy every observer. Keep the deadline off that pool.
var expiration =
observers.schedule(
check, Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
awaitDeadlines.schedule(
expire,
Math.max(0, deadline - System.nanoTime()),
TimeUnit.NANOSECONDS);
result.whenComplete((view, error) -> expiration.cancel(false));
} catch (RejectedExecutionException error) {
result.completeExceptionally(error);
Expand Down Expand Up @@ -1143,6 +1151,7 @@ public void close() {
waits.forEach(
wait -> wait.completeExceptionally(new IllegalStateException("Runtime closed")));
observers.shutdownNow();
awaitDeadlines.shutdownNow();
active.values()
.forEach(
a -> {
Expand All @@ -1163,7 +1172,7 @@ public void close() {
if (!ownedThreads.contains(Thread.currentThread())) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
try {
for (var executor : List.of(observers, timer, workers))
for (var executor : List.of(observers, awaitDeadlines, timer, workers))
executor.awaitTermination(
Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
} catch (InterruptedException interrupted) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import io.agentscope.durable.DurableTypes.TurnStatus;
import io.agentscope.durable.DurableTypes.TurnView;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
Expand Down Expand Up @@ -87,6 +88,42 @@ void awaitTimesOutInsteadOfFailingWhenPollsKeepFailingUntilTheDeadline() {
}
}

@Test
void awaitTimesOutWhileAnObservationIsBlocked() throws Exception {
var backend = backend();
var pollEntered = new CountDownLatch(1);
var unblockPoll = new CountDownLatch(1);
when(backend.turn(thread, "turn-1"))
.thenAnswer(
invocation -> {
pollEntered.countDown();
if (!unblockPoll.await(8, TimeUnit.SECONDS)) {
throw new AssertionError("Test did not release the backend poll");
}
return succeeded();
});
try (var runtime =
DurableRuntime.builder()
.backend(backend)
.definition("agent", "v1", "1")
.observerParallelism(1)
.build()) {
var turn = runtime.createSession(key, "agent").submit("r1", "input");
try {
var future = turn.await(Duration.ofMillis(500)).toCompletableFuture();
assertTrue(pollEntered.await(2, TimeUnit.SECONDS));
var error =
assertThrows(
ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
assertInstanceOf(TimeoutException.class, error.getCause());
assertTrue(error.getCause().getMessage().contains("turn-1"));
} finally {
unblockPoll.countDown();
}
assertEquals(TurnStatus.SUCCEEDED, turn.status().status());
}
}

/** Minimal Backend whose user operations answer with schema-valid canned views. */
private SessionBackend backend() {
var backend = mock(SessionBackend.class);
Expand Down
3 changes: 2 additions & 1 deletion docs/dev/en/docs/harness/durable.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,8 @@ delivery, subscribe or open the event stream before `submit`; this preserves liv
a fast Agent. The old submit-and-observe `stream(...)` shortcut is deprecated because its name was
ambiguous and it could only attach after admission.
Retries use the same requestId; observing an existing Turn never resubmits. Timeout errors
include Thread/Turn identity. Closing a subscription, cancelling a Future or closing
include Thread/Turn identity. The wait deadline can expire while a status read is still in progress.
Closing a subscription, cancelling a Future or closing
Runtime never cancels durable work; cancellation is explicit. Short operations can
perform database/network I/O; Web hosts must call them off event-loop threads.

Expand Down
1 change: 1 addition & 0 deletions docs/dev/zh/docs/harness/durable.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ Run/Step 更换而改变;重新调用模型时增加 attempt,重放已提交
订阅或打开事件流,再调用 `submit`,这样快速完成的 Agent 也不会漏掉实时预览。旧的
submit-and-observe `stream(...)` 快捷方法因为名称含混且只能在受理后连接,现已 deprecated。
同一 requestId 可安全重试;重复观察原 Turn 不重复提交。超时错误包含 Thread/Turn 身份。
即使状态读取仍在进行,等待也可以按截止时间结束。
关闭订阅、取消 Future 或关闭 Runtime 都不会取消持久任务,只有显式 cancel 才会发起取消。
这些短操作可能访问数据库/网络,Web 宿主须在非事件循环线程调用。

Expand Down
Loading