Repository navigation
fix(jdbc): allow sandbox-shaped slot ids containing path separators - #3233
Conversation
SessionSandboxStateStore 会把隔离键打包成斜杠分隔的 sessionId (sandbox/session/<id>、sandbox/user/<agentId>/<id> 等),而 JdbcAgentStateStore.validateSlotId 拒绝含 / 或 \ 的 slot, 导致沙箱恢复状态在所有 JDBC 后端上永远无法持久化(仅记一条 WARN, 静默丢失)。 slot ID 在该存储里只作为预编译语句的绑定参数(已核对全部 17 处 dialect SQL 均为 ? 占位符,无字符串拼接),不是文件路径,路径分隔符 限制只对文件型存储有意义(JsonFileAgentStateStore 自己通过 safeSegment 编码每个路径段)。因此移除该检查,保留空值与 255 长度 校验。 H2 回归测试:四种沙箱形状 slot ID 的 save/get/exists/delete 端到端 往返;空值/超长仍然拒绝。 Fixes agentscope-ai#3231
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
Correct, well-scoped fix for #3231. Verified against main: every slotId reach-path in JdbcAgentStateStore goes through dialect.sessionState*(...) as a BoundSql parameter (e.g. WHERE session_id = ?), so relaxing the separator guard exposes no SQL surface; JsonFileAgentStateStore still encodes unsafe segments via safeSegment (Base64), so the two store families keep independent path safety. H2 round-trip coverage of all four SessionSandboxStateStore id shapes plus the blank/oversized regression guard is exactly what this change needs.
Two non-blocking notes:
- The guard also rejected
\, so the relaxation now accepts backslash-bearing slot ids too; that is fine for JDBC (opaque bind value) but worth keeping in mind for any future export/migration path into a filesystem-backed store. slotId(userId, sessionId)composes keys — since equals-only bind semantics apply, separator-collision behavior is unchanged by this PR.
LGTM.
Automated review by github-manager-bot
|
方案没问题,slot id 在这个 store 里只是 PreparedStatement 的绑定值,分隔符检查本来就不该存在。 合并前有一个改动请求:deprecated 的 postgres 模块里还留着同样的检查(PostgresAgentStateStore.validateSessionId,约 758 行)。这个pg模块 虽已标记废弃,但仍在构建发布,之前的修复也都是 jdbc / mysql / postgres 三个模块一起改的,留在上面的用户会遇到完全相同的静默丢数据,不修的话原 issue 只算解决了一半。 |
评审请求(PR agentscope-ai#3233):deprecated 的 postgres 模块仍随版本构建发布, PostgresAgentStateStore.validateSessionId 保留了与 JdbcAgentStateStore 相同的 / 与 \ 拒绝逻辑,留在该模块上的用户会遇到完全相同的沙箱恢复 状态静默丢失(agentscope-ai#3231 只算解决了一半)。 同 JDBC 修复:移除路径分隔符检查(此处 slot id 同样只作为 PreparedStatement 绑定参数),保留空值与 255 长度校验。原有断言旧 拒绝行为的 rejectsSessionIdWithPathSeparators 测试替换为 acceptsSandboxShapedSessionIds(沙箱形状 slot ID 可正常保存)。
|
Thanks @xzxiaoshan — agreed, good catch. Pushed as 1824cbc on the same branch:
Postgres module suite: 148/148 green. |
|
LGTM |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review after 1824cbc (the follow-up requested by @xzxiaoshan). The new commit removes the identical / + \ rejection from the deprecated PostgresAgentStateStore.validateSessionId and swaps the old rejectsSessionIdWithPathSeparators test for acceptsSandboxShapedSessionIds — that closes the "half-fixed" gap, and I verified the claim independently: in both the JDBC and the Postgres store a slot id is only ever a bound parameter, while the path-based backend (JsonFileAgentStateStore) encodes each segment via safeSegment, so it keeps its own traversal safety. Left-aligning with MysqlAgentStateStore (which never had the check) is the right shape for the fix, and blank/oversized rejection is intentionally retained.
One pre-existing gap worth a separate issue, not a change request here: PostgresAgentStateStore.listSessionIds builds LIKE '<userPrefix>%' without escaping SQL wildcards, while the JDBC store has likePrefixPattern(...) plus a test named listSessionIdsEscapesPercentAndUnderscore. The default anonymous prefix __anon__ is therefore six single-character wildcards on Postgres, and a caller-supplied userId containing _/% widens the result set further. It is out of this PR's diff and unrelated to the separator change, so consider porting the JDBC escape helper in a follow-up.
CI note at review time: license/cla, License and Module Sync passed; build (ubuntu-latest) / build (windows-latest) were still queued when this review was posted, and Codecov reports all modified coverable lines covered. The Postgres assertions run against a mocked PreparedStatement rather than a real backend, so they pin the bind value but not end-to-end persistence on Postgres — the same point as the inline test nit, not a blocker.
Approved: the change is small, well-targeted, and the regression is covered on both backends.
Automated review by github-manager-bot
| } | ||
| // Path separators are allowed: the slot id is only ever bound as a PreparedStatement | ||
| // parameter here, never used as a filesystem path, and SessionSandboxStateStore | ||
| // legitimately generates slash-separated slot ids ("sandbox/session/<id>") — rejecting |
There was a problem hiding this comment.
[Info] Same rationale holds on this side of the fix — I re-checked the deprecated module: every access path in this class binds session_id as a PreparedStatement parameter (session_id = ?), and getFullTableName() is built from schema/table names only, never from a slot id, so allowing / here is safe. Consistent with the JDBC change and with MysqlAgentStateStore, which has never had the separator check.
| // legitimately generates slash-separated slot ids ("sandbox/session/<id>") — rejecting | ||
| // them silently dropped all sandbox resume state (#3231). | ||
| if (sessionId.length() > 255) { | ||
| throw new IllegalArgumentException("AgentStateStore ID cannot exceed 255 characters"); |
There was a problem hiding this comment.
[Warning] Not blocking, and pre-existing rather than introduced here: with the separator check gone, sandbox slots reach this table as __anon__:sandbox/user/<agentId>/<id>, and the column is VARCHAR(255). validateSessionId only bounds the inner session id, so a composed slot that overflows 255 chars will fail at insert (or be truncated by a non-strict driver) and reproduce exactly the silent-loss class of bug #3231 is fixing. A cheap follow-up: validate the composed slotId(userId, sessionId) length instead of the raw segment, or reject loudly at the call site.
| void acceptsSandboxShapedSessionIds() throws SQLException { | ||
| // Regression for #3231: SessionSandboxStateStore generates slash-separated slot ids | ||
| // ("sandbox/session/<id>", "sandbox/user/<agentId>/<id>"); they are opaque bind values | ||
| // here, not paths, and used to be rejected — silently dropping sandbox resume state. | ||
| PostgresAgentStateStore store = | ||
| PostgresAgentStateStore.builder(dataSource).createIfNotExist(false).build(); | ||
| assertThrows( | ||
| IllegalArgumentException.class, | ||
| () -> store.save("user", "a/b", "key", new TestState("v"))); | ||
| assertThrows( | ||
| IllegalArgumentException.class, | ||
| () -> store.save("user", "a\\b", "key", new TestState("v"))); | ||
|
|
||
| store.save(null, "sandbox/session/01M31AQP7A24X0Y4A12RKADD5P", "key", new TestState("v1")); | ||
| store.save( | ||
| null, | ||
| "sandbox/user/agent-7/01M31AQP7A24X0Y4A12RKADD5P", | ||
| "key", | ||
| new TestState("v2")); | ||
|
|
||
| verify(preparedStatement) | ||
| .setString(1, "__anon__:sandbox/session/01M31AQP7A24X0Y4A12RKADD5P"); | ||
| verify(preparedStatement) | ||
| .setString(1, "__anon__:sandbox/user/agent-7/01M31AQP7A24X0Y4A12RKADD5P"); |
There was a problem hiding this comment.
[Info] Good regression coverage. One nit: both verify(preparedStatement).setString(1, ...) calls assert only the first bind of the upsert, so they would still pass if the slot composition (normalizeUser + : separator) changed shape. Asserting the full bind set with an ArgumentCaptor, or at least pinning the trailing state_key/item_index binds, makes the contract test harder to break silently. The JDBC H2 test covers this by round-tripping real rows, so this is purely about symmetry.
listSessionIds built its LIKE pattern from the raw user segment, so user
ids containing '%' or '_' widened the prefix match across users: e.g.
listSessionIds("user_1") also returned sessions of "userA1", and the
anonymous user "__anon__" compiled to an 8-character wildcard run.
Escape '\', '%' and '_' before appending '%', following PostgreSQL's
default LIKE escape character, mirroring the escape helper already used
by the MySQL JDBC store as suggested in the agentscope-ai#3233 review.
Regression tests cover '%', '_' (anonymous user) and the escape
character itself.
Co-Authored-By: Claude Code <[email protected]>
This is by an automated agent, not a human. Fixes #4329. ## AgentScope-Java Version 2.1.0-SNAPSHOT (`main`) ## Description `PostgresAgentStateStore.listSessionIds` built its `LIKE` pattern by concatenating the raw user segment, so user ids containing PostgreSQL wildcards (`%`, `_`) widened the prefix match across users. For example, `listSessionIds("user_1")` also matched slots of `userA1`, and the anonymous user `__anon__` compiled to a run of single-character wildcards. The pattern now escapes `\`, `%` and `_` with PostgreSQL's default `LIKE` escape character before appending the trailing `%`, mirroring the `likePrefixPattern` helper already used by the JDBC state store (as suggested in the #3233 review). Three regression tests cover `%`, the underscores in the anonymous user, and the escape character itself. ## Verification - `mvn -B -T1C -pl agentscope-extensions/agentscope-extensions-postgresql -am test` → BUILD SUCCESS; PostgreSQL module: 151 tests, 0 failures, 0 errors, including the three new `PostgresAgentStateStoreTest` cases. - `mvn -B -T1C -pl agentscope-extensions/agentscope-extensions-postgresql spotless:check` → BUILD SUCCESS. ## Checklist - [x] Code has been formatted with `mvn spotless:apply` - [x] All tests are passing (`mvn test`) - [x] Javadoc comments are complete and follow project conventions - [ ] Related documentation has been updated — not applicable: internal SQL pattern fix with no documented behavior change - [x] Code is ready for review Co-authored-by: shanuo0312 <[email protected]> Co-authored-by: Joe Zou <[email protected]>
Fixes #3231
Problem
SessionSandboxStateStorepacks isolation keys into slash-separated session ids (sandbox/session/<id>,sandbox/user/<agentId>/<id>,sandbox/agent/<agentId>,sandbox/global), butJdbcAgentStateStore.validateSlotIdrejected any slot id containing/or\\. Every JDBC-backed sandbox state write failed and was only logged as a warning, so sandbox resume state was silently never persisted on any JDBC backend.Fix (option 2 from the evaluation - the smaller, non-breaking change)
Remove the path-separator guard from
JdbcAgentStateStore.validateSlotId; the null/empty and 255-length checks stay. Safety notes:sessionIdusages inSessionStateDialectbind it via?; there is no string interpolation into SQL and no filesystem use.JsonFileAgentStateStoreencodes every path segment viasafeSegment/decodeSegment, so relaxing the JDBC guard opens no traversal hole.Tests (H2, real database round-trips)
sandboxShapedSessionIdsRoundTrip- all four slot id shapesSessionSandboxStateStoregenerates (session / user / agent / global) save, read back,exists, anddeleteend-to-end. This is the exact scenario from the issue: previously every one of these threwSession ID cannot contain path separators.blankAndOversizedSessionIdsStillRejected- the remaining validations still hold.Module suite: 87/87 green (
BUILD SUCCESS).