Skip to content

fix(redis): add Redis Cluster support for AgentStateStore - #2587

Open
amyaxy wants to merge 1 commit into
agentscope-ai:mainfrom
amyaxy:fix/2579_agentStateStore-support-for-redis-cluster
Open

amyaxy wants to merge 1 commit into
agentscope-ai:mainfrom
amyaxy:fix/2579_agentStateStore-support-for-redis-cluster

Conversation

@amyaxy

@amyaxy amyaxy commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Description

close #2579

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

@amyaxy amyaxy changed the title fix(redis): add Redis Cluster support for AgentStateStore and RedisSt… fix(redis): add Redis Cluster support for AgentStateStore Aug 6, 2026
@codecov

codecov Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

@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 modifies 12 files with 1160 lines of diff.

Observations

  • Files changed: 12
  • Test coverage: ✅ Tests included
  • CLA: ✅ Signed

Suggestions

  • Please ensure all public API changes are backward compatible
  • Consider adding unit tests for new logic paths

Automated review by github-manager-bot

@amyaxy

amyaxy commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@zouyx 麻烦审核一下,谢谢

@amyaxy
amyaxy requested review from oss-maintainer and zouyx August 9, 2026 09:48
@zouyx

zouyx commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

@zouyx 麻烦审核一下,谢谢

这个变更有点多,需要点时间

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/build Build, CI, BOM, distribution area/core/memory Memory, session, state area/extensions agentscope-extensions (general) labels Aug 11, 2026
@amyaxy
amyaxy force-pushed the fix/2579_agentStateStore-support-for-redis-cluster branch 4 times, most recently from e6e47fc to e1bbb79 Compare September 12, 2026 14:17

@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 on the current head e1bbb798. My previous pass on this PR was on 4bd16042 and was a shallow auto-summary, not a real review; the branch has been squashed and reworked since, so this is a full review of the PR as it stands.

The design is sound and the reasoning behind it is careful: one hash tag per session ({user/session}) so every multi-key EVAL stays inside a single slot, append guarded on hash and length with an atomic rewrite fallback, MGET for the versioned read, per-master SCAN fan-out replacing the old single-node scan (a real cluster bug), an already-configured-client guard on the builder, and a per-key delete() override so the interface default is no longer a silent no-op. Test coverage is unusually good for a change of this size.

My findings are mostly about what happens around the change rather than inside it:

  • 1 Critical — a duplicate testcontainers.version in agentscope-dependencies-bom/pom.xml: that property decides the managed Testcontainers version for the whole reactor, and it now exists twice (1.21.4 at line 76, 2.0.5 at line 104) while mongodb/jdbc pin their own.
  • 5 Warnings — the un-tagged → tagged key layout lands as silent data loss with no migration path; clearAllSessions() can no longer reach untracked or legacy-layout keys; mget's non-atomic default quietly keeps the torn-read bug for custom adapters; validateScopeId rejects / and , in ids that work today; and the cluster integration test — the only thing that can prove the CROSSSLOT and multi-shard SCAN claims — is silently skipped in CI on both runners (verified in the run log).
  • 1 Warning on the shared core helper — removing sampling is right, but the list is now serialized 2-3 times per save for every AgentStateStore implementation that shares ListHashUtil, and it is still collapsed to 32 bits.

Not converting to an approval while the duplicate-property and migration questions are open: the first is a one-line fix, the second decides whether this can ship on a patch line. Inline comments carry the details and suggested shapes.

CI: all checks passing on e1bbb798 (License, Module Sync, ubuntu + windows builds, codecov, CLA signed). mergeable: MERGEABLE, no conflicts.


Automated review by github-manager-bot

