Repository navigation
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
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
|
@zouyx 麻烦审核一下,谢谢 |
这个变更有点多,需要点时间 |
e6e47fc to
e1bbb79
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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.versioninagentscope-dependencies-bom/pom.xml: that property decides the managed Testcontainers version for the whole reactor, and it now exists twice (1.21.4at line 76,2.0.5at 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-atomicdefaultquietly keeps the torn-read bug for custom adapters;validateScopeIdrejects/and,in ids that work today; and the cluster integration test — the only thing that can prove theCROSSSLOTand multi-shardSCANclaims — 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
AgentStateStoreimplementation that sharesListHashUtil, 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
| <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> |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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/:vercompanions → write under the tagged key) in the module README or a smallmain()tool; - or a legacy read fallback (tagged key first, then un-tagged, rewrite on hit);
- or at least a startup
ERRORlog when un-tagged keys are detected underkeyPrefix.
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); |
There was a problem hiding this comment.
[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
slotIdcannot address any more) — so the leftover data from the migration above is not even cleanable viaclearAllSessions(); - orphans from a partial write (crash after
RPUSH/SETbut before theSADDthat registers the member), and _keyssets 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) { |
There was a problem hiding this comment.
[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
mgetabstract (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 soRedisAgentStateStorecan log a one-time WARN at build time (andgetVersionedcan fall back to a single-keyEVAL/MULTIread for those adapters).
| throw new IllegalArgumentException("sessionId must not be blank"); | ||
| } | ||
| return normalizeUser(userId) + "/" + sessionId; | ||
| validateScopeId(sessionId, "sessionId"); |
There was a problem hiding this comment.
[Warning] Two over-rejections here that turn previously-working ids into runtime exceptions:
/insessionIdis not needed./must be banned inuserId, becauselistSessionIds("a")would otherwise match{a/b/sess}:_keysand hand back sessions belonging to usera/b. ButsessionIdcannot cause that confusion:listSessionIdsstrips the fixedkeyPrefix + "{" + userSegment + "/"prefix and the"}" + KEYS_SUFFIXtail, so asessionIdofagent1/run42round-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 throwsIllegalArgumentException— a hard regression on live data, on top of the key-layout break.,is not a glob character for Redis. Redis'sSCAN/KEYSmatcher (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: ==="); |
There was a problem hiding this comment.
[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:
- Make the skip loud: emit an ERROR-level marker and/or fail when an env flag such as
REQUIRE_CLUSTER_IT=1is set, then run one CI job with that flag so a passing run is distinguishable from a skipped one. - 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"; |
There was a problem hiding this comment.
[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,
ListHashUtil.computeHash(values)serializes all elements to JSON (this line);ListHashUtil.needsFullRewrite(values, storedHash, existingCount)then callscomputeHash(values.subList(0, existingCount))→ the stored prefix is serialized a second time (this method was not touched, soJdbcAgentStateStore,Mysql/PostgresAgentStateStore,MongoAgentStateStore,Oss/CosAgentStateStore,JsonFileAgentStateStoreandJedisAgentStateStoreall inherit the same multiplication);buildListSaveArgs(...)serializes all elements again to build theRPUSHarguments.
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.
e1bbb79 to
708b6d1
Compare
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
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
708b6d1 to
63fca52
Compare
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
63fca52 to
4efae85
Compare
Description
close #2579
Checklist
Please check the following items before code is ready to be reviewed.
mvn spotless:applymvn test)