Skip to content

fix(agent): agent state redis key without same hashslot - #3129

Merged
xzxiaoshan merged 8 commits into
agentscope-ai:mainfrom
rudy2steiner:redis-agent-state
Oct 10, 2026
Merged

xzxiaoshan merged 8 commits into
agentscope-ai:mainfrom
rudy2steiner:redis-agent-state

Conversation

@rudy2steiner

@rudy2steiner rudy2steiner commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Background

RedisAgentStateStore uses a Lua script to update the state value, version, and session index atomically. Redis Cluster requires every key passed to one Lua script to belong to the same hash slot.

The original key layout did not use a Redis hash tag:

  • agentscope:session:userId/sessionId:agent_state
  • agentscope:session:userId/sessionId:agent_state:ver
  • agentscope:session:userId/sessionId:_keys

Redis Cluster hashes these complete keys independently, so they may be assigned to different slots and the save or CAS operation fails with CROSSSLOT.

Related issue: #3085

What Changed

  • Added explicit V0 and V1 key layouts. V0 remains the default to preserve existing behavior; V1 must be selected for Redis Cluster.
  • V1 wraps the session segment in a Redis hash tag:
    • V0: agentscope:session:userId/sessionId:agent_state
    • V1: agentscope:session:{userId/sessionId}:agent_state
  • The state key, version key, and session index now share one Redis Cluster slot under V1.
  • Applied the configured layout consistently to single state, list state, exists, delete, and listSessionIds.
  • Added a RedisDistributedStore.fromJedis(...) overload that accepts the key layout version.
  • Updated Jedis key scanning to iterate across all Redis Cluster masters.
  • Delete unused and dangerous clearAllSessions
  • Added validation for V1 key components and escaped Redis glob characters used by session listing.
  • Added focused unit tests and real three-master Redis Cluster integration tests for V1 save/CAS and cluster-wide session listing.
  • Documented the V0/V1 key differences and migration process in the English and Chinese Redis distributed-storage guides.

V0 and V1 use different key namespaces and do not read each other's data. All application instances sharing a key prefix must use the same layout version and migrate existing V0 data before switching to V1.

@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.20000% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...tensions/redis/state/RedisAgentStateKeyLayout.java 91.07% 0 Missing and 5 partials ⚠️
...tscope/extensions/redis/RedisDistributedStore.java 83.33% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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

Introduces RedisAgentStateKeyLayout so the versioned state key, its :ver key and the session :_keys marker share one Redis Cluster hash slot (fixing the CROSSSLOT failure of the Lua CAS path), keeps legacy v0 sessions readable, and adds a solid mock-based test suite. The layout extraction itself is clean and well documented — but the v0/v1 decision is inferred from the existence of the v0 :_keys marker while list state is always written under v0, which lets a list write flip an existing v1 session back to v0. That is a data-loss path and needs to be addressed before merge.