Comment thread agentscope-dependencies-bom/pom.xml Outdated
<a2a-transport-jsonrpc.version>0.3.3.Final</a2a-transport-jsonrpc.version>
<jedis.version>7.4.1</jedis.version>
<lettuce.version>6.4.2.RELEASE</lettuce.version>
<testcontainers.version>2.0.5</testcontainers.version>

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] This adds a second testcontainers.version declaration: line 76 of the same <properties> block already has <testcontainers.version>1.21.4</testcontainers.version>, and testcontainers-bom is imported via ${testcontainers.version} (line 205-208). Whichever duplicate the model builder keeps, the managed Testcontainers line for every module inheriting this BOM is now ambiguous — and if the new value wins, every module inheriting the BOM takes a silent 1.21.x → 2.0.5 major jump in one commit. Meanwhile agentscope-extensions-mongodb pins 1.21.4 literally on testcontainers:mongodb / testcontainers:junit-jupiter, and agentscope-extensions-jdbc declares its own 1.21.3 property, so the reactor ends up with three different Testcontainers versions depending on this file.

If the goal is only to get GenericContainer + Wait into this module's tests, delete this line and let the redis module inherit 1.21.4 from the BOM. If 2.x really is required here, bump the existing property at line 76 (in a dedicated commit) and align mongodb/jdbc in the same change, so there is exactly one declaration of the managed version.

* <li>AgentStateStore marker: {@code <prefix>{<user>/<session>}:_keys} - Redis Set tracking all state keys
* </ul>
*
* <p><strong>Breaking change:</strong> the slot id is wrapped in a Redis Cluster hash tag

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 hash-tag layout is the right design for Cluster, but "must be migrated" is written without a migration path, and for a state store the failure mode is silent data loss rather than an error: every key is derived from slotId(...), so after an upgrade get/getList/exists on pre-upgrade sessions just return empty — the agent resumes with a blank transcript and nothing tells the operator why. RedisStore (its "Breaking change" note, ~line 52) has the same shape.

Could one of these ship with the PR?

  • a migration snippet (batch SCAN keyPrefix* → read :list / :_hash / :ver companions → write under the tagged key) in the module README or a small main() tool;
  • or a legacy read fallback (tagged key first, then un-tagged, rewrite on hit);
  • or at least a startup ERROR log when un-tagged keys are detected under keyPrefix.

Worth stating explicitly which companions move with the payload (:_hash, :ver, the :_keys member names, which change from key/key:list-relative to the tagged slot), since a partial copy leaves a session readable but with a stale list hash.

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

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] Narrowing the sweep from keyPrefix + "*" to keyPrefix + "*" + KEYS_SUFFIX makes the marker-driven CLEAR_SESSION_SCRIPT correct, but it also means anything not reachable from a live _keys set can never be deleted through this class:

  • every pre-upgrade un-tagged key (which the new slotId cannot address any more) — so the leftover data from the migration above is not even cleanable via clearAllSessions();
  • orphans from a partial write (crash after RPUSH/SET but before the SADD that registers the member), and
  • _keys sets deleted out of band while their payload keys survive.

clearAllSessions() is documented as "for testing or cleanup"; for both uses the contract just got weaker than callers expect (tests that flush the prefix between runs will leak, and operators reading the javadoc will assume the prefix is emptied).

Suggested: keep this path as the default, and add an explicit opt-in for the full sweep — e.g. clearAllSessions(boolean includeUntracked) that additionally SCAN keyPrefix* → UNLINK in batches — or at minimum document in the javadoc that untracked and legacy-layout keys are not removed by this call.

* does not exist
* @since 2.0.4
*/
default List<String> mget(String... 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] getVersioned now depends on this being one atomic MGET to close the torn (payload, version-counter) read — but RedisClientAdapter is a public extension point (Builder.clientAdapter(...), used by callers who bring their own client wrapper), and this default implementation is two sequential get() calls. A custom adapter that does not override it keeps exactly the race the change is meant to remove, with no compile error and no runtime signal: it will pass single-threaded tests and pair a payload with a counter written by a different thread.

The javadoc says implementations "should" override; since CAS reads now rest on it, I'd make the requirement non-optional. Practical options:

  • make mget abstract (breaking, but the interface is @since-versioned and the three in-tree adapters all implement it anyway);
  • or keep the default and add a default boolean supportsAtomicMget() { return false; } marker so RedisAgentStateStore can log a one-time WARN at build time (and getVersioned can fall back to a single-key EVAL/MULTI read for those adapters).

