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 @@ -195,13 +195,7 @@ public static void main(String[] args) throws Exception {
Files.writeString(workspace.resolve("ready"), "ready");
Thread.sleep(30000);
}
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {
// The fixture must keep ticking until the acceptResult proxy records the
// terminal handoff. A runtime wakeup may interrupt this polling sleep.
Thread.interrupted();
}
pause(10);
}
}
}
Expand Down Expand Up @@ -231,7 +225,7 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
if ("during-tool".equals(mode)) {
while (!Files.exists(workspace.resolve("ready"))
&& process.isAlive()
&& System.nanoTime() < deadline) Thread.sleep(20);
&& System.nanoTime() < deadline) pause(20);
assertTrue(
Files.exists(workspace.resolve("ready")),
() -> read(directory.resolve("brain.log")));
Expand All @@ -251,7 +245,7 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
&& System.nanoTime() < deadline) {
replacement.tick(new ThreadKey(KEY, "main"));
assertNull(replacement.lastFailure(new ThreadKey(KEY, "main")));
Thread.sleep(20);
pause(20);
}
assertEquals(
TurnStatus.SUCCEEDED,
Expand All @@ -269,6 +263,15 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
}
}

/** Sleeps through a runtime wakeup instead of failing the polling loop. */
private static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException wakeup) {
Thread.interrupted();
}
}

private static String read(Path path) {
try {
return Files.readString(path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@Timeout(30)
class HttpServerApplicationTest {
@TempDir static Path directory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import io.agentscope.durable.DurableException;
import io.agentscope.durable.DurableJson;
import io.agentscope.durable.DurableRuntime;
import io.agentscope.durable.DurableTurn;
import io.agentscope.durable.DurableTypes.ExecutionRequest;
import io.agentscope.durable.DurableTypes.ExecutionResult;
import io.agentscope.durable.DurableTypes.ExecutionState;
Expand Down Expand Up @@ -82,6 +83,7 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
import org.apache.rocketmq.client.apis.message.Message;
Expand Down Expand Up @@ -131,6 +133,10 @@ void cleanupSchemas() throws Exception {
}

static final Duration POLL = Duration.ofMillis(10);

/** Redelivery window for the fake broker; it has to stay well above consumer latency. */
static final long ACK_TIMEOUT_MILLIS = 1000;

static final ClientServiceProvider FACTORY = ClientServiceProvider.loadService();
static final RocketMqExecutionTopology.Route TOPOLOGY =
RocketMqExecutionTopology.route(RocketMqExecutionTopology.DEFAULT_NAMESPACE, "hands");
Expand All @@ -143,9 +149,46 @@ void cleanupSchemas() throws Exception {
.withOrigin(new RunStepRef("brain-run", "brain-step")));

static void await(BooleanSupplier condition) throws Exception {
assertTrue(waitUpTo10s(condition), "Condition did not become true");
}

/** Waits as long as {@link #await(BooleanSupplier)}, then fails with the caller's snapshot. */
static void await(String what, BooleanSupplier condition, Supplier<String> diagnostics)
throws Exception {
assertTrue(
waitUpTo10s(condition),
() -> what + " did not become true within 10s: " + diagnostics.get());
}

private static boolean waitUpTo10s(BooleanSupplier condition) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (!condition.getAsBoolean() && System.nanoTime() < deadline) Thread.sleep(10);
assertTrue(condition.getAsBoolean(), "Condition did not become true");
return condition.getAsBoolean();
}

private static String recoveryDiagnostics(
DurableRuntime runtime, DurableTurn turn, Broker broker, AtomicInteger modelCalls) {
StringBuilder out = new StringBuilder("turnId=").append(turn.turnId());
try {
out.append(", turn.status=").append(turn.status().status());
} catch (RuntimeException e) {
out.append(", turn.status=<unreadable: ").append(e).append('>');
}
try {
Throwable failure = runtime.lastFailure(turn.threadKey());
out.append(", lastFailure=").append(failure == null ? "none" : failure.toString());
} catch (RuntimeException e) {
out.append(", lastFailure=<unreadable: ").append(e).append('>');
}
return out.append(", modelCalls=")
.append(modelCalls.get())
.append(", commandAcks=")
.append(broker.commandAcks.get())
.append(", eventAcks=")
.append(broker.eventAcks.get())
.append(", queuedEvents=")
.append(broker.events.size())
.toString();
}

@Test
Expand Down Expand Up @@ -220,7 +263,7 @@ SimpleConsumer consumer(String topic) throws Exception {
() -> {
if (!acked.contains(message)) queue.add(message);
},
50,
ACK_TIMEOUT_MILLIS,
TimeUnit.MILLISECONDS);
return List.of(message);
});
Expand Down Expand Up @@ -401,9 +444,11 @@ public Flux<ChatResponse> stream(
worker.start();
runtime.start();
await(
"turn reaches SUCCEEDED",
() ->
runtime.getSession(session).getTurn(turn.turnId()).status().status()
== TurnStatus.SUCCEEDED);
== TurnStatus.SUCCEEDED,
() -> recoveryDiagnostics(runtime, turn, broker, modelCalls));
await(() -> broker.eventAcks.get() > 0);
assertEquals(
"done",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.core.event.AgentEvent;
import io.agentscope.core.message.Msg;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import reactor.core.publisher.Flux;

/**
Expand Down Expand Up @@ -52,7 +55,8 @@ public String getAgentDescription() {
@Override
public Flux<AgentEvent> streamEvents(List<Msg> requestMessages, AgentRequestOptions options) {
String taskId = options.getTaskId();
if (agentCache.containsKey(taskId)) {
RunningTask previous = agentCache.get(taskId);
if (null != previous && !previous.awaitRelease(Duration.ofSeconds(2))) {
throw new IllegalStateException("Agent already exists for taskId: " + taskId);
}
ReActAgent agent = buildReActAgent();
Expand All @@ -70,10 +74,15 @@ public Flux<AgentEvent> streamEvents(List<Msg> requestMessages, AgentRequestOpti
throw new IllegalStateException("Agent already exists for taskId: " + taskId);
}
try {
return agent.streamEvents(requestMessages, task.context())
.doFinally(signal -> agentCache.remove(taskId, task));
return agent.streamEvents(requestMessages, task.context)
.doFinally(
signal -> {
agentCache.remove(taskId, task);
task.release();
});
} catch (RuntimeException | Error e) {
agentCache.remove(taskId, task);
task.release();
throw e;
}
}
Expand Down Expand Up @@ -112,12 +121,36 @@ public void stop(String taskId) {
if (null != task) {
// Interrupt the session the task runs in; the no-arg interrupt() targets the default
// session, which may belong to another caller of a shared agent.
task.agent().interrupt(task.context());
task.agent.interrupt(task.context);
task.release();
}
}

/** The agent running a task and the context it was started with. */
private record RunningTask(ReActAgent agent, RuntimeContext context) {}
private static final class RunningTask {

private final ReActAgent agent;
private final RuntimeContext context;
private final CountDownLatch released = new CountDownLatch(1);

private RunningTask(ReActAgent agent, RuntimeContext context) {
this.agent = agent;
this.context = context;
}

private void release() {
released.countDown();
}

private boolean awaitRelease(Duration timeout) {
try {
return released.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
}

/**
* Build {@link ReActAgent} to run new request.
Expand Down
Loading