Repository navigation
fix(agent): agent state redis key without same hashslot - #3129
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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:_keysmarker, soresolve()afterwards returns v0 for a session whose versioned state lives under v1: reads silently return empty, the next write duplicates the key, anddelete()orphans the v1 keys. Layout depends on write order. - [Warning]
RedisAgentStateKeyLayout.java:65—EXISTSprobe 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— rawuserId/sessionIdinterpolated into a hash tag andKEYSglob patterns ({},*,?,[,/) corrupt slot assignment and parsing. - [Warning]
RedisAgentStateStore.java:441— cluster-safety is incomplete for the multi-keydeleteKeys(...)indelete()/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/clastatus 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); |
There was a problem hiding this comment.
[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:
save(userId, sessionId, "state", value)-> no v0 marker -> v1 layout; state +:ver+ v1:_keyswritten underprefix{{user}/{sess}}:....save(userId, sessionId, "items", list)-> writes v0 list keys and creates the v0:_keysmarker.- Any later
get(...)/getVersioned(...)/saveIfVersion(...)now resolves to v0 and readsprefix{user}/{sess}:state, which does not exist -> the state written in step 1 silently disappears (empty Optional / version reset), and the followingsaveoverwrites under a different key. delete(...)also resolves to v0 afterwards, so the v1state/ver/_keyskeys 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())) { |
There was a problem hiding this comment.
[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
EXISTSon every call. - Race: two threads writing the same brand-new session can both observe
keyExists == falseand pick v1 (fine), but a thread that runs after the v0 marker first appears will switch layouts mid-flight — see the interleaving problem flagged onRedisAgentStateStore.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); |
There was a problem hiding this comment.
[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( |
There was a problem hiding this comment.
[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/sessionIdcontaining{,}or*/?/[moves or breaks the hash tag and the glob match (keys could land in the wrong slot, orlistSessionIdssilently returns nothing); - a
sessionIdcontaining/is mis-parsed byparseV0SessionIdKeysKey/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); |
There was a problem hiding this comment.
[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()); | |||
There was a problem hiding this comment.
[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; | ||
|
|
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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, which330ead5fmade 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. |
There was a problem hiding this comment.
[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)) { |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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()); | ||
|
|
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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)usedv0KeyLayout, flipping an existing v1 session back to v0. Fixed in the current head;save(userId, sessionId, key, List)now callsresolveKeyLayout()and the new testlistSaveDoesNotMoveExistingClusterSafeSessionBackToLegacyLayoutguards it. - [Warning]
RedisAgentStateKeyLayout.resolve()adds an extraEXISTSround 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/sessionIdinterpolated raw into the hash tag and intoKEYS/glob patterns (wildcard injection / cross-session key collision risk). Still open. - [Warning]
exists()probes v1-first whileresolve()may pick v0 — inconsistent precedence. Still open. - [Info] Class javadoc of
RedisAgentStateStorestill 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 extraEXISTSround 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 theresolve()race or a partial migration), keys from the other layout leak forever. Delete both layouts, or ensureresolve()can never produce a mixed-layout session. - [WARNING]
RedisAgentStateKeyLayout.java:248—sessionSegment()(line 248) interpolatesuserIdandsessionIdliterally into Redis keys, hash tags, and SCAN patterns without escaping. AsessionIdsuch ass*1turnsv1KeysPattern()intoprefix{user/s*1}:_keysand matches unrelated sessions;}or{inuserId/sessionIdbreaks 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), whileresolveKeyLayout()(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), butsave(userId, sessionId, key, List)now callsresolveKeyLayout()(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—newSessionSaveUsesOneHashSlotForLuaKeysasserts that Lua keys contain the string"{user/s1}"(viaassertClusterSafeSessionKeys), but string containment does not prove the keys share the same Redis Cluster hash slot. Add a hash-slot assertion (e.g., usingJedisClusterCRC16.getSlot) over the captured Lua keys, or an integration test against a real cluster. - [INFO]
RedisAgentStateStoreTest.java:257—deleteSessionUsesLegacyLayoutWhenOnlyLegacyMarkerExistscovers 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 thatdelete()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())) { |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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; |
There was a problem hiding this comment.
[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)) { |
There was a problem hiding this comment.
[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. |
There was a problem hiding this comment.
[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() { |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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.
|
@xzxiaoshan PTAL Thanks. |
|
下面整理了表格,统一说明: 待修复问题
@rudy2steiner 处理一下 |
SummaryRe-check at the same head What still blocks the approval (both pinned inline)
Note on @xzxiaoshan item #6 (description vs code precedence)From my earlier pass the code side is consistent: Not verified by meItems #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 forwardPush the fixes for the two inline items together with the maintainer list and ping me - I will review only the delta against Inline notes (anchored to this head)
Automated review by github-manager-bot |
我晚点看看 |
SummaryDelta re-review at
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 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
CI at this head is green (build ubuntu + windows, validate, Check License, Check Module Sync, codecov). Automated review by github-manager-bot Inline notesThe 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 — [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 [2] WARNING — [Warning] The environment gate is only as forgiving as its pre-checks. [3] WARNING — [Warning] One consequence worth deciding on purpose: under V0 the restrictions do not apply, so a [4] INFO — [Info] |
oss-maintainer
left a comment
There was a problem hiding this comment.
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 unscopedkeyPrefix + "*"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 rawIllegalArgumentExceptionoutside thetryblock 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) { |
There was a problem hiding this comment.
[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.
| @@ -0,0 +1,30 @@ | |||
| ## Background | |||
There was a problem hiding this comment.
[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); | ||
| } |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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.javano longer issues akeyPrefix + "*"pattern delete, and theMono/Schedulersimports 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, andassertSingleKeyDeletesis still used by the two remainingdelete()tests — no orphaned helper.pr.mddeleted, along with the two.gitignorelines 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—validateV1UserIdstill runs outside thetry, so a bad V1 user id surfaces as a rawIllegalArgumentExceptionwhile 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 + "*")) andRedissonAgentStateStore.java:334(getKeysByPattern(keyPrefix + "*")) — plusJsonFileAgentStateStoreandMysqlAgentStateStore. 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); |
There was a problem hiding this comment.
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.
|
@xzxiaoshan help me review again when you have time |
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.
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.
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
Background
RedisAgentStateStoreuses 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_stateagentscope:session:userId/sessionId:agent_state:veragentscope:session:userId/sessionId:_keysRedis 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
agentscope:session:userId/sessionId:agent_stateagentscope:session:{userId/sessionId}:agent_stateexists,delete, andlistSessionIds.RedisDistributedStore.fromJedis(...)overload that accepts the key layout version.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.