Skip to content

fix(core): persist agent state under the caller's identity - #3335

Merged
juruoO-o merged 5 commits into
agentscope-ai:mainfrom
quhengshuo:fix/2475-session-id-slash
Nov 11, 2026
Merged

juruoO-o merged 5 commits into
agentscope-ai:mainfrom
quhengshuo:fix/2475-session-id-slash

Conversation

@quhengshuo

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.4-SNAPSHOT (main @ 9c8b10d)

Description

Fixes #2475.

Problem. With an AgentStateStore configured, saveStateToSession recovered (userId, sessionId) by splitting the slot key (userId or "__anon__") + "/" + sessionId at its last /, while loads used the caller's real pair. For a sessionId containing / (e.g. a Base64 DingTalk openConversationId), saves and loads therefore addressed different pairs:

  • A trailing / split into a blank sessionId, so the save failed (sessionId must not be blank).
  • On stores that key user and session separately (InMemory, JsonFile, JDBC/MySQL/PostgreSQL, Mongo), each call started from an empty history, getAgentState(uid, sid) returned a fresh state, and state was written under made-up user ids such as u1/cid..., which also polluted per-user queries like listSessionIds. On versioning stores, every save from the second turn on also hit a spurious CAS conflict (the default OVERWRITE logs a warning; FAIL throws).
  • Redis/OSS/COS join user and session with /, so both pairs mapped to the same storage key and the history loss was masked there.

Fix. CallExecution now carries the resolved (userId, sessionId) as final fields and derives slotKey from them. saveStateToSession passes 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, and streamEvents. SlotRef and 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 to null, and every in-repo store maps null, blank and "__anon__" to the same bucket.

Tests (ReActAgentPerSessionStateTest):

  • Parameterized over ("u1", base64 id), ("u1", "tenant/chat/42"), ("u1", "conv/"), (null, base64 id): state is readable under the caller's pair, and agent_state is written under exactly that pair.
  • Two turns on one session: no CAS conflict, and a rebuilt agent replays both turns.

Without the fix, the new cases fail (4 failures, 1 error).

How to test: mvn -pl agentscope-core verify

Out of scope (happy to follow up separately):

  • The slot key is still not injective: ("u1/a", "b") and ("u1", "a/b") share a key. This needs a userId containing /.
  • Rows written under corrupted pairs before this fix stay orphaned on the stores that key user and session separately (plus the JPA store in agentscope-service). This may be worth a release note.

Credit: same approach as #2476 by @waterWang; the regression-test idea comes from @gxgeek-n.

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing: agentscope-core verify (2491 tests) and agentscope-harness (1057 tests) locally; full repo left to CI
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (N/A, no public API change)
  • Code is ready for review

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
@CLAassistant

CLAassistant commented Sep 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ quhengshuo
❌ ”zhuzhiyu.zzy“


”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 utafrali left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

codecov Bot commented Sep 28, 2026

Copy link
Copy Markdown

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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added both rows in 41538cd; they fail without the fix as well. Also documented on AgentStateStore (b0bdd69) that a blank userId and "__anon__" must resolve to the same namespace as null.

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 oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  • b0bdd691 documents the anonymous-userId invariant on AgentStateStore (blank / "__anon__" / null resolve 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 implicit ReActAgent behavior.
  • 41538cd4 extends the parameterized regression matrix with the "" and "__anon__" rows. Together with the previously added multi-turn coverage of the conv/ 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:

  1. 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.
  2. 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

@jujn jujn added the P0 重要紧急 label Nov 4, 2026
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 juruoO-o left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

补审通过:移除 SlotRef.parse、CallExecution 直接携带 (userId, sessionId) 原身份落盘,含 '/' 的 sessionId 不再被错误拆分;参数化测试覆盖 Base64/尾斜杠/匿名身份与重启回放。CI 双平台绿。

@juruoO-o
juruoO-o merged commit 01eaa24 into agentscope-ai:main Nov 11, 2026
9 of 11 checks passed
juruoO-o added a commit to aiyili/agentscope-java that referenced this pull request Nov 11, 2026
aiyili added a commit to aiyili/agentscope-java that referenced this pull request Nov 12, 2026
chickenlj added a commit that referenced this pull request Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 重要紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:AgentState is persisted under a corrupted (userId, sessionId) slot when sessionId contains '/'

6 participants