Skip to content

Commit 2c93536

Browse files
authored
fix(a2a,durable,rocketmq): fix the four flaky tests that fail unrelated builds (#4176)
1 parent a4306d6 commit 2c93536

4 files changed

Lines changed: 100 additions & 17 deletions

File tree

  • agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope
  • agentscope-examples/durable/integrated/http-server/src/test/java/io/agentscope/durable/examples/httpserver
  • agentscope-extensions
    • agentscope-extensions-durable-rocketmq/src/test/java/io/agentscope/extensions/durable/rocketmq
    • agentscope-extensions-protocol/agentscope-extensions-a2a/agentscope-extensions-a2a-server/src/main/java/io/agentscope/core/a2a/server/executor/runner

‎agentscope-durable/durable-adapters/durable-adapter-harness-agentscope/src/test/java/io/agentscope/durable/agentscope/ProcessRecoveryTest.java‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,7 @@ public static void main(String[] args) throws Exception {
195195
Files.writeString(workspace.resolve("ready"), "ready");
196196
Thread.sleep(30000);
197197
}
198-
try {
199-
Thread.sleep(10);
200-
} catch (InterruptedException ignored) {
201-
// The fixture must keep ticking until the acceptResult proxy records the
202-
// terminal handoff. A runtime wakeup may interrupt this polling sleep.
203-
Thread.interrupted();
204-
}
198+
pause(10);
205199
}
206200
}
207201
}
@@ -231,7 +225,7 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
231225
if ("during-tool".equals(mode)) {
232226
while (!Files.exists(workspace.resolve("ready"))
233227
&& process.isAlive()
234-
&& System.nanoTime() < deadline) Thread.sleep(20);
228+
&& System.nanoTime() < deadline) pause(20);
235229
assertTrue(
236230
Files.exists(workspace.resolve("ready")),
237231
() -> read(directory.resolve("brain.log")));
@@ -251,7 +245,7 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
251245
&& System.nanoTime() < deadline) {
252246
replacement.tick(new ThreadKey(KEY, "main"));
253247
assertNull(replacement.lastFailure(new ThreadKey(KEY, "main")));
254-
Thread.sleep(20);
248+
pause(20);
255249
}
256250
assertEquals(
257251
TurnStatus.SUCCEEDED,
@@ -269,6 +263,15 @@ void replacementCollectsOriginalResultWithoutRepeatingEffect(String mode) throws
269263
}
270264
}
271265

266+
/** Sleeps through a runtime wakeup instead of failing the polling loop. */
267+
private static void pause(long millis) {
268+
try {
269+
Thread.sleep(millis);
270+
} catch (InterruptedException wakeup) {
271+
Thread.interrupted();
272+
}
273+
}
274+
272275
private static String read(Path path) {
273276
try {
274277
return Files.readString(path);

‎agentscope-examples/durable/integrated/http-server/src/test/java/io/agentscope/durable/examples/httpserver/HttpServerApplicationTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,12 @@
3737
import org.springframework.beans.factory.annotation.Autowired;
3838
import org.springframework.boot.test.context.SpringBootTest;
3939
import org.springframework.boot.test.web.server.LocalServerPort;
40+
import org.springframework.test.annotation.DirtiesContext;
4041
import org.springframework.test.context.DynamicPropertyRegistry;
4142
import org.springframework.test.context.DynamicPropertySource;
4243

4344
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
45+
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
4446
@Timeout(30)
4547
class HttpServerApplicationTest {
4648
@TempDir static Path directory;

‎agentscope-extensions/agentscope-extensions-durable-rocketmq/src/test/java/io/agentscope/extensions/durable/rocketmq/RocketMqExecutionTest.java‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
import io.agentscope.durable.DurableException;
4444
import io.agentscope.durable.DurableJson;
4545
import io.agentscope.durable.DurableRuntime;
46+
import io.agentscope.durable.DurableTurn;
4647
import io.agentscope.durable.DurableTypes.ExecutionRequest;
4748
import io.agentscope.durable.DurableTypes.ExecutionResult;
4849
import io.agentscope.durable.DurableTypes.ExecutionState;
@@ -82,6 +83,7 @@
8283
import java.util.concurrent.atomic.AtomicInteger;
8384
import java.util.function.BooleanSupplier;
8485
import java.util.function.Function;
86+
import java.util.function.Supplier;
8587
import org.apache.rocketmq.client.apis.ClientServiceProvider;
8688
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;
8789
import org.apache.rocketmq.client.apis.message.Message;
@@ -131,6 +133,10 @@ void cleanupSchemas() throws Exception {
131133
}
132134

133135
static final Duration POLL = Duration.ofMillis(10);
136+
137+
/** Redelivery window for the fake broker; it has to stay well above consumer latency. */
138+
static final long ACK_TIMEOUT_MILLIS = 1000;
139+
134140
static final ClientServiceProvider FACTORY = ClientServiceProvider.loadService();
135141
static final RocketMqExecutionTopology.Route TOPOLOGY =
136142
RocketMqExecutionTopology.route(RocketMqExecutionTopology.DEFAULT_NAMESPACE, "hands");
@@ -143,9 +149,46 @@ void cleanupSchemas() throws Exception {
143149
.withOrigin(new RunStepRef("brain-run", "brain-step")));
144150

145151
static void await(BooleanSupplier condition) throws Exception {
152+
assertTrue(waitUpTo10s(condition), "Condition did not become true");
153+
}
154+
155+
/** Waits as long as {@link #await(BooleanSupplier)}, then fails with the caller's snapshot. */
156+
static void await(String what, BooleanSupplier condition, Supplier<String> diagnostics)
157+
throws Exception {
158+
assertTrue(
159+
waitUpTo10s(condition),
160+
() -> what + " did not become true within 10s: " + diagnostics.get());
161+
}
162+
163+
private static boolean waitUpTo10s(BooleanSupplier condition) throws Exception {
146164
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
147165
while (!condition.getAsBoolean() && System.nanoTime() < deadline) Thread.sleep(10);
148-
assertTrue(condition.getAsBoolean(), "Condition did not become true");
166+
return condition.getAsBoolean();
167+
}
168+
169+
private static String recoveryDiagnostics(
170+
DurableRuntime runtime, DurableTurn turn, Broker broker, AtomicInteger modelCalls) {
171+
StringBuilder out = new StringBuilder("turnId=").append(turn.turnId());
172+
try {
173+
out.append(", turn.status=").append(turn.status().status());
174+
} catch (RuntimeException e) {
175+
out.append(", turn.status=<unreadable: ").append(e).append('>');
176+
}
177+
try {
178+
Throwable failure = runtime.lastFailure(turn.threadKey());
179+
out.append(", lastFailure=").append(failure == null ? "none" : failure.toString());
180+
} catch (RuntimeException e) {
181+
out.append(", lastFailure=<unreadable: ").append(e).append('>');
182+
}
183+
return out.append(", modelCalls=")
184+
.append(modelCalls.get())
185+
.append(", commandAcks=")
186+
.append(broker.commandAcks.get())
187+
.append(", eventAcks=")
188+
.append(broker.eventAcks.get())
189+
.append(", queuedEvents=")
190+
.append(broker.events.size())
191+
.toString();
149192
}
150193

151194
@Test
@@ -220,7 +263,7 @@ SimpleConsumer consumer(String topic) throws Exception {
220263
() -> {
221264
if (!acked.contains(message)) queue.add(message);
222265
},
223-
50,
266+
ACK_TIMEOUT_MILLIS,
224267
TimeUnit.MILLISECONDS);
225268
return List.of(message);
226269
});
@@ -401,9 +444,11 @@ public Flux<ChatResponse> stream(
401444
worker.start();
402445
runtime.start();
403446
await(
447+
"turn reaches SUCCEEDED",
404448
() ->
405449
runtime.getSession(session).getTurn(turn.turnId()).status().status()
406-
== TurnStatus.SUCCEEDED);
450+
== TurnStatus.SUCCEEDED,
451+
() -> recoveryDiagnostics(runtime, turn, broker, modelCalls));
407452
await(() -> broker.eventAcks.get() > 0);
408453
assertEquals(
409454
"done",

‎agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-a2a/agentscope-extensions-a2a-server/src/main/java/io/agentscope/core/a2a/server/executor/runner/BaseReActAgentRunner.java‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,12 @@
2020
import io.agentscope.core.agent.RuntimeContext;
2121
import io.agentscope.core.event.AgentEvent;
2222
import io.agentscope.core.message.Msg;
23+
import java.time.Duration;
2324
import java.util.List;
2425
import java.util.concurrent.ConcurrentHashMap;
2526
import java.util.concurrent.ConcurrentMap;
27+
import java.util.concurrent.CountDownLatch;
28+
import java.util.concurrent.TimeUnit;
2629
import reactor.core.publisher.Flux;
2730

2831
/**
@@ -52,7 +55,8 @@ public String getAgentDescription() {
5255
@Override
5356
public Flux<AgentEvent> streamEvents(List<Msg> requestMessages, AgentRequestOptions options) {
5457
String taskId = options.getTaskId();
55-
if (agentCache.containsKey(taskId)) {
58+
RunningTask previous = agentCache.get(taskId);
59+
if (null != previous && !previous.awaitRelease(Duration.ofSeconds(2))) {
5660
throw new IllegalStateException("Agent already exists for taskId: " + taskId);
5761
}
5862
ReActAgent agent = buildReActAgent();
@@ -70,10 +74,15 @@ public Flux<AgentEvent> streamEvents(List<Msg> requestMessages, AgentRequestOpti
7074
throw new IllegalStateException("Agent already exists for taskId: " + taskId);
7175
}
7276
try {
73-
return agent.streamEvents(requestMessages, task.context())
74-
.doFinally(signal -> agentCache.remove(taskId, task));
77+
return agent.streamEvents(requestMessages, task.context)
78+
.doFinally(
79+
signal -> {
80+
agentCache.remove(taskId, task);
81+
task.release();
82+
});
7583
} catch (RuntimeException | Error e) {
7684
agentCache.remove(taskId, task);
85+
task.release();
7786
throw e;
7887
}
7988
}
@@ -112,12 +121,36 @@ public void stop(String taskId) {
112121
if (null != task) {
113122
// Interrupt the session the task runs in; the no-arg interrupt() targets the default
114123
// session, which may belong to another caller of a shared agent.
115-
task.agent().interrupt(task.context());
124+
task.agent.interrupt(task.context);
125+
task.release();
116126
}
117127
}
118128

119129
/** The agent running a task and the context it was started with. */
120-
private record RunningTask(ReActAgent agent, RuntimeContext context) {}
130+
private static final class RunningTask {
131+
132+
private final ReActAgent agent;
133+
private final RuntimeContext context;
134+
private final CountDownLatch released = new CountDownLatch(1);
135+
136+
private RunningTask(ReActAgent agent, RuntimeContext context) {
137+
this.agent = agent;
138+
this.context = context;
139+
}
140+
141+
private void release() {
142+
released.countDown();
143+
}
144+
145+
private boolean awaitRelease(Duration timeout) {
146+
try {
147+
return released.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
148+
} catch (InterruptedException e) {
149+
Thread.currentThread().interrupt();
150+
return false;
151+
}
152+
}
153+
}
121154

122155
/**
123156
* Build {@link ReActAgent} to run new request.

0 commit comments

Comments
 (0)