Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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 @@ -129,6 +129,8 @@ public record Registration(String harness, String definitionVersion, HarnessAdap
private final ScheduledThreadPoolExecutor heartbeats;
private final ExecutorService workers;
private final ScheduledThreadPoolExecutor observers;
private final ScheduledThreadPoolExecutor awaitDeadlines;
private final ExecutorService awaitCompletions;
private final Set<SessionEventSubscription> subscriptions = ConcurrentHashMap.newKeySet();
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
Expand Down Expand Up @@ -318,6 +320,11 @@ 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);
awaitCompletions =
ExecutionThreads.create(0, "durable-await-completion", this::trackThread);
}

public static Builder builder() {
Expand Down Expand Up @@ -497,6 +504,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 @@ -515,13 +530,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 @@ -538,9 +546,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));
// Status reads and inline future callbacks can both block.
var expiration =
observers.schedule(
check, Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
awaitDeadlines.schedule(
() -> awaitCompletions.execute(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 @@ -1262,6 +1273,8 @@ public void close() {
waits.forEach(
wait -> wait.completeExceptionally(new IllegalStateException("Runtime closed")));
observers.shutdownNow();
awaitDeadlines.shutdownNow();
awaitCompletions.shutdownNow();
active.values()
.forEach(
a -> {
Expand All @@ -1283,7 +1296,14 @@ public void close() {
if (!ownedThreads.contains(Thread.currentThread())) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
try {
for (var executor : List.of(observers, timer, heartbeats, workers))
for (var executor :
List.of(
observers,
awaitDeadlines,
awaitCompletions,
timer,
heartbeats,
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 @@ -17,6 +17,7 @@
package io.agentscope.durable;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand All @@ -35,6 +36,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 +89,85 @@ 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());
}
}

@Test
void awaitTimeoutIsIndependentOfAnEarlierTimeoutCallback() throws Exception {
var backend = backend();
when(backend.turn(thread, "turn-1")).thenReturn(running());
var callbackEntered = new CountDownLatch(1);
var unblockCallback = new CountDownLatch(1);
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 first = turn.await(Duration.ofSeconds(1)).toCompletableFuture();
var callback =
first.whenComplete(
(view, failure) -> {
callbackEntered.countDown();
try {
if (!unblockCallback.await(8, TimeUnit.SECONDS)) {
throw new AssertionError(
"Test did not release callback");
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new AssertionError(interrupted);
}
});
assertTrue(callbackEntered.await(5, TimeUnit.SECONDS));
var second = turn.await(Duration.ofMillis(250)).toCompletableFuture();
var error =
assertThrows(
ExecutionException.class, () -> second.get(3, TimeUnit.SECONDS));
assertInstanceOf(TimeoutException.class, error.getCause());
assertTrue(error.getCause().getMessage().contains("turn-1"));
assertFalse(callback.isDone(), "The first callback must still be blocked");
} finally {
unblockCallback.countDown();
}
}
}

/** Minimal Backend whose user operations answer with schema-valid canned views. */
private SessionBackend backend() {
var backend = mock(SessionBackend.class);
Expand Down
5 changes: 3 additions & 2 deletions docs/dev/en/docs/harness/durable.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,9 @@ the actual output, and UNKNOWN remains until the outcome is explicitly reconcile
delivery, subscribe or open the event stream before `submit`; this preserves live previews even for
a fast Agent.
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
Runtime never cancels durable work; cancellation is explicit. Short operations can
include Thread/Turn identity. A status read or an earlier timeout callback can still be
in progress when another wait expires. 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.

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

Expand Down
Loading