Skip to content

Commit c664ed0

Browse files
committed
test(state): regression coverage for agentscope-ai#2475 corrupted slot when sessionId contains '/'
Adds end-to-end coverage pinning AgentState slot integrity through a real ReActAgent call against InMemoryAgentStateStore. Six cases: - sessionId with '/' persists under the original (userId, sessionId) - nothing leaks into the pair the old SlotRef.parse() would have derived - state replays across two calls in the same session - anonymous user (__anon__ prefix) with '/' in sessionId - sessionId with multiple '/' - plain sessionId without '/' still works (no regression from the fix) The fixture uses a real DingTalk-style openConversationId ("cidLcMOzfRs62haqnq1NO8SxeYdmc/lO8bWyidOisoKAzM=") and asserts the exact corrupted pair the old lastIndexOf('/') split produced, so the test fails loudly rather than silently if slot derivation regresses. Verified both directions: - on main (SlotRef.parse still present): 5 of 6 fail - with the agentscope-ai#2475 fix applied: 6 of 6 pass The only case passing on both is the plain-sessionId one, which the bug never affected.
1 parent 0bdb6bb commit c664ed0

1 file changed

Lines changed: 240 additions & 0 deletions

File tree

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
/*
2+
* Copyright 2024-2026 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.agentscope.core.state;
17+
18+
import static org.junit.jupiter.api.Assertions.assertEquals;
19+
import static org.junit.jupiter.api.Assertions.assertNotNull;
20+
import static org.junit.jupiter.api.Assertions.assertTrue;
21+
22+
import io.agentscope.core.ReActAgent;
23+
import io.agentscope.core.agent.RuntimeContext;
24+
import io.agentscope.core.message.ContentBlock;
25+
import io.agentscope.core.message.Msg;
26+
import io.agentscope.core.message.MsgRole;
27+
import io.agentscope.core.message.TextBlock;
28+
import io.agentscope.core.model.ChatModelBase;
29+
import io.agentscope.core.model.ChatResponse;
30+
import io.agentscope.core.model.GenerateOptions;
31+
import io.agentscope.core.model.ToolSchema;
32+
import java.time.Duration;
33+
import java.util.List;
34+
import java.util.Optional;
35+
import org.junit.jupiter.api.DisplayName;
36+
import org.junit.jupiter.api.Test;
37+
import reactor.core.publisher.Flux;
38+
39+
/**
40+
* Regression tests for <a
41+
* href="https://github.com/agentscope-ai/agentscope-java/issues/2475">#2475</a>.
42+
*
43+
* <p>Bug: {@code ReActAgent} builds an internal slot key as {@code userId + "/" + sessionId}, and
44+
* end-of-call persistence used to re-derive the pair by splitting that key at the <em>last</em>
45+
* {@code '/'} ({@code SlotRef.parse}). When the sessionId itself contains {@code '/'} the split
46+
* produced a corrupted pair, so {@code AgentState} was written under the wrong keys and any later
47+
* read with the original {@code (userId, sessionId)} returned empty/fresh state — silently breaking
48+
* conversation-history replay.
49+
*
50+
* <p>This is not an exotic input: DingTalk {@code openConversationId} values are standard Base64 and
51+
* legitimately contain {@code '/'}.
52+
*
53+
* <p>Fixed by storing {@code userId} / {@code sessionId} directly on {@code CallExecution} instead of
54+
* round-tripping through the concatenated slot key. These tests pin the behavior end-to-end through a
55+
* real {@link ReActAgent} call against an {@link InMemoryAgentStateStore}.
56+
*/
57+
@DisplayName("#2475: AgentState slot integrity when sessionId contains '/'")
58+
class AgentStateSlotKeySessionIdSlashTest {
59+
60+
private static final Duration TIMEOUT = Duration.ofSeconds(15);
61+
private static final String STATE_KEY = "agent_state";
62+
63+
/** A real DingTalk-style openConversationId: Base64, contains a single '/'. */
64+
private static final String DINGTALK_SESSION_ID =
65+
"cidLcMOzfRs62haqnq1NO8SxeYdmc/lO8bWyidOisoKAzM=";
66+
67+
private static final String USER_ID = "u1";
68+
69+
/** Minimal model: answers with plain text so the ReAct loop terminates after one turn. */
70+
private static final class TextOnlyModel extends ChatModelBase {
71+
72+
@Override
73+
public String getModelName() {
74+
return "text-only";
75+
}
76+
77+
@Override
78+
protected Flux<ChatResponse> doStream(
79+
List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) {
80+
return Flux.just(
81+
ChatResponse.builder()
82+
.content(List.<ContentBlock>of(TextBlock.builder().text("ok").build()))
83+
.build());
84+
}
85+
}
86+
87+
private static Msg userMsg(String text) {
88+
return Msg.builder()
89+
.name("user")
90+
.role(MsgRole.USER)
91+
.content(List.<ContentBlock>of(TextBlock.builder().text(text).build()))
92+
.build();
93+
}
94+
95+
private static ReActAgent buildAgent(AgentStateStore store) {
96+
return ReActAgent.builder()
97+
.name("asst")
98+
.sysPrompt("You are concise.")
99+
.model(new TextOnlyModel())
100+
.stateStore(store)
101+
.build();
102+
}
103+
104+
@Test
105+
@DisplayName("sessionId with '/': state is persisted under the original (userId, sessionId)")
106+
void sessionIdWithSlash_statePersistedUnderOriginalSlot() {
107+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
108+
ReActAgent agent = buildAgent(store);
109+
110+
Msg reply =
111+
agent.call(
112+
List.of(userMsg("hi")),
113+
RuntimeContext.builder()
114+
.userId(USER_ID)
115+
.sessionId(DINGTALK_SESSION_ID)
116+
.build())
117+
.block(TIMEOUT);
118+
assertNotNull(reply, "agent call returned no reply");
119+
120+
Optional<AgentState> saved =
121+
store.get(USER_ID, DINGTALK_SESSION_ID, STATE_KEY, AgentState.class);
122+
assertTrue(
123+
saved.isPresent(),
124+
"#2475 regression: no AgentState under the original (userId, sessionId) — the slot"
125+
+ " key was split at the '/' inside the sessionId");
126+
}
127+
128+
@Test
129+
@DisplayName("sessionId with '/': nothing is written to the corrupted split pair")
130+
void sessionIdWithSlash_noStateUnderCorruptedSlot() {
131+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
132+
ReActAgent agent = buildAgent(store);
133+
134+
agent.call(
135+
List.of(userMsg("hi")),
136+
RuntimeContext.builder()
137+
.userId(USER_ID)
138+
.sessionId(DINGTALK_SESSION_ID)
139+
.build())
140+
.block(TIMEOUT);
141+
142+
// Reproduce exactly what the old SlotRef.parse() would have derived: split
143+
// "u1/cidLcMOzfRs62haqnq1NO8SxeYdmc/lO8bWyidOisoKAzM=" at the LAST '/'.
144+
String slotKey = USER_ID + "/" + DINGTALK_SESSION_ID;
145+
int lastSlash = slotKey.lastIndexOf('/');
146+
String corruptedUserId = slotKey.substring(0, lastSlash);
147+
String corruptedSessionId = slotKey.substring(lastSlash + 1);
148+
149+
// Guard: the fixture must actually exercise the corruption path.
150+
assertEquals("u1/cidLcMOzfRs62haqnq1NO8SxeYdmc", corruptedUserId);
151+
assertEquals("lO8bWyidOisoKAzM=", corruptedSessionId);
152+
153+
Optional<AgentState> leaked =
154+
store.get(corruptedUserId, corruptedSessionId, STATE_KEY, AgentState.class);
155+
assertTrue(
156+
leaked.isEmpty(),
157+
"#2475 regression: AgentState leaked into the corrupted slot ("
158+
+ corruptedUserId
159+
+ ", "
160+
+ corruptedSessionId
161+
+ ") — state store accumulates rows under bogus userId prefixes");
162+
}
163+
164+
@Test
165+
@DisplayName("sessionId with '/': second call replays the first call's state")
166+
void sessionIdWithSlash_stateReplayedAcrossCalls() {
167+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
168+
ReActAgent agent = buildAgent(store);
169+
170+
RuntimeContext ctx =
171+
RuntimeContext.builder().userId(USER_ID).sessionId(DINGTALK_SESSION_ID).build();
172+
173+
agent.call(List.of(userMsg("first")), ctx).block(TIMEOUT);
174+
Optional<AgentState> afterFirst =
175+
store.get(USER_ID, DINGTALK_SESSION_ID, STATE_KEY, AgentState.class);
176+
assertTrue(afterFirst.isPresent(), "state missing after first call");
177+
178+
agent.call(List.of(userMsg("second")), ctx).block(TIMEOUT);
179+
Optional<AgentState> afterSecond =
180+
store.get(USER_ID, DINGTALK_SESSION_ID, STATE_KEY, AgentState.class);
181+
assertTrue(
182+
afterSecond.isPresent(),
183+
"#2475 regression: state under the original slot disappeared after the second"
184+
+ " call");
185+
}
186+
187+
@Test
188+
@DisplayName("anonymous user + sessionId with '/': state still lands on the original slot")
189+
void anonymousUserSessionIdWithSlash_statePersistedUnderOriginalSlot() {
190+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
191+
ReActAgent agent = buildAgent(store);
192+
193+
// No userId: slotKey becomes "__anon__/<sessionId>", so the '/' inside the sessionId is
194+
// still the last one and the old parse() corrupted this case too.
195+
agent.call(
196+
List.of(userMsg("hi")),
197+
RuntimeContext.builder().sessionId(DINGTALK_SESSION_ID).build())
198+
.block(TIMEOUT);
199+
200+
Optional<AgentState> saved =
201+
store.get(null, DINGTALK_SESSION_ID, STATE_KEY, AgentState.class);
202+
assertTrue(
203+
saved.isPresent(),
204+
"#2475 regression: anonymous state not stored under the original sessionId");
205+
}
206+
207+
@Test
208+
@DisplayName("sessionId with multiple '/': state still lands on the original slot")
209+
void sessionIdWithMultipleSlashes_statePersistedUnderOriginalSlot() {
210+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
211+
ReActAgent agent = buildAgent(store);
212+
213+
String multiSlash = "a/b/c/d";
214+
agent.call(
215+
List.of(userMsg("hi")),
216+
RuntimeContext.builder().userId(USER_ID).sessionId(multiSlash).build())
217+
.block(TIMEOUT);
218+
219+
Optional<AgentState> saved = store.get(USER_ID, multiSlash, STATE_KEY, AgentState.class);
220+
assertTrue(
221+
saved.isPresent(),
222+
"#2475 regression: multi-slash sessionId not stored under the original slot");
223+
}
224+
225+
@Test
226+
@DisplayName("sessionId without '/': unchanged behavior (no regression from the fix)")
227+
void sessionIdWithoutSlash_unchangedBehavior() {
228+
InMemoryAgentStateStore store = new InMemoryAgentStateStore();
229+
ReActAgent agent = buildAgent(store);
230+
231+
String plainSession = "session-1";
232+
agent.call(
233+
List.of(userMsg("hi")),
234+
RuntimeContext.builder().userId(USER_ID).sessionId(plainSession).build())
235+
.block(TIMEOUT);
236+
237+
Optional<AgentState> saved = store.get(USER_ID, plainSession, STATE_KEY, AgentState.class);
238+
assertTrue(saved.isPresent(), "plain sessionId must keep working after the fix");
239+
}
240+
}

0 commit comments

Comments
 (0)