Repository navigation
fix(core): agent_state 无条件保存后缓存自身写入的版本 - #3236
Conversation
…IfVersion(UNVERSIONED) call instead of a post-save re-read, closing the window where a concurrent writer's version could leak into slotVersions and bypass CAS stale-write protection; the InMemory UNVERSIONED branch is now atomic, with regression tests added
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
Closes the remaining caller-side window from #3234: persistAgentStateCas no longer infers the version with a separate getVersioned() after an unconditional write, and InMemoryAgentStateStore.saveIfVersion(..., UNVERSIONED) now returns the version of its own write from inside the same synchronized section.
Verified against main (10b8a99a7):
- The interface default is
save(); return UNVERSIONED;(AgentStateStore.java:134-138), so the defensive fall-through at:563is only reachable for a backend that claimssupportsVersioning()and then mis-reports — and it degrades to exactly the old behaviour. Consistent with the existingOVERWRITEarm. setSingleStatedelegating intosetSingleStateReturningVersionkeeps one version-increment implementation, and both methods aresynchronizedon the sameSessionDatamonitor, so no new lock ordering was introduced.- Version numbering stays aligned with
casSingleState(first write = 1, absent = 0), soexpectedVersion == 0create-if-absent semantics are untouched. - The tests are targeted rather than incidental:
unknownVersionMustNotPoisonNextPublicSavepins the actual failure mode underFAIL, andordinaryFreshAndReloadedSlotsAlreadyHaveVersionsdocuments that the ordinary fresh/reload path never reaches the branch.
LGTM. The inline notes are follow-ups, not blockers.
Findings
- [Warning]
ReActAgent.java:547— the "store returns the version assigned to THIS write" premise holds for JDBC (#3220) and in-memory, butMysqlAgentStateStore:457-459andPostgresAgentStateStore:361-363still dosave()followed by areadVersion()on a separate connection, so #3234 is not fully closed for those backends. Suggest a follow-up issue, ideally fixing it in the store layer so the shutdown saver (:373-388) is covered too. - [Info]
ReActAgent.java:563— the defensive fallback can write twice for a store that inherits the defaultsaveIfVersion; alog.warnwould avoid the amplification. Codecov's 2 missing + 1 partial lines on this file look like this branch. - [Info]
InMemoryAgentStateStore.java:97— unconditional CAS writes no longer route through the overridablesave(); subclass hooks (metrics/replication/audit) will stop seeing them. Worth one line in the class Javadoc or the release notes. - [Info]
InMemoryUnconditionalVersionTest.java:48— optional: add a shared-store two-thread case that does not depend on thesave()bypass to pin the atomicity directly.
Checks
Check License / Check Module Sync / build (ubuntu-latest) / build (windows-latest) all pass at head e445f27; license/cla signed.
Automated review by github-manager-bot
| slotVersions.put(slot, after.version()); | ||
| return after.version(); | ||
| // Unconditional write through the versioning API: the store returns the | ||
| // version assigned to THIS write (JDBC #3220, in-memory likewise), so |
There was a problem hiding this comment.
The trust assumption in this comment holds for JdbcAgentStateStore (upsert + version read inside one write transaction, #3220) and now for InMemoryAgentStateStore, but not for the two SQL extension stores:
MysqlAgentStateStore.saveIfVersion(..., UNVERSIONED)—agentscope-extensions/agentscope-extensions-mysql/src/main/java/io/agentscope/extensions/mysql/state/MysqlAgentStateStore.java:457-459callssave()and thenreadVersion(), and each opens its ownConnection(:376and:441), so the version read is a second transaction.PostgresAgentStateStore.saveIfVersion(..., UNVERSIONED)—.../postgresql/state/PostgresAgentStateStore.java:361-363, same shape.
So the cache is no longer poisoned by a read on the caller side, but on MySQL/PG a commit landing between those two store statements is still adopted. That is not a regression introduced here — before this PR every backend went through save + getVersioned() — it is the same window moved one layer down, and #3234 is only fully closed once those two branches return the version of their own write from inside the write transaction. Redis (RedisAgentStateStore, JedisAgentStateStore, RedissonAgentStateStore) and Mongo are already atomic on this path.
Suggest a follow-up issue rather than expanding this PR. The evaluation comment on #3234 reached the same conclusion, and fixing it in the store layer also covers the shutdown saver, which calls saveIfVersion directly (:373-388).
| // Defensive only: a versioning backend returning UNVERSIONED for an | ||
| // unconditional write violates the AgentStateStore contract. | ||
| stateStore.save(userId, sessionId, "agent_state", toSave); |
There was a problem hiding this comment.
Minor: for a backend that reports supportsVersioning() == true while inheriting the interface default saveIfVersion (AgentStateStore.java:134-138, which already calls save(...) and returns UNVERSIONED), this fallback writes the state a second time — one write before this change, two after. The OVERWRITE branch below (:597) already has that shape, so it is consistent rather than new, but a log.warn instead of the extra save() would avoid the write amplification while still flagging the contract violation.
Codecov reports 2 missing + 1 partial line on this file and this defensive branch looks like the uncovered one; a stub store (supportsVersioning() -> true, saveIfVersion -> UNVERSIONED, counting save() calls) would cover it and pin whichever behaviour we settle on.
| // Write and version read in one synchronized section — save() plus a separate | ||
| // lookup could leak a concurrent writer's version when one instance is shared. | ||
| // Does not delegate to the overridable save() (mirrors JDBC #3220). | ||
| SessionData data = lookupOrCreate(userId, sessionId); | ||
| return data.setSingleStateReturningVersion(key, value); |
There was a problem hiding this comment.
The atomicity fix itself is right: lookupOrCreate(...) plus one synchronized method that both writes and returns next closes the window, and having setSingleState delegate to setSingleStateReturningVersion keeps a single version-increment implementation.
One observable side effect for a public, non-final class: saveIfVersion(..., UNVERSIONED) no longer routes through the overridable save(), so third-party subclasses that hook save() for metrics, replication or audit silently stop seeing unconditional CAS writes — this PR's own InMemoryUnconditionalVersionTest depends on that bypass. It mirrors what #3220 did for JDBC, so I would keep the behaviour and just say so in the class Javadoc (or the release notes) so subclass authors are not surprised.
| InMemoryAgentStateStore store = | ||
| new InMemoryAgentStateStore() { | ||
| @Override | ||
| public void save(String u, String s, String k, State v) { | ||
| super.save(u, s, k, v); | ||
| // Inject a concurrent writer exactly when the value under test is | ||
| // written through save(): on main the unconditional saveIfVersion | ||
| // delegates to save() and reads the version outside the lock, so this | ||
| // injection lands in that window. The fixed path never routes through | ||
| // save(), which is what keeps this hook silent after the fix. | ||
| if (v instanceof T t && "mine".equals(t.v())) { | ||
| super.save(u, s, k, new T("other")); | ||
| } | ||
| } | ||
| }; | ||
| store.save("u", "s", "k", new T("initial")); // version 1 | ||
| long returned = | ||
| store.saveIfVersion("u", "s", "k", new T("mine"), AgentStateStore.UNVERSIONED); | ||
| // This caller's write is version 2; on main the injected writer makes it return 3. | ||
| assertEquals(2L, returned); |
There was a problem hiding this comment.
Good deterministic repro — it returns 3 on main and 2 here, and it reuses the snippet from #3234 as-is, which makes the regression permanent.
Since the fixture proves the fix by asserting that a save() override is now not called, consider adding the sibling case that does not depend on that seam: two threads sharing one store, each doing saveIfVersion(..., UNVERSIONED), asserting every caller receives the version its own write produced. Optional, coverage dimension only.
Fixes #3234
agent_state 首次持久化(
expectedVersion == UNVERSIONED)原来是先save()再单独getVersioned()取版本,两步之间如果有别的写入方提交,slotVersions里缓存的就是对方的版本号,下一次 CAS 带着过期信息照样成功,APPEND_MERGE/FAIL都拦不住。两处改动:
ReActAgent.persistAgentStateCas的 UNVERSIONED 分支改调saveIfVersion(..., UNVERSIONED),直接用返回值。后端违约返回 UNVERSIONED 时退回普通save(),兜底方式和已有的 OVERWRITE 分支一致。InMemoryAgentStateStore.saveIfVersion的 UNVERSIONED 分支不再走可覆写的save()再锁外读版本,改为SessionData.setSingleStateReturningVersion一个 synchronized 方法写完直接返回本次版本。