throw new IllegalArgumentException("sessionId must not be blank");
}
return normalizeUser(userId) + "/" + sessionId;
validateScopeId(sessionId, "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] Two over-rejections here that turn previously-working ids into runtime exceptions:

  1. / in sessionId is not needed. / must be banned in userId, because listSessionIds("a") would otherwise match {a/b/sess}:_keys and hand back sessions belonging to user a/b. But sessionId cannot cause that confusion: listSessionIds strips the fixed keyPrefix + "{" + userSegment + "/" prefix and the "}" + KEYS_SUFFIX tail, so a sessionId of agent1/run42 round-trips correctly and matches nothing outside its own user segment. Composite session ids (<agent>/<run>, path-derived ids, tenant:ws/thread-7) work today against this store; after this change every read and write for them throws IllegalArgumentException — a hard regression on live data, on top of the key-layout break.
  2. , is not a glob character for Redis. Redis's SCAN/KEYS matcher (stringmatchlen) implements *, ?, [...]/[^...]/[a-b] and \ escapes — there is no {a,b} alternation, so a comma inside a pattern is literal and cannot "parse as a glob set" as the javadoc above states. (The {...} alternation people remember is from the hash-tag slot optimization docs, which is about routing, not matching.) Banning , only shrinks the set of usable user ids.

Suggested shape: ban { } on both segments (they really do terminate the tag early) and ban * ? [ ] \ on the userId segment only (that is the segment embedded in the MATCH pattern); allow / and , in sessionId. Adding two tests — slotId("u", "a/b") succeeds and listSessionIds("u") returns "a/b", plus listSessionIds("a,b") returning the right set — would pin the intended rule. If you keep the stricter rule instead, please call it out as a documented breaking change for existing session ids, not just an internal validation note.

.build();
redisStore = new RedisStore(jedisCluster, "agentscope:store:");
} catch (Throwable t) {
System.err.println("=== RedisClusterIntegrationTest skipped due to: ===");

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] Checked against this PR's own CI run rather than assumed — build (ubuntu-latest) job 103566953951:

=== RedisClusterIntegrationTest skipped due to: ===
org.testcontainers.containers.ContainerLaunchException: Container startup failed for image redis:7-alpine
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, ... in io.agentscope.extensions.redis.RedisClusterIntegrationTest

and build (windows-latest) skips with Could not find a valid Docker environment. So both cluster-only behaviours this class exists to prove — no CROSSSLOT on the multi-key EVALs, and SCAN reaching every master — are currently not covered by CI, and the green checks are not evidence that the cluster path works. The remaining tests in this PR (LettuceClientAdapterClusterScanTest, JedisClientAdapterClusterScanTest) mock the client, so a topology/MOVED regression here would be invisible.

Two asks:

  1. Make the skip loud: emit an ERROR-level marker and/or fail when an env flag such as REQUIRE_CLUSTER_IT=1 is set, then run one CI job with that flag so a passing run is distinguishable from a skipped one.
  2. Note the ubuntu failure is a container startup failure, not "Docker missing" — the hard-pinned host bindings on 7000-7005 are the usual suspect on shared runners (any process or parallel job holding those ports breaks it). Letting Testcontainers pick random host ports and building the seed URIs from the mapped ports would make the job stable enough to require.

State item = values.get(idx);
int itemHash = item != null ? item.hashCode() : 0;
sb.append(idx).append(":").append(itemHash).append(",");
String json = item != null ? JsonUtils.getJsonCodec().toJson(item) : "null";

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] Dropping sampling is the correct fix — a sampled hash genuinely cannot prove that a non-sampled index is unchanged, and the stale-data consequence is worse than the cost. But the cost is now paid 2-3 times per save, in every store, on the hottest write path: for one save(userId, sessionId, key, List) in RedisAgentStateStore,

  1. ListHashUtil.computeHash(values) serializes all elements to JSON (this line);
  2. ListHashUtil.needsFullRewrite(values, storedHash, existingCount) then calls computeHash(values.subList(0, existingCount)) → the stored prefix is serialized a second time (this method was not touched, so JdbcAgentStateStore, Mysql/PostgresAgentStateStore, MongoAgentStateStore, Oss/CosAgentStateStore, JsonFileAgentStateStore and JedisAgentStateStore all inherit the same multiplication);
  3. buildListSaveArgs(...) serializes all elements again to build the RPUSH arguments.