Findings

  • [Critical] RedisAgentStateStore.java:306 — save(list) creates the v0 :_keys marker, so resolve() afterwards returns v0 for a session whose versioned state lives under v1: reads silently return empty, the next write duplicates the key, and delete() orphans the v1 keys. Layout depends on write order.
  • [Warning] RedisAgentStateKeyLayout.java:65 — EXISTS probe on every versioned op (extra round trip per state access) and non-deterministic under concurrency; prefer an explicit/pinned layout choice.
  • [Warning] RedisAgentStateStore.java:405 — delete() removes only one layout while a session can legitimately own keys in both.
  • [Warning] RedisAgentStateKeyLayout.java:82 — raw userId/sessionId interpolated into a hash tag and KEYS glob patterns ({}, *, ?, [, /) corrupt slot assignment and parsing.
  • [Warning] RedisAgentStateStore.java:441 — cluster-safety is incomplete for the multi-key deleteKeys(...) in delete()/clearAllSessions(), which still spans slots across sessions.
  • [Info] tests — interleaved sequence, dual-layout delete and hostile ids are untested; a testcontainers cluster test would prove the fix end-to-end.
  • [Info] RedisAgentStateKeyLayout.java:43 — no operator escape hatch (explicit layout version) and no documented v0 -> v1 migration path.

Suggestions

The smallest safe fix for the Critical item: make resolve() decide the versioned layout from a marker that only versioned writes create (e.g. existence of the v0 state/:ver key or a dedicated :_layout key written once), or track list keys under the same resolved layout as versioned keys — then the v0 marker can never be produced by a list write.

CI / Merge state

  • mergeable=MERGEABLE, mergeStateStatus=BLOCKED (required review/approval outstanding).
  • Codecov reports patch coverage 89.02% with 9 lines uncovered.
  • No license/cla status is reported on this head, so CLA state is unknown to me — a maintainer should confirm before merging.

Nice work on the key-layout extraction and the documentation comments; the mixed-layout interaction is the one thing I would not merge without resolving.


Automated review by github-manager-bot

public void save(String userId, String sessionId, String key, List<? extends State> values) {
String slotId = slotId(userId, sessionId);
String listKey = getListKey(slotId, key);
RedisAgentStateKeyLayout keyLayout = v0KeyLayout(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.

[Critical] A list write flips an existing v1 session back to the v0 layout, making already-written v1 state invisible.

save(list) always uses v0KeyLayout(...), and the marker it writes (addToSet(keysKey, ...) at line 339) is therefore the v0 :_keys key. But RedisAgentStateKeyLayout.resolve() decides the layout solely from keyExists(v0._keys).

Sequence for a session created after this change:

  1. save(userId, sessionId, "state", value) -> no v0 marker -> v1 layout; state + :ver + v1 :_keys written under prefix{{user}/{sess}}:....
  2. save(userId, sessionId, "items", list) -> writes v0 list keys and creates the v0 :_keys marker.
  3. Any later get(...)/getVersioned(...)/saveIfVersion(...) now resolves to v0 and reads prefix{user}/{sess}:state, which does not exist -> the state written in step 1 silently disappears (empty Optional / version reset), and the following save overwrites under a different key.
  4. delete(...) also resolves to v0 afterwards, so the v1 state/ver/_keys keys are never removed -> permanent orphan keys.

This is data loss in a normal usage pattern (versioned state + message list for the same session), and it also means the layout a session ends up in depends on write order. Suggested fix: keep the layout decision per key-family rather than per session — i.e. list keys always v0 and only presence of a v0 versioned state/_keys marker drives versioned reads — or put list state under the same resolved layout as versioned state so the v0 marker can never be created by a list write for a v1 session. Please also add a regression test for the interleaved sequence save(single) -> save(list) -> getVersioned(single).

static RedisAgentStateKeyLayout resolve(
RedisClientAdapter client, String keyPrefix, String userId, String sessionId) {
RedisAgentStateKeyLayout v0 = v0(keyPrefix, userId, sessionId);
if (client.keyExists(v0.getKeysKey())) {

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.

[Warning] Layout probing adds one EXISTS round trip to every versioned read/write, and is not concurrency-safe.

resolve() is called from saveVersioned, getVersioned, saveIfVersion, get, delete — so every state operation now costs an extra round trip before the real work, on a path that is typically hit once per agent turn. Two consequences worth documenting/optimising:

  • Cost: for standalone/sentinel deployments that never had this key, a per-session layout cache (bounded, or a one-shot flag stored on the session) avoids paying EXISTS on every call.
  • Race: two threads writing the same brand-new session can both observe keyExists == false and pick v1 (fine), but a thread that runs after the v0 marker first appears will switch layouts mid-flight — see the interleaving problem flagged on RedisAgentStateStore.save(list).

A deterministic choice (config-selected layout version, or layout pinned by the first write and never inferred from key existence) would remove both issues.

public void delete(String userId, String sessionId) {
String slotId = slotId(userId, sessionId);
String keysKey = getKeysKey(slotId);
RedisAgentStateKeyLayout keyLayout = resolveKeyLayout(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.

[Warning] delete() only ever removes one layout's keys, so v0+v1 sessions leak keys.

delete() resolves a single layout and deletes only the keys derived from it. Because list state is intentionally written under v0 while versioned state may be under v1 (and vice versa, depending on write order), a session can legitimately own keys in both layouts; the current implementation cannot clean up both. clearAllSessions() (pattern keyPrefix + "*") does cover both, which highlights the asymmetry.

Consider collecting keys from both v0 and v1 markers in delete() (two SMEMBERS + one deleteKeys per layout, or a merged set) so that deletion is complete regardless of which layout the session ended up in.

* @return v1 cluster-safe key layout
*/
static RedisAgentStateKeyLayout v1(String keyPrefix, String userId, String sessionId) {
return new RedisAgentStateKeyLayout(

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.

[Warning] userId/sessionId are interpolated raw into a hash tag and into KEYS/glob patterns.

v1() builds "{" + normalizeUser(userId) + "/" + sessionId + "}", and v1KeysPattern/v0KeysPattern are consumed by findKeysByPattern. That means:

  • a userId/sessionId containing {, } or */?/[ moves or breaks the hash tag and the glob match (keys could land in the wrong slot, or listSessionIds silently returns nothing);
  • a sessionId containing / is mis-parsed by parseV0SessionIdKeysKey/parseV1SessionIdFromKeysKey, which split on the first / boundary implicitly by prefix length.

Since these ids come from external callers (tenant/user identifiers), please validate or encode them (e.g. reject or escape {}, *, ?, [, /) in sessionSegment(...) and add a test for hostile ids. Note #3112 (fail early for incompatible Redisson state-store clients) shows this area is sensitive to silently-wrong behaviour.

String sessionId =
withoutPrefix.substring(0, withoutPrefix.length() - KEYS_SUFFIX.length());
sessionIds.add(sessionId);
String v1KeysPattern = RedisAgentStateKeyLayout.v1KeysPattern(keyPrefix, userSegment);

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.

[Warning] The Redis Cluster bug is fixed for keys inside one session, but the multi-key DEL in delete() still spans slots.

The hash tag makes state, ver and _keys share a slot, which is what the Lua CAS needs — good. But delete() finishes with client.deleteKeys(keysToDelete.toArray(...)), and clearAllSessions() deletes a whole keyPrefix + "*" scan set in one call. Under Redis Cluster those calls pass keys from many sessions (many slots); depending on adapter that is a CROSSSLOT error or a silent partial delete, so the cluster-safety story is incomplete. Please confirm the adapters' behaviour (Redisson batch vs JedisCluster.del(String...) vs Lettuce) and, if needed, group keys per slot / delete one-by-one. Worth calling out explicitly in the class javadoc either way.

@@ -81,4 +94,216 @@ void saveIfVersionCasDelegatesToLua() {
assertEquals(5L, version);
verify(client, times(1)).evalScript(any(), anyList(), anyList());

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.

[Info] Test coverage is good for the happy paths; the risky transitions are untested. Mock-based tests assert which key strings reach the client, which is the right level, but please add: (a) the interleaved save(single) -> save(list) -> getVersioned(single) sequence from the finding above; (b) delete() for a session that owns keys in both layouts; (c) listSessionIds when a userId/sessionId contains glob or hash-tag characters. A testcontainers-backed cluster smoke test (testcontainers is already a project dependency) would be the only way to prove the slot assumption end-to-end.

private final String keyPrefix;

private final String slotId;

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.

[Info] Class-level javadoc of RedisAgentStateKeyLayout: the v0/v1 split has no operator-facing escape hatch. Deployments that would rather start clean (or roll back) cannot choose a layout explicitly, and there is no migration path documented for v0 -> v1 (v0 sessions stay non-cluster-safe forever, which is exactly the reported failure mode). Consider a RedisAgentStateStore builder option (e.g. keyLayoutVersion(v1) / forceClusterSafeLayout()) plus a short migration note in the docs.

@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

330ead5f fixes the blocking issue from my previous round: save(list) / getList(...) now go through resolveKeyLayout(...) instead of hard-coding the v0 layout, so a list write can no longer create a v0 :_keys marker for a session whose versioned state lives under v1 — and listSaveDoesNotMoveExistingClusterSafeSessionBackToLegacyLayout pins exactly the interleaving that used to lose data. CI is green (build on ubuntu + windows) and the CLA is signed. Thanks for the quick and precise turnaround.

Downgrading to COMMENT rather than APPROVE because two layout-resolution inconsistencies are still open (one of them a direct consequence of the fix): exists() and resolve() now disagree about which marker wins, delete() still cleans only one layout, and the class javadoc still documents the behaviour the new commit removed. None of these look hard to close.

Findings

  • [Warning] RedisAgentStateStore.java:54 — class javadoc still says list state keeps the v0 layout, which 330ead5f made untrue.
  • [Warning] RedisAgentStateStore.java:387 — exists() probes v1 first, resolve() probes v0 first: contradictory answers for a session with both markers.
  • [Warning] RedisAgentStateStore.java:405 — delete() removes only one layout's keys (carried over, still open).
  • [Info] RedisAgentStateStoreTest.java:217 — regression test for the fixed sequence confirmed; delete-mixed-layout and hostile-id cases still untested.

Carried over and unchanged from the previous round, so I won't re-annotate them: the per-operation EXISTS probe cost in resolve(), raw userId/sessionId interpolation into hash tags and KEYS glob patterns, the cross-slot deleteKeys(...) in delete() / clearAllSessions(), and the missing operator-facing layout-version switch.


Automated review by github-manager-bot

* {@code {userId}/{sessionId}} (or {@code __anon__/{sessionId}} when user id is absent). Existing
* versioned state entries keep their v0 non-hash-tagged session segment. New versioned state
* entries use a Redis Cluster-safe hash-tagged session segment, where {@code {userId}/{sessionId}}
* is wrapped in braces. List state keeps the v0 non-hash-tagged layout.

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.

[Warning] The new commit 330ead5f moved list state onto the resolved layout, but this class javadoc still states the opposite: "List state keeps the v0 non-hash-tagged layout", and the key-structure bullets at lines 60-63 document list keys as {prefix}{userId}/{sessionId}:{stateKey}:list. Since save(list)/getList(...) now call resolveKeyLayout(...), a brand-new session's list keys are in fact hash-tagged ({prefix}{user/session}:messages:list). Please update this block (and the matching sentence in RedisAgentStateKeyLayout lines 29-30) — the layout is what operators use to size, scan and migrate keys, so a doc that contradicts the code is a real hazard here.

try {
return client.keyExists(keysKey) && client.getSetSize(keysKey) > 0;
String v1KeysKey = v1KeyLayout.getKeysKey();
if (client.keyExists(v1KeysKey)) {

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.

[Warning] exists() and resolve() use opposite layout precedence. exists() probes v1 first and only falls back to v0 when the v1 marker is missing, while RedisAgentStateKeyLayout.resolve() (used by get/getVersioned/save/saveIfVersion/delete) probes v0 first and only uses v1 when no v0 marker exists. For a session that owns both markers — a v0 session created before this change that later got versioned state, or any partially migrated session — exists() can report the v1 view while every read/write/delete acts on the v0 view, so a caller sees exists == false for data it can still read (or vice versa). Worth picking one documented precedence rule and sharing a single helper between exists() and resolve(); the existsSelectsClusterSafeLayoutBeforeLegacyFallback test currently locks in the v1-first behaviour, so it would need updating with whichever direction you choose.

public void delete(String userId, String sessionId) {
String slotId = slotId(userId, sessionId);
String keysKey = getKeysKey(slotId);
RedisAgentStateKeyLayout keyLayout = resolveKeyLayout(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.

[Warning] Carried over from the previous round and still open: delete() resolves exactly one layout, so a session that legitimately owns keys under both v0 and v1 is only half removed and the other layout's state/ver/_keys entries stay as permanent orphans. clearAllSessions() (keyPrefix + "*") does cover both, which shows the asymmetry. Collecting tracked members from both markers (two SMEMBERS + one merged deleteKeys) would make deletion complete regardless of how a session ended up mixed.

})
.when(client)
.addToSet(anyString(), anyString());

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.

[Info] listSaveDoesNotMoveExistingClusterSafeSessionBackToLegacyLayout is exactly the regression test the previous round asked for — thanks, the interleaved save(single) -> save(list) -> getVersioned(single) sequence is now pinned and the atomic AtomicBoolean marker simulation makes the failure mode impossible to reintroduce silently. Two gaps still open from last time: delete() for a session that owns keys in both layouts, and listSessionIds/key building when a userId/sessionId contains {, }, *, ? or /.

@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

This PR introduces a Redis Cluster-safe v1 key layout for RedisAgentStateStore by wrapping the session segment in a Redis hash tag ({userId/sessionId}), while keeping existing v0 sessions on the legacy non-tagged layout so previously persisted state remains readable and writable. Key construction is extracted into RedisAgentStateKeyLayout, and several unit tests are added for layout selection, backward compatibility, and cluster-safe key strings. The critical regression where save(userId, sessionId, key, List) forced v0 layout for an existing v1 session is fixed in the current head.

However, the layout resolution is still racy and performed on every call, delete() only cleans one of the two possible layouts, user/session identifiers are interpolated into keys and patterns unsafely, and the precedence between exists() and resolveKeyLayout() is inconsistent. These issues affect correctness, safety in Redis Cluster, and key hygiene, so the PR needs another revision before approval.

Previous findings status

  • [Critical] save(list) used v0KeyLayout, flipping an existing v1 session back to v0. Fixed in the current head; save(userId, sessionId, key, List) now calls resolveKeyLayout() and the new test listSaveDoesNotMoveExistingClusterSafeSessionBackToLegacyLayout guards it.
  • [Warning] RedisAgentStateKeyLayout.resolve() adds an extra EXISTS round trip on every versioned read/write and is not concurrency-safe. Still open.
  • [Warning] delete() removes only one resolved layout, leaking keys of the other layout. Still open.
  • [Warning] userId/sessionId interpolated raw into the hash tag and into KEYS/glob patterns (wildcard injection / cross-session key collision risk). Still open.
  • [Warning] exists() probes v1-first while resolve() may pick v0 — inconsistent precedence. Still open.
  • [Info] Class javadoc of RedisAgentStateStore still claims list state keeps the v0 layout. Still open; the statement is now actively misleading because new sessions write list keys with the v1 layout.
  • [Info] No operator-facing way to pin/roll back the layout (v0 vs v1) for a deployment. Still open.
  • [Info] Test gaps: interleaved save(single)/save(list) ordering, delete of mixed-layout session, exists() precedence. Partially addressed — exists() precedence and list-v1-layout are now tested, but mixed-layout deletion and interleaved ordering are not.

Verdict

REQUEST_CHANGES — The racy per-call layout resolution, single-layout deletion, and unsanitized userId/sessionId interpolation are material correctness and cluster-safety issues that should be fixed before this PR is merged.

Findings

  • [WARNING] RedisAgentStateKeyLayout.java:65 — RedisAgentStateKeyLayout.resolve() performs an extra EXISTS round trip on every versioned read/write and the v0/v1 decision is not atomic. Between the probe at line 65 and the subsequent write, another client can create the v0 marker, causing the same logical session to be split across both layouts. Consider caching the resolved layout per (userId, sessionId) in the store or providing an explicit, atomic migration path.
  • [WARNING] RedisAgentStateStore.java:405 — delete() resolves the layout once (line 405) and only deletes keys belonging to that layout. If a session ever ends up with both v0 and v1 marker sets (e.g., due to the resolve() race or a partial migration), keys from the other layout leak forever. Delete both layouts, or ensure resolve() can never produce a mixed-layout session.
  • [WARNING] RedisAgentStateKeyLayout.java:248 — sessionSegment() (line 248) interpolates userId and sessionId literally into Redis keys, hash tags, and SCAN patterns without escaping. A sessionId such as s*1 turns v1KeysPattern() into prefix{user/s*1}:_keys and matches unrelated sessions; } or { in userId/sessionId breaks Redis hash-tag parsing and can make v1 keys hash to the wrong cluster slot or collide with other sessions. Sanitize or reject characters that have Redis pattern/key semantics.
  • [WARNING] RedisAgentStateStore.java:387 — exists() checks the v1 marker first and falls back to v0 (lines 387-392), while resolveKeyLayout() (used by every read/write) prefers v0 whenever the v0 marker exists. For a session with both markers, exists() and the actual storage layout can disagree on which keys matter. Use the same precedence in both paths.
  • [INFO] RedisAgentStateStore.java:54 — The class-level Javadoc still states that "List state keeps the v0 non-hash-tagged layout" (line 54), but save(userId, sessionId, key, List) now calls resolveKeyLayout() (line 306), so new sessions write list keys with the hash-tagged v1 layout. Update the Javadoc to reflect that list layout follows the resolved session layout.
  • [INFO] RedisAgentStateStoreTest.java:102 — newSessionSaveUsesOneHashSlotForLuaKeys asserts that Lua keys contain the string "{user/s1}" (via assertClusterSafeSessionKeys), but string containment does not prove the keys share the same Redis Cluster hash slot. Add a hash-slot assertion (e.g., using JedisClusterCRC16.getSlot) over the captured Lua keys, or an integration test against a real cluster.
  • [INFO] RedisAgentStateStoreTest.java:257 — deleteSessionUsesLegacyLayoutWhenOnlyLegacyMarkerExists covers deletion of a purely v0 session, but there is no test for a mixed-layout session where both v0 and v1 marker sets exist. Such a test would expose that delete() currently leaves the unresolved layout behind.

Automated review by github-manager-bot — round 3 (re-review after the merge of main). All findings above are inline comments on the current head f4e6e167; the previous save(list) critical regression is confirmed fixed.

static RedisAgentStateKeyLayout resolve(
RedisClientAdapter client, String keyPrefix, String userId, String sessionId) {
RedisAgentStateKeyLayout v0 = v0(keyPrefix, userId, sessionId);
if (client.keyExists(v0.getKeysKey())) {

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.

[Warning] RedisAgentStateKeyLayout.resolve() performs an extra EXISTS round trip on every versioned read/write and the v0/v1 decision is not atomic. Between the probe at line 65 and the subsequent write, another client can create the v0 marker, causing the same logical session to be split across both layouts. Consider caching the resolved layout per (userId, sessionId) in the store or providing an explicit, atomic migration path.

public void delete(String userId, String sessionId) {
String slotId = slotId(userId, sessionId);
String keysKey = getKeysKey(slotId);
RedisAgentStateKeyLayout keyLayout = resolveKeyLayout(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.

[Warning] delete() resolves the layout once (line 405) and only deletes keys belonging to that layout. If a session ever ends up with both v0 and v1 marker sets (e.g., due to the resolve() race or a partial migration), keys from the other layout leak forever. Delete both layouts, or ensure resolve() can never produce a mixed-layout session.

if (sessionId == null || sessionId.isBlank()) {
throw new IllegalArgumentException("sessionId must not be blank");
}
return normalizeUser(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.

[Warning] sessionSegment() (line 248) interpolates userId and sessionId literally into Redis keys, hash tags, and SCAN patterns without escaping. A sessionId such as s*1 turns v1KeysPattern() into prefix{user/s*1}:_keys and matches unrelated sessions; } or { in userId/sessionId breaks Redis hash-tag parsing and can make v1 keys hash to the wrong cluster slot or collide with other sessions. Sanitize or reject characters that have Redis pattern/key semantics.

try {
return client.keyExists(keysKey) && client.getSetSize(keysKey) > 0;
String v1KeysKey = v1KeyLayout.getKeysKey();
if (client.keyExists(v1KeysKey)) {

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.

[Warning] exists() checks the v1 marker first and falls back to v0 (lines 387-392), while resolveKeyLayout() (used by every read/write) prefers v0 whenever the v0 marker exists. For a session with both markers, exists() and the actual storage layout can disagree on which keys matter. Use the same precedence in both paths.

* {@code {userId}/{sessionId}} (or {@code __anon__/{sessionId}} when user id is absent). Existing
* versioned state entries keep their v0 non-hash-tagged session segment. New versioned state
* entries use a Redis Cluster-safe hash-tagged session segment, where {@code {userId}/{sessionId}}
* is wrapped in braces. List state keeps the v0 non-hash-tagged layout.

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.

[Info] The class-level Javadoc still states that "List state keeps the v0 non-hash-tagged layout" (line 54), but save(userId, sessionId, key, List) now calls resolveKeyLayout() (line 306), so new sessions write list keys with the hash-tagged v1 layout. Update the Javadoc to reflect that list layout follows the resolved session layout.


@Test
@DisplayName("new session save passes only cluster-safe keys to Lua")
void newSessionSaveUsesOneHashSlotForLuaKeys() {

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.

[Info] newSessionSaveUsesOneHashSlotForLuaKeys asserts that Lua keys contain the string "{user/s1}" (via assertClusterSafeSessionKeys), but string containment does not prove the keys share the same Redis Cluster hash slot. Add a hash-slot assertion (e.g., using JedisClusterCRC16.getSlot) over the captured Lua keys, or an integration test against a real cluster.

assertTrue(deleted.contains("agentscope:session:{user/s1}:agent_state:ver"));
}

@Test

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.

[Info] deleteSessionUsesLegacyLayoutWhenOnlyLegacyMarkerExists covers deletion of a purely v0 session, but there is no test for a mixed-layout session where both v0 and v1 marker sets exist. Such a test would expose that delete() currently leaves the unresolved layout behind.

oss-maintainer

This comment was marked as abuse.

@jujn

jujn commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

@xzxiaoshan PTAL Thanks.

@xzxiaoshan

xzxiaoshan commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

下面整理了表格,统一说明:

待修复问题

# 大概的代码位置 说明
1 JedisClientAdapter.java:155-169 Cluster 下无 key 的 SCAN 只会落到一个节点上,listSessionIds 会漏掉其他节点上的会话,而且没有任何报错,比直接失败更隐蔽。Jedis 有现成的全节点迭代 API scanIteration(),建议换掉这个循环。Lettuce 和 Redisson 的实现已经覆盖全部 master,不用动。这也是 v1-only 下唯一跨 slot 作用域的方法,修好它跨 slot 面就补齐了。
2 RedisAgentStateStore.java:479-493 这个方法建议直接删掉。全库清除没有用户维度,隔离只有 keyPrefix 一层,多个应用共用一个 Redis 时会互相误伤;Jedis Cluster 上还会漏分片、批量 DEL 跨 slot 报错。它不在 AgentStateStore 接口上,框架内部也没有任何调用,全库清理是一个很危险的行为,如果业务真需要全库清理的业务自己实现更合适。
3 RedisAgentStateStore.java:382-394 这里把 sessionId 的校验异常包进了 RuntimeException,delete() 也是同样写法。但 save/get 路径的布局构造在 try 外面,blank sessionId 抛的是原始 IllegalArgumentException,两边行为不一致。建议把校验挪到 try 之前,和其他方法对齐。
4 RedisAgentStateKeyLayout.java:118-120 userId 是直接拼进 SCAN pattern 的,含 * ? [ 这类字符时会误匹配别的用户的会话。#2579 里有现成的 glob 转义,建议一并移植,顺带对 id 和 prefix 里的花括号加个校验。
5 RedisAgentStateStoreTest.java 单测都是 mock 的,验证 key 拼接没问题,但验证不了 Cluster 上 CROSSSLOT 真的消失。#2579 里有现成的 Testcontainers 集成测试,可以考虑移植或者看什么方式比较合适。如果已经在真实 Cluster 上手动验证过,也可以在 PR 描述里补一句结论。
6 RedisAgentStateKeyLayout.java:63-70 PR 描述里写的是 exists 先查 v1 marker、缺失才回退 v0,代码实际是先查 v0,测试 existsUsesResolvedLegacyLayoutWhenBothMarkersExist 断言的也是 v0 优先。应该是最后一个 commit 改了优先级但描述没跟上,两边需要取齐;如果按 v1-only 方向改,兼容行为这节描述直接重写。

@rudy2steiner 处理一下

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Summary

Re-check at the same head 65e52f5c: no new commits since my previous pass, and the thread has since picked up a detailed list from @xzxiaoshan, so this comment only records what still stands on my side and where it overlaps. I am not re-listing items @xzxiaoshan already located.

What still blocks the approval (both pinned inline)

  • Unsanitized userId/sessionId interpolated into the hash tag and into the SCAN glob patterns (RedisAgentStateKeyLayout.java:118, also 84/130/245). Overlaps @xzxiaoshan item Do you have any plans to release a JavaScript/TypeScript SDK? #4 on the glob side; the hash-tag side ({, }, / in an id) additionally breaks the cross-slot guarantee that is the whole point of the v1 layout.
  • Layout resolution costs an extra EXISTS round trip on every state operation and the v0/v1 choice is not atomic (RedisAgentStateKeyLayout.java:66, called from 7 places in RedisAgentStateStore).

Note on @xzxiaoshan item #6 (description vs code precedence)

From my earlier pass the code side is consistent: exists() goes through resolveKeyLayout() and the both-markers test asserts v0-first. So #6 looks like a PR-description fix rather than a behaviour fix - the "Compatibility behavior" section should be rewritten to say v0-first (or v1-only if that is the chosen direction), not the other way round.

Not verified by me

Items #1 (Jedis cluster SCAN visiting a single shard), #2 (whole-DB clear helper), #3 (validation exception wrapping inconsistency), #5 (mock-only tests vs real-cluster proof) are outside what I re-checked this round; I have no counter-evidence and they read as legitimate - I would treat #1 and #2 as blocking on the maintainer's judgement.

Path forward

Push the fixes for the two inline items together with the maintainer list and ping me - I will review only the delta against 65e52f5c. CI (Check License, Check Module Sync, ubuntu + windows builds, codecov) is green on this head and CLA is signed; reviewDecision stays CHANGES_REQUESTED until the items above are addressed.

Inline notes (anchored to this head)

  • [WARNING] agentscope-extensions/agentscope-extensions-redis/src/main/java/io/agentscope/extensions/redis/state/RedisAgentStateKeyLayout.java:66 — Re-verified at this head: still open. resolve(...) calls client.keyExists(v0.getKeysKey()) on every invocation, and RedisAgentStateStore resolves on every save/get/saveIfVersion/getVersioned/getList/exists (RedisAgentStateStore.java:234, 262, 286, 305, 347, 363, 384) - one extra round trip per state operation, and the check-then-choose sequence is not atomic: between the EXISTS returning false and the following v1 read/write, another caller can create a v0 marker, so a session can end up split across layouts. Smallest fix: cache the resolved layout per (userId, sessionId) after the first resolution, which removes both the round trip and the TOCTOU.

  • [CRITICAL] agentscope-extensions/agentscope-extensions-redis/src/main/java/io/agentscope/extensions/redis/state/RedisAgentStateKeyLayout.java:118 — Re-verified at this head: still open, and this is the same root cause as @xzxiaoshan's item Do you have any plans to release a JavaScript/TypeScript SDK? #4 plus the hash-tag half that Do you have any plans to release a JavaScript/TypeScript SDK? #4 does not cover. sessionSegment (line 245) and v1 (line 84) concatenate raw userId/sessionId into the Redis hash tag, while v1KeysPattern (this line, v1KeysPattern) and v0KeysPattern (line 130) concatenate the raw user segment into SCAN glob patterns; the Jedis/Lettuce/Redisson client adapters pass the pattern through unchanged. An id containing *, ?, [ or ] lets listSessionIds match other users' marker keys (tenant-isolation leak in listing), and an id containing {, } or / silently breaks the slot grouping that v1 exists to provide. Smallest fix: escape/encode userId and sessionId before building the segment and the patterns, and decode them in parseV1SessionIdFromKeysKey/parseV0SessionIdKeysKey.


Automated review by github-manager-bot

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

下面整理了表格,统一说明:

待修复问题

大概的代码位置 说明

1 JedisClientAdapter.java:155-169 Cluster 下无 key 的 SCAN 只会落到一个节点上,listSessionIds 会漏掉其他节点上的会话,而且没有任何报错,比直接失败更隐蔽。Jedis 有现成的全节点迭代 API scanIteration(),建议换掉这个循环。Lettuce 和 Redisson 的实现已经覆盖全部 master,不用动。这也是 v1-only 下唯一跨 slot 作用域的方法,修好它跨 slot 面就补齐了。
2 RedisAgentStateStore.java:479-493 这个方法建议直接删掉。全库清除没有用户维度,隔离只有 keyPrefix 一层,多个应用共用一个 Redis 时会互相误伤;Jedis Cluster 上还会漏分片、批量 DEL 跨 slot 报错。它不在 AgentStateStore 接口上,框架内部也没有任何调用,全库清理是一个很危险的行为,如果业务真需要全库清理的业务自己实现更合适。
3 RedisAgentStateStore.java:382-394 这里把 sessionId 的校验异常包进了 RuntimeException,delete() 也是同样写法。但 save/get 路径的布局构造在 try 外面,blank sessionId 抛的是原始 IllegalArgumentException,两边行为不一致。建议把校验挪到 try 之前,和其他方法对齐。
4 RedisAgentStateKeyLayout.java:118-120 userId 是直接拼进 SCAN pattern 的,含 * ? [ 这类字符时会误匹配别的用户的会话。#2579 里有现成的 glob 转义,建议一并移植,顺带对 id 和 prefix 里的花括号加个校验。
5 RedisAgentStateStoreTest.java 单测都是 mock 的,验证 key 拼接没问题,但验证不了 Cluster 上 CROSSSLOT 真的消失。#2579 里有现成的 Testcontainers 集成测试,可以考虑移植或者看什么方式比较合适。如果已经在真实 Cluster 上手动验证过,也可以在 PR 描述里补一句结论。
6 RedisAgentStateKeyLayout.java:63-70 PR 描述里写的是 exists 先查 v1 marker、缺失才回退 v0,代码实际是先查 v0,测试 existsUsesResolvedLegacyLayoutWhenBothMarkersExist 断言的也是 v0 优先。应该是最后一个 commit 改了优先级但描述没跟上,两边需要取齐;如果按 v1-only 方向改,兼容行为这节描述直接重写。
@rudy2steiner 处理一下

下面整理了表格,统一说明:

待修复问题

大概的代码位置 说明

1 JedisClientAdapter.java:155-169 Cluster 下无 key 的 SCAN 只会落到一个节点上,listSessionIds 会漏掉其他节点上的会话,而且没有任何报错,比直接失败更隐蔽。Jedis 有现成的全节点迭代 API scanIteration(),建议换掉这个循环。Lettuce 和 Redisson 的实现已经覆盖全部 master,不用动。这也是 v1-only 下唯一跨 slot 作用域的方法,修好它跨 slot 面就补齐了。
2 RedisAgentStateStore.java:479-493 这个方法建议直接删掉。全库清除没有用户维度,隔离只有 keyPrefix 一层,多个应用共用一个 Redis 时会互相误伤;Jedis Cluster 上还会漏分片、批量 DEL 跨 slot 报错。它不在 AgentStateStore 接口上,框架内部也没有任何调用,全库清理是一个很危险的行为,如果业务真需要全库清理的业务自己实现更合适。
3 RedisAgentStateStore.java:382-394 这里把 sessionId 的校验异常包进了 RuntimeException,delete() 也是同样写法。但 save/get 路径的布局构造在 try 外面,blank sessionId 抛的是原始 IllegalArgumentException,两边行为不一致。建议把校验挪到 try 之前,和其他方法对齐。
4 RedisAgentStateKeyLayout.java:118-120 userId 是直接拼进 SCAN pattern 的,含 * ? [ 这类字符时会误匹配别的用户的会话。#2579 里有现成的 glob 转义,建议一并移植,顺带对 id 和 prefix 里的花括号加个校验。
5 RedisAgentStateStoreTest.java 单测都是 mock 的,验证 key 拼接没问题,但验证不了 Cluster 上 CROSSSLOT 真的消失。#2579 里有现成的 Testcontainers 集成测试,可以考虑移植或者看什么方式比较合适。如果已经在真实 Cluster 上手动验证过,也可以在 PR 描述里补一句结论。
6 RedisAgentStateKeyLayout.java:63-70 PR 描述里写的是 exists 先查 v1 marker、缺失才回退 v0,代码实际是先查 v0,测试 existsUsesResolvedLegacyLayoutWhenBothMarkersExist 断言的也是 v0 优先。应该是最后一个 commit 改了优先级但描述没跟上,两边需要取齐;如果按 v1-only 方向改,兼容行为这节描述直接重写。
@rudy2steiner 处理一下

我晚点看看

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Summary

Delta re-review at e6de9ef3 (previous pass at 65e52f5c, COMMENTED). The redesign in 59ef31b4 + the merge of main resolves both blockers that kept this out of approval since round one:

  • Per-call EXISTS probe / TOCTOU on layout resolution — fixed. Layout is now an explicit, pinned KeyLayoutVersion (resolveKeyLayout is a pure switch, RedisAgentStateStore.java:485); no probing, no race, and the operator escape hatch I asked for exists as builder().keyLayoutVersion(V1) + the RedisDistributedStore.fromJedis(...) overload.
  • Unsanitized userId/sessionId inside the hash tag and glob patterns — fixed. validateV1KeyPrefix/validateV1UserId/validateV1SessionId reject {, } and /, and escapeRedisGlobLiteral makes SCAN MATCH treat ids literally.
  • The Redisson-only eval gap in my previous round is moot now that the layout is pinned per store instance.

This also lands the requested real-cluster coverage (3-master testcontainers test, Docker- and port-gated) and a genuinely thorough V0→V1 migration runbook in both docs. Cross-checking @xzxiaoshan's list: #1 scanIteration ✅, #3 validation-exception consistency ✅ (resolveKeyLayout sits outside the try in both exists() and delete()), #4 glob escape + brace validation ✅, #5 integration test ✅, #6 description/behaviour mismatch ✅ (rewritten around explicit layout); #2 (clearAllSessions) is the one item still open, see inline.

Remaining notes are one scope item, one runner-robustness item, one behavioural divergence worth pinning, and #2 above — none of them is a data-loss path.

Findings

  • [Warning] pr.md:1 — PR description committed to the repo root; the .gitignore hunk is also unrelated to this change.
  • [Warning] RedisAgentStateClusterIntegrationTest.java:97 — post-container.start() failures rethrow and error the class instead of skipping; on shared runners that becomes recurring CI noise.
  • [Warning] RedisAgentStateStore.java:487 — V1's id restrictions are not symmetric with V0 (/ in ids is ambiguous under V0); document + test the divergence.
  • [Info] RedisAgentStateStore.java:507 — clearAllSessions() still present after the maintainer asked for removal.

CI at this head is green (build ubuntu + windows, validate, Check License, Check Module Sync, codecov). license/cla reports no status context on this head, so I am leaving this as a comment rather than an approval — the merge decision is the maintainer's, and this is very close.


Automated review by github-manager-bot

Inline notes

The review draft from the previous round is still pending on this PR, so GitHub would not accept a second review object; these notes are posted here instead of as line comments.

[1] WARNING — pr.md:1

[Warning] This file is the PR description pasted into the repository root and looks like a local working artifact rather than a deliverable — nothing in the repo references it, and its content duplicates the PR body. Please drop it from the branch. The .gitignore addition in the same push (ignoring the generated agentscope-copilotkit static bundle) is also unrelated to the Redis key layout; it is harmless but would be cleaner as its own commit or PR so this one stays scoped.

[2] WARNING — agentscope-extensions/agentscope-extensions-redis/src/test/java/io/agentscope/extensions/redis/state/RedisAgentStateClusterIntegrationTest.java:97

[Warning] The environment gate is only as forgiving as its pre-checks. preStartSkipReason is set for "Docker unavailable" and "fixed port already in use", but anything that fails after container.start() is entered — image pull rate limit, boot script error, the 90s Wait.forListeningPorts timeout, awaitClusterReady() giving up — is rethrown (catch (Throwable failure) { ...; throw failure; }), which errors the whole class instead of skipping it. On a shared runner with a pinned host port (17000-17002 by default) that turns infra flakiness into a red build (windows-latest)/build (ubuntu-latest) that the author cannot fix from the branch. Suggested shape: set preStartSkipReason = "cluster unavailable: " + failure and return instead of rethrowing, reserving hard failure for assertion errors inside the @Test bodies.

[3] WARNING — agentscope-extensions/agentscope-extensions-redis/src/main/java/io/agentscope/extensions/redis/state/RedisAgentStateStore.java:487

[Warning] resolveKeyLayout is now a pure switch — the per-call EXISTS probe and its TOCTOU window are gone, and the {/}// rejection plus glob escaping closes the slot-splitting hole. Both of my long-standing blockers are resolved; this is the right design.

One consequence worth deciding on purpose: under V0 the restrictions do not apply, so a userId/sessionId containing / still produces ambiguous marker keys (p:user/a/b:_keys) that parseV0SessionIdFromKeysKey cannot split back into (user, session), and listSessionIds will hand back a session id that no longer round-trips through save/get. V1 fixes it by rejecting such ids, which means the same application data can work under V1 and be silently corrupt under V0 — i.e. a V0→V1 migration can change which ids are legal, not just where keys live. Could you (a) add a note to the migration doc step 1 saying ids rejected by V1 must be resolved before cutover because they were never unambiguous under V0, and (b) add one unit test with a userId containing / under each layout, so the divergence is pinned rather than discovered in production?

[4] INFO — agentscope-extensions/agentscope-extensions-redis/src/main/java/io/agentscope/extensions/redis/state/RedisAgentStateStore.java:507

[Info] clearAllSessions() is still on the class after @xzxiaoshan explicitly suggested deleting it (no user dimension, keyPrefix is the only isolation boundary, no framework caller, and now the English doc actively recommends it must not be used for V0 cleanup). The change here makes it cluster-safe (one DEL per key) but does not address the original objection. If the answer is "keep it for tests/ops", the two @Deprecated words would at least stop new deployments from discovering it; otherwise please remove it in this PR so item 2 of the maintainer list can be closed.

@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

Redis Cluster hash-slot fix for RedisAgentStateStore: the V1 layout puts a hash tag on every key touched by the Lua CAS script (state, version, index), exists / delete / listSessionIds resolve through the same layout, and the Jedis adapter now iterates all cluster masters instead of scanning a single node. The previous round's findings on delete(), exists() and the class javadoc are addressed. Not blocking on correctness — three items below, one of which should be fixed before merge. CLA note: no license/cla status context was found on head e6de9ef, please confirm the signed CLA is attached to this PR's commits.

Findings

  • [Warning] RedisAgentStateStore.java:506 — clearAllSessions() is still an unscoped keyPrefix + "*" delete: it wipes V0 and V1 keys for every user behind that prefix, and now does it one key at a time.
  • [Warning] pr.md — the PR description was committed to the repository root; it is not referenced by the build or the docs.
  • [Info] listSessionIds — V1 user-id validation throws a raw IllegalArgumentException outside the try block while every other method wraps failures; standardise the wrapping.

Suggestions

  • Either drop clearAllSessions() or mark it test-only (and scope it to one layout / one user) — as written it is a data-loss button in production.
  • Remove pr.md; the PR body already carries that content.
  • Migration is documented as manual with no V0 dual-read, which is a legitimate choice — but it means an upgrade silently starts a new state namespace. Worth calling out in the release notes, not only in the store javadoc.

Automated review by github-manager-bot

Set<String> keys = client.findKeysByPattern(keyPrefix + "*");
if (!keys.isEmpty()) {
client.deleteKeys(keys.toArray(new String[0]));
for (String key : keys) {

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.

[WARNING] clearAllSessions() remains a global, user-unscoped delete that matches every key under keyPrefix + "*" and now deletes one key at a time. It will remove both V0 and V1 keys for every user/session sharing the prefix, making it dangerous for production and unsuitable for the documented selective V0 cleanup. Consider removing it or restricting it to a test-only utility as suggested by prior review feedback.

Comment thread pr.md Outdated
@@ -0,0 +1,30 @@
## Background

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.

[WARNING] A pr.md file has been added at the repository root. It appears to be a copy of the PR description rather than project documentation, and is not referenced by the build or docs. Remove it before merge to avoid cluttering the repo root.

return sessionIds;
} catch (Exception e) {
throw new RuntimeException("Failed to list sessions", e);
}

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.

[INFO] In listSessionIds, the V1 user-id validation is performed outside the try block, so an invalid user id throws a raw IllegalArgumentException instead of the RuntimeException wrapper used by save, get, exists, and delete. Move the validation inside the try block or standardize the wrapping so the method's failure mode is consistent with the rest of the store.

@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-reviewed the delta since e6de9ef — one commit, 00752a68 ("clean clear all sessions of RedisAgentStateStore"). Both pre-merge items from my previous round are resolved, and resolved in the strongest way available:

  • clearAllSessions() removed outright rather than scoped or annotated as test-only. RedisAgentStateStore.java no longer issues a keyPrefix + "*" pattern delete, and the Mono/Schedulers imports that only that method needed are gone with it, so there is no leftover prefix-wide data-loss button on the V0/V1 migration path. The matching test (clearAllSessionsDeletesClusterKeysIndividually) was deleted in the same commit, and assertSingleKeyDeletes is still used by the two remaining delete() tests — no orphaned helper.
  • pr.md deleted, along with the two .gitignore lines that had been added to hide it.
  • The en/zh migration runbook (step 9) now warns against prefix-wide cleanup generically instead of naming a method that no longer exists, which keeps the documented procedure honest after the deletion.

The hash-slot core of the PR is unchanged by this commit, and the cluster/CAS coverage added earlier (RedisAgentStateKeyLayout, RedisAgentStateClusterIntegrationTest) still covers it. Approved — CI is 6/6 completed/success on head 00752a68 with license/cla: success; the PR sits MERGEABLE / blocked only on branch protection, i.e. it needs a maintainer merge, which I will not do.

Notes

  • [Info] RedisAgentStateStore.java:456 — validateV1UserId still runs outside the try, so a bad V1 user id surfaces as a raw IllegalArgumentException while every other failure in the class is wrapped. Cosmetic, not a blocker, and I did not ask for it to change here.
  • Out of scope but worth tracking: the same prefix-wide pattern delete still exists on the two sibling stores in this module — JedisAgentStateStore.java:349 (jedis.keys(keyPrefix + "*")) and RedissonAgentStateStore.java:334 (getKeysByPattern(keyPrefix + "*")) — plus JsonFileAgentStateStore and MysqlAgentStateStore. Removing only the Redis one fixes this PR's path; a follow-up that removes or scopes the rest is the real close-out, and it belongs in its own PR rather than tacked onto this one.

Automated review by github-manager-bot

String userSegment = normalizeUser(userId);
String userSegment = RedisAgentStateKeyLayout.normalizeUser(userId);
if (keyLayoutVersion == KeyLayoutVersion.V1) {
RedisAgentStateKeyLayout.validateV1UserId(userSegment);

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.

Carry-over from the last round, non-blocking: validateV1UserId is still called outside the try, so a malformed V1 user id escapes as a raw IllegalArgumentException while every other failure in this class is wrapped in RuntimeException("Failed to ..."). Moving it inside the block (or wrapping it) would make the error surface uniform for callers.

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

@xzxiaoshan help me review again when you have time

@xzxiaoshan
xzxiaoshan merged commit 48f7257 into agentscope-ai:main Oct 10, 2026
7 checks passed
@jujn jujn added the 2.0.5 label Oct 10, 2026
helloworldtang pushed a commit to helloworldtang/agentscope-java that referenced this pull request Oct 10, 2026
Brings in agentscope-ai#2697 (structured-output fallback determinism) and agentscope-ai#3129.

Conflict resolution: ReActAgentStructuredOutputTest.java — both sides
appended test suites at the end of the class (ours: prose/guard/
unknown-domain/retry-prompt; agentscope-ai#2697's: tool_choice forcing and
request-local reminder tests) plus overlapping imports. Kept both
suites and both import sets; closed the MathAnswer helper before the
incoming tests.

Semantic integration check (auto-merged ReActAgent.java): the two
retry mechanisms are disjoint by guard conditions — native path runs
this PR's validation retry (nativeResponseFormat != null, soTool ==
null), fallback path runs agentscope-ai#2697's forced-retry loop (soTool != null);
isNonDegradableFailure and the extraction seam are intact. Verified by
the focused structured-output suite: 48 tests green including both
sides' cases.
helloworldtang pushed a commit to helloworldtang/agentscope-java that referenced this pull request Oct 11, 2026
Brings main (incl. agentscope-ai#2697, agentscope-ai#3324, agentscope-ai#2751, agentscope-ai#3129) into the branch. Only
conflict: ReActAgentStructuredOutputTest.java — this branch's added test
(testToolBasedExtractionPreservesMessageIdentity) sat exactly where
agentscope-ai#2697 later appended its new tests; kept both sides (our test plus the
incoming suite) and both import sets. ReActAgent.java auto-merged.

Verified: ReActAgentStructuredOutputTest 16 tests green including both
this branch's identity test and the merged-in tests.
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified fix to the 2.0.x implementation and retain its
existing public contracts where the upstream kernel differs.

(cherry picked from commit 48f7257)
Constraint: No AgentScope Service or SDK migration
Confidence: high
Not-tested: Whole-repository verification pending after lane integration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants