Skip to content

fix(core): agent_state 无条件保存后缓存自身写入的版本 - #3236

Merged
jujn merged 2 commits into
agentscope-ai:mainfrom
xzxiaoshan:fix/agent-state-unconditional-version
Sep 21, 2026
Merged

jujn merged 2 commits into
agentscope-ai:mainfrom
xzxiaoshan:fix/agent-state-unconditional-version

Conversation

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

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 方法写完直接返回本次版本。

…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

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.92308% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/src/main/java/io/agentscope/core/ReActAgent.java 62.50% 2 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@jujn
jujn merged commit 7d08f8f into agentscope-ai:main Sep 21, 2026
6 checks passed

@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

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 :563 is only reachable for a backend that claims supportsVersioning() and then mis-reports — and it degrades to exactly the old behaviour. Consistent with the existing OVERWRITE arm.
  • setSingleState delegating into setSingleStateReturningVersion keeps one version-increment implementation, and both methods are synchronized on the same SessionData monitor, so no new lock ordering was introduced.
  • Version numbering stays aligned with casSingleState (first write = 1, absent = 0), so expectedVersion == 0 create-if-absent semantics are untouched.
  • The tests are targeted rather than incidental: unknownVersionMustNotPoisonNextPublicSave pins the actual failure mode under FAIL, and ordinaryFreshAndReloadedSlotsAlreadyHaveVersions documents 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, but MysqlAgentStateStore:457-459 and PostgresAgentStateStore:361-363 still do save() followed by a readVersion() 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 default saveIfVersion; a log.warn would 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 overridable save(); 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 the save() 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

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.

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-459 calls save() and then readVersion(), and each opens its own Connection (:376 and :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).

Comment on lines +561 to +563
// Defensive only: a versioning backend returning UNVERSIONED for an
// unconditional write violates the AgentStateStore contract.
stateStore.save(userId, sessionId, "agent_state", toSave);

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.

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.

Comment on lines +93 to +97
// 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);

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.

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.

Comment on lines +29 to +48
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);

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.

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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: agent_state 无条件保存后可能缓存到别的写入方的版本号

3 participants