For a long-running agent transcript (hundreds to thousands of blocks per turn) that is roughly 3x the JSON work per save, plus a single StringBuilder holding the whole serialized list before it is collapsed into Integer.toHexString(sb.toString().hashCode()) — still a 32-bit digest, which is the same truncation that made sampling weak; a collision silently reuses a stale list.

A cheap restructure that keeps the semantics: serialize once. Have the store build List<String> json first, hash it with a streaming MessageDigest (update(idx), update(':'), update(json_i), update(',')) so nothing is materialized as one big string and the digest is 128+ bits, and pass the same List<String> into the Lua args. Add a computeHashOfSerialized(List<String>) overload so existing computeHash(List<? extends State>) callers stay source-compatible.

@amyaxy
amyaxy force-pushed the fix/2579_agentStateStore-support-for-redis-cluster branch from e1bbb79 to 708b6d1 Compare October 8, 2026 10:18
amyaxy added a commit to amyaxy/agentscope-java that referenced this pull request Oct 8, 2026
close agentscope-ai#2579

- Bind session/namespace keys to the same slot via hash tags to avoid
  CROSSSLOT errors on multi-key EVAL in cluster mode
- Fix cross-node SCAN for Jedis (scanIteration) and Lettuce (iterate all
  master nodes) so listSessionIds/clearAllSessions no longer miss shards
- Escape glob metacharacters in listSessionIds userId
- Document key-layout breaking change in class Javadoc
- Make the integration test portable (single container + fixed port
  bindings) so it runs on Windows/macOS/Linux
- Add testcontainers dependency; add unit + integration tests (22 cases pass)

Address review feedback on PR agentscope-ai#2587:

- core: replace ListHashUtil's 32-bit String.hashCode() digest with a
  streamed SHA-256 (64-char hex) so distinct list contents can no longer
  collide on the short digest; delegating overloads stay source-compatible
- redis(state): validate user/session id segments before embedding them
  in cluster hash tags, rejecting glob metacharacters instead of reading
  from a wrong slot
- redis(state): read payload+version as one consistent pair in
  getVersioned - a single atomic MGET when the adapter supports it,
  otherwise a verified re-read with a bounded retry budget that fails
  loudly instead of returning a mismatched pair
- redis(state): clearAllSessions gains includeUntracked, a cluster-safe
  one-by-one sweep for orphaned, marker-less and legacy-layout keys
- redis: add RedisKeyLayoutMigration (dry-run report, per-key
  cluster-safe copy, skip/orphan reporting); store constructors detect
  legacy pre-hash-tag keys at startup and warn with a pointer to the
  tool; javadoc documents the upgrade procedure
- test: cluster IT honors REQUIRE_CLUSTER_IT (hard failure instead of a
  silent skip), supports CLUSTER_BASE_PORT override and port-segment
  retries; add a dedicated redis-cluster-it CI job; cover the migration
  tool and verified reads with unit tests
- build: drop the stray testcontainers.version property from the
  dependencies BOM
amyaxy added a commit to amyaxy/agentscope-java that referenced this pull request Oct 8, 2026
close agentscope-ai#2579

- Bind session/namespace keys to the same slot via hash tags to avoid
  CROSSSLOT errors on multi-key EVAL in cluster mode
- Fix cross-node SCAN for Jedis (scanIteration) and Lettuce (iterate all
  master nodes) so listSessionIds/clearAllSessions no longer miss shards
- Escape glob metacharacters in listSessionIds userId
- Document key-layout breaking change in class Javadoc
- Make the integration test portable (single container + fixed port
  bindings) so it runs on Windows/macOS/Linux
- Add testcontainers dependency; add unit + integration tests (22 cases pass)

Address review feedback on PR agentscope-ai#2587:

- core: replace ListHashUtil's 32-bit String.hashCode() digest with a
  streamed SHA-256 (64-char hex) so distinct list contents can no longer
  collide on the short digest; delegating overloads stay source-compatible
- redis(state): validate user/session id segments before embedding them
  in cluster hash tags, rejecting glob metacharacters instead of reading
  from a wrong slot
- redis(state): read payload+version as one consistent pair in
  getVersioned - a single atomic MGET when the adapter supports it,
  otherwise a verified re-read with a bounded retry budget that fails
  loudly instead of returning a mismatched pair
- redis(state): clearAllSessions gains includeUntracked, a cluster-safe
  one-by-one sweep for orphaned, marker-less and legacy-layout keys
- redis: add RedisKeyLayoutMigration (dry-run report, per-key
  cluster-safe copy, skip/orphan reporting); store constructors detect
  legacy pre-hash-tag keys at startup and warn with a pointer to the
  tool; javadoc documents the upgrade procedure
- test: cluster IT honors REQUIRE_CLUSTER_IT (hard failure instead of a
  silent skip), supports CLUSTER_BASE_PORT override and port-segment
  retries; add a dedicated redis-cluster-it CI job; cover the migration
  tool and verified reads with unit tests
- build: drop the stray testcontainers.version property from the
  dependencies BOM
@amyaxy
amyaxy force-pushed the fix/2579_agentStateStore-support-for-redis-cluster branch from 708b6d1 to 63fca52 Compare October 8, 2026 11:15
close agentscope-ai#2579

- Bind session/namespace keys to the same slot via hash tags to avoid
  CROSSSLOT errors on multi-key EVAL in cluster mode
- Fix cross-node SCAN for Jedis (scanIteration) and Lettuce (iterate all
  master nodes) so listSessionIds/clearAllSessions no longer miss shards
- Escape glob metacharacters in listSessionIds userId
- Document key-layout breaking change in class Javadoc
- Make the integration test portable (single container + fixed port
  bindings) so it runs on Windows/macOS/Linux
- Add testcontainers dependency; add unit + integration tests (22 cases pass)

Address review feedback on PR agentscope-ai#2587:

- core: replace ListHashUtil's 32-bit String.hashCode() digest with a
  streamed SHA-256 (64-char hex) so distinct list contents can no longer
  collide on the short digest; delegating overloads stay source-compatible
- redis(state): validate user/session id segments before embedding them
  in cluster hash tags, rejecting glob metacharacters instead of reading
  from a wrong slot
- redis(state): read payload+version as one consistent pair in
  getVersioned - a single atomic MGET when the adapter supports it,
  otherwise a verified re-read with a bounded retry budget that fails
  loudly instead of returning a mismatched pair
- redis(state): clearAllSessions gains includeUntracked, a cluster-safe
  one-by-one sweep for orphaned, marker-less and legacy-layout keys
- redis: add RedisKeyLayoutMigration (dry-run report, per-key
  cluster-safe copy, skip/orphan reporting); store constructors detect
  legacy pre-hash-tag keys at startup and warn with a pointer to the
  tool; javadoc documents the upgrade procedure
- test: cluster IT honors REQUIRE_CLUSTER_IT (hard failure instead of a
  silent skip), supports CLUSTER_BASE_PORT override and port-segment
  retries; add a dedicated redis-cluster-it CI job; cover the migration
  tool and verified reads with unit tests
- build: drop the stray testcontainers.version property from the
  dependencies BOM
@amyaxy
amyaxy force-pushed the fix/2579_agentStateStore-support-for-redis-cluster branch from 63fca52 to 4efae85 Compare October 8, 2026 15:22

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/build Build, CI, BOM, distribution area/core/memory Memory, session, state area/extensions agentscope-extensions (general) bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: agentStateStore does not support Redis Cluster.

4 participants