This is an automated email from the ASF dual-hosted git repository.
lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git
The following commit(s) were added to refs/heads/master by this push:
new 00ad2f388 fix(ai): preserve the turn claim across admission checks
(#7390)
00ad2f388 is described below
commit 00ad2f388e4df7bf59b3264380f8ea03b7a85872
Author: zmuxuny <[email protected]>
AuthorDate: Fri Nov 27 12:30:44 2026 +0800
fix(ai): preserve the turn claim across admission checks (#7390)
---
.../studio/ops/ai/conversation/AiRunService.java | 8 +--
.../ops/ai/conversation/AiRunServiceTest.java | 62 ++++++++++++++++++++++
2 files changed, 67 insertions(+), 3 deletions(-)
diff --git
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
index f5231fa9d..f2929b276 100644
---
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
+++
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
@@ -193,15 +193,17 @@ public class AiRunService {
"Pick a model in the AI settings.");
}
- // Admission: one active run per conversation, which is what makes a
single writer per timeline
- // a guarantee rather than a hope.
+ // Choose the candidate turn BEFORE checking for an active run. If
another request is admitted
+ // after this read, it claims this same turn and the unique key below
rejects one of us. Reading
+ // MAX(turn) after an idle check would instead let that stale check
admit a different turn while
+ // the other request is still active, bypassing the single-writer
guarantee.
+ int turn = runRepository.maxTurn(conversationId) + 1;
runRepository.findActiveByConversationId(conversationId).ifPresent(active -> {
log.info("refusing a second run for conversation {}: run {} is {}",
conversationId, active.getId(), active.getStatus());
throw busy();
});
- int turn = runRepository.maxTurn(conversationId) + 1;
// MAX(seq) and never rmq_ai_conversation.last_seq: that column is a
cache for the reconnect fast
// path and a run that died mid-flush leaves it low, which would reuse
timeline positions.
int seedSeq = eventRepository.maxSeq(conversationId);
diff --git
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
index 57b39ee18..e3369dd95 100644
---
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
+++
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
@@ -38,6 +38,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.time.Clock;
@@ -53,12 +55,15 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -218,6 +223,63 @@ class AiRunServiceTest {
assertThat(runUpdates).isEmpty();
}
+ @ParameterizedTest
+ @ValueSource(strings = {"activeLookup", "timelineSeed"})
+ void racingAdmissionMustKeepTheTurnClaimFromBeforeTheIdleCheckTest(String
interleaving) {
+ ExecutorService deferred = mock(ExecutorService.class);
+ when(deferred.submit(any(Runnable.class)))
+ .thenAnswer(invocation -> new
FutureTask<>(invocation.getArgument(0), null));
+ service = serviceWith(deferred);
+ when(runRepository.maxTurn(CONVERSATION_ID)).thenAnswer(invocation ->
+
runInserts.stream().mapToInt(RmqAiRun::getTurn).max().orElse(0));
+ AtomicBoolean firstQuery = new AtomicBoolean(true);
+ Runnable admitOtherRequest = () -> {
+ if (firstQuery.compareAndSet(true, false)) {
+ service.sendMessage(CONVERSATION_ID,
AiRunService.RunRequest.of("winning request"));
+ }
+ };
+ when(eventRepository.maxSeq(CONVERSATION_ID)).thenAnswer(invocation ->
{
+ if ("timelineSeed".equals(interleaving)) {
+ // Both requests already chose the same turn: the unique key
is the backstop.
+ admitOtherRequest.run();
+ }
+ return
inserted.stream().mapToInt(RmqAiEvent::getSeq).max().orElse(0);
+ });
+ when(runRepository.insert(any(RmqAiRun.class))).thenAnswer(invocation
-> {
+ RmqAiRun run = invocation.getArgument(0);
+ // Model the existing database uniqueness constraint, not a
stronger active-run lock.
+ if (runInserts.stream().anyMatch(existing ->
existing.getTurn().equals(run.getTurn()))) {
+ throw new DuplicateKeyException("uk_ai_run_conversation_turn");
+ }
+ run.setId(RUN_ID + run.getTurn() - 1L);
+ runInserts.add(AiRunTestSupport.copyOf(run));
+ return run;
+ });
+
when(runRepository.findActiveByConversationId(CONVERSATION_ID)).thenAnswer(invocation
-> {
+ Optional<RmqAiRun> snapshot = runInserts.stream().findFirst();
+ if ("activeLookup".equals(interleaving)) {
+ // Another request is admitted after this query saw no active
run, before the
+ // delayed caller receives that result. Its worker stays
queued throughout.
+ admitOtherRequest.run();
+ }
+ return snapshot;
+ });
+
+ Throwable refusal = catchThrowable(() ->
service.sendMessage(CONVERSATION_ID,
+ AiRunService.RunRequest.of("delayed request")));
+
+ assertThat(runInserts).as("one active run despite both callers
observing idle")
+ .hasSize(1);
+ assertThat(refusal).isInstanceOfSatisfying(BusinessException.class,
+ exception -> assertThat(exception.getCode()).isEqualTo(409));
+ assertThat(registry.liveRunIds()).containsExactly(RUN_ID);
+ assertThat(inserted).filteredOn(row -> "user".equals(row.getType()))
+ .hasSize(1)
+ .extracting(RmqAiEvent::getPayload)
+ .allSatisfy(payload -> assertThat(payload).contains("winning
request"));
+ verify(deferred).submit(any(Runnable.class));
+ }
+
@Test
void aConversationWithoutToolsShouldSaySoInItsTimelineTest() {
when(workspace.prepare(anyLong(), any())).thenReturn(Optional.empty());