Repository navigation
fix(core): persist agent state under the caller's identity - #3335
Conversation
ReActAgent re-derived (userId, sessionId) at save time by splitting the internal slot key "<userId>/<sessionId>" at its last '/'. A sessionId that contains '/' (e.g. a Base64 DingTalk openConversationId) was saved under a corrupted pair while every load used the real one, so each call started from an empty history and later turns hit spurious CAS conflicts; a trailing '/' made the save fail outright. Carry the resolved (userId, sessionId) on CallExecution, derive the slot key from it, and use it for every per-call save. Remove SlotRef and the unused three-argument CallExecution constructor. The slot key format is unchanged. Fixes agentscope-ai#2475
|
”zhuzhiyu.zzy“ seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
utafrali
left a comment
There was a problem hiding this comment.
The fix is correct: removing SlotRef.parse eliminates the fragile lastIndexOf('/') split that silently misrouted saves whenever a sessionId contained /. Carrying userId and sessionId as final fields on CallExecution makes the data flow explicit and the two new test methods cover the key regression cases well. The two comments above are minor polish items, not blockers.
| persistAgentStateCas( | ||
| ref.userId, | ||
| ref.sessionId, | ||
| scope.userId, |
There was a problem hiding this comment.
This quietly changes the value passed to the store for anonymous callers. The old SlotRef.parse always converted the "__anon__" user segment back to null before calling persistAgentStateCas, so every anonymous slot (userId null, blank, or literally "__anon__") hit the same store row. Now scope.userId carries the raw caller-supplied value: a null userId still arrives as null, but an explicit "__anon__" or blank string arrives as-is.
Every in-repo store normalizes these three to the same bucket, so it is safe for the bundled implementations. However, any third-party AgentStateStore that does not apply that normalization will silently split existing anonymous histories across different rows after an upgrade. This is worth calling out in the AgentStateStore interface Javadoc (something like: "null, blank, and \"__anon__\" must all map to the same logical anonymous user"), so implementors know the invariant the framework now relies on.
There was a problem hiding this comment.
Thanks for the review. The two sides already disagreed here before this change: activateSlotForContext has always loaded with the caller's raw userId, and only the save went through SlotRef.parse, which rewrote a blank or literal "__anon__" userId to null. On a store that doesn't normalize, those saves were never read back. Now load and save use the same value, so nothing that was readable before becomes unreadable. Happy to add a note to the AgentStateStore Javadoc that a blank userId should be treated like null (all bundled stores already do this) if maintainers want it in this PR.
| assertEquals( | ||
| Set.of(Arrays.asList(userId, sessionId)), | ||
| store.agentStateWrites, | ||
| "agent_state must never be written under a pair re-derived from the slot key"); |
There was a problem hiding this comment.
The multi-turn CAS test only runs against BASE64_SESSION_ID. The "conv/" trailing-slash case is the one the PR description identifies as causing sessionId must not be blank failures on save — the scenario where the save always wrote to the wrong slot and the second call could never see version 1, making CAS conflicts certain on FAIL policy. That case is the strongest regression to cover here.
Converting this method to @ParameterizedTest @MethodSource("sessionIdsContainingSlash") (matching callPersistsUnderCallerIdentityWhenSessionIdContainsSlash) would close that gap with minimal extra code.
There was a problem hiding this comment.
Good call, parameterized the multi-turn test over the same sessionIdsContainingSlash source in 2cecea2; all four rows fail without the fix. On main the conv/ case already fails on the first save (sessionId must not be blank), which the first test catches; the multi-turn test now also covers the anonymous and multi-segment ids.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Run historySurvivesCallsAndRestartsWhenSessionIdContainsSlash over the same sessionIdsContainingSlash source as the single-call test, so the anonymous, multi-segment and trailing-slash ids are also checked across two turns and an agent restart.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
The PR fixes the sessionId-with-slash bug by carrying the resolved (userId, sessionId) pair on CallExecution and using it directly for agent_state saves, eliminating the fragile SlotRef.parse split. The identity flow is now consistent across normal calls, structured-output paths, failure saves, interrupts, and streamEvents, and making userId/sessionId/slotKey final improves thread-safety when saves run on Schedulers.boundedElastic(). The regression tests cover the key broken cases well; the remaining concerns are minor: the AgentStateStore interface should document the null/blank/"anon" normalization invariant (already raised by another reviewer), and the slot key remains non-injective for userIds containing '/'. Overall the change is correct and safe to merge after addressing the documentation/test polish items.
Re-reviewed at head bb0572699d; CLA: signed.
Automated review by github-manager-bot
| */ | ||
| private static String slotKey(String userId, String sessionId) { | ||
| Objects.requireNonNull(sessionId, "sessionId must not be null"); | ||
| return (userId == null || userId.isBlank() ? "__anon__" : userId) + "/" + sessionId; |
There was a problem hiding this comment.
The slotKey format is still non-injective for userId values containing / (e.g. ("u1/a", "b") and ("u1", "a/b") both map to "u1/a/b"). The PR correctly fixes the sessionId-with-slash case, but slash-bearing userIds can still cause cross-slot stateCache/slotVersions collisions and unintended call-serialization sharing. This is acknowledged as out of scope, so this is a residual risk to track rather than a regression.
There was a problem hiding this comment.
Agreed, tracked in #3337 so it doesn't get lost.
| private void recordWrite(String userId, String sessionId, String key) { | ||
| if ("agent_state".equals(key)) { | ||
| agentStateWrites.add(Arrays.asList(userId, sessionId)); | ||
| } |
There was a problem hiding this comment.
The new parameterized test covers null userId but not blank or the literal "__anon__" userId. The PR's compatibility claim relies on all three mapping to the same anonymous bucket, so adding Arguments.of("", BASE64_SESSION_ID) and Arguments.of("__anon__", BASE64_SESSION_ID) to sessionIdsContainingSlash() would lock that invariant in place.
ReActAgent treats a null, blank or "__anon__" userId as the same anonymous caller and passes the caller's raw value to the store, so implementations must resolve all three to one namespace. Every bundled store already does this; state it on the interface for third-party implementations.
Add both to sessionIdsContainingSlash so the single-call and multi-turn regression tests also pin the anonymous-caller variants.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of 41538cd4 (previous review was on 2cecea2c). Both follow-up commits land exactly what the review thread asked for, and the core fix is unchanged. Verdict: no new findings.
b0bdd691documents the anonymous-userId invariant onAgentStateStore(blank /"__anon__"/nullresolve to the same namespace), which is the right place: it makes the contract every store relies on part of the SPI javadoc instead of an implicitReActAgentbehavior.41538cd4extends the parameterized regression matrix with the""and"__anon__"rows. Together with the previously added multi-turn coverage of theconv/trailing-slash case, the failure mode from #2475 (save/load pair divergence on slash-containing sessionIds) is now pinned by tests on all three identity shapes.- The carry-over limitation you flagged (slot key non-injectivity,
("u1/a","b")vs("u1","a/b")) is tracked in #3337 — good that it has an owner rather than living only in this thread.
Two notes for maintainers, neither blocking:
- CI was still running at review time (
build (ubuntu/windows-latest)pending; License and Module Sync pass), so this comment isn't a merge signal on its own. - The PR description's "out of scope" point about rows written under corrupted pairs before this fix staying orphaned on stores that key user and session separately (plus the JPA store) is worth a release note when this lands.
Automated review by github-manager-bot
Resolve the saveLegacyState conflict by keeping main's cancellation-aware write gate (beginStateWrite / try-finally) while persisting under the caller's resolved (userId, sessionId) from CallExecution instead of the removed SlotRef slot-key parsing.
juruoO-o
left a comment
There was a problem hiding this comment.
补审通过:移除 SlotRef.parse、CallExecution 直接携带 (userId, sessionId) 原身份落盘,含 '/' 的 sessionId 不再被错误拆分;参数化测试覆盖 Base64/尾斜杠/匿名身份与重启回放。CI 双平台绿。
AgentScope-Java Version
2.0.4-SNAPSHOT (main @ 9c8b10d)
Description
Fixes #2475.
Problem. With an
AgentStateStoreconfigured,saveStateToSessionrecovered(userId, sessionId)by splitting the slot key(userId or "__anon__") + "/" + sessionIdat its last/, while loads used the caller's real pair. For a sessionId containing/(e.g. a Base64 DingTalkopenConversationId), saves and loads therefore addressed different pairs:/split into a blank sessionId, so the save failed (sessionId must not be blank).getAgentState(uid, sid)returned a fresh state, and state was written under made-up user ids such asu1/cid..., which also polluted per-user queries likelistSessionIds. On versioning stores, every save from the second turn on also hit a spurious CAS conflict (the default OVERWRITE logs a warning;FAILthrows)./, so both pairs mapped to the same storage key and the history loss was masked there.Fix.
CallExecutionnow carries the resolved(userId, sessionId)as final fields and derivesslotKeyfrom them.saveStateToSessionpasses that pair to the store. Every per-call save goes through this one method: normal completion, both structured-output paths, the failure path, user interrupt, andstreamEvents.SlotRefand the unused 3-arg constructor are removed. The slot-key format is unchanged; it stays an opaque cache/serialization key.Identities without
/still land on the same rows: saves now pass the caller's raw userId, so a blank or literal"__anon__"userId is no longer rewritten tonull, and every in-repo store maps null, blank and"__anon__"to the same bucket.Tests (
ReActAgentPerSessionStateTest):("u1", base64 id),("u1", "tenant/chat/42"),("u1", "conv/"),(null, base64 id): state is readable under the caller's pair, andagent_stateis written under exactly that pair.Without the fix, the new cases fail (4 failures, 1 error).
How to test:
mvn -pl agentscope-core verifyOut of scope (happy to follow up separately):
("u1/a", "b")and("u1", "a/b")share a key. This needs a userId containing/.Credit: same approach as #2476 by @waterWang; the regression-test idea comes from @gxgeek-n.
Checklist
mvn spotless:applyverify(2491 tests) and agentscope-harness (1057 tests) locally; full repo left to CI