Repository navigation
Description
多个 agent 实例(或多个节点)共享同一个 state store 时,agent 靠 slotVersions 缓存的版本号做 CAS 防过期写。槽位首次持久化(expectedVersion == UNVERSIONED)走的是"先写入、再取版本"路径,这两步不是原子的:中间如果别的写入方提交,agent 缓存到的就是对方的版本号,后续 CAS 的过期写保护失效(ConflictPolicy.APPEND_MERGE / FAIL 都不会触发)。
PR #3220 修掉了 JDBC store 的这个问题,目前还剩两个窗口:
-
ReActAgent.persistAgentStateCas(ReActAgent.java:543-555):UNVERSIONED 分支先调stateStore.save(...),再单独调stateStore.getVersioned(...),两次调用之间可能插入别人的提交。触发场景:agent 构造或重启后某槽位首次持久化,或 shutdown 保存器(ReActAgent.java:373)在不知道版本号时保存。 -
InMemoryAgentStateStore.saveIfVersion(..., UNVERSIONED)(InMemoryAgentStateStore.java:92-97):分支先调save()(synchronized 块结束即释放锁),随后在锁外读版本,共享同一实例的线程都可能读到后写入者的版本,违反接口约定 "On success returns the new version"。
To Reproduce
问题 2 可用下面的确定性测试在 main 上复现(实际返回 3,期望 2),放在 agentscope-core/src/test/java/io/agentscope/core/state/InMemoryUnconditionalVersionTest.java:
package io.agentscope.core.state;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class InMemoryUnconditionalVersionTest {
record T(String v) implements State {}
@Test
@DisplayName("unconditional save returns its own version even when a writer interleaves")
void unconditionalSaveReturnsOwnVersion() {
AtomicInteger saves = new AtomicInteger();
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 after the 2nd save — exactly in the
// window between save() and the unlocked version read on main.
if (saves.incrementAndGet() == 2) {
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; version 3 belongs to the injected writer.
assertEquals(2L, returned);
var latest = store.getVersioned("u", "s", "k", T.class);
assertEquals(3L, latest.version());
assertEquals("other", latest.value().v());
}
}问题 1 不需要 store 层另有 bug:两个节点共用一个 JdbcAgentStateStore,同时重启(slotVersions 为空),都在第一个 checkpoint 做无条件持久化,B 在 A 的 save() 和 getVersioned() 之间提交,A 就缓存了 B 的版本。
Expected behavior
无条件保存后,agent 缓存的应该是自己这次写入产生的版本号,而不是并发写入方的(saveIfVersion 成功时返回的就是本次写入的版本)。
Activity
oss-maintainer commentedon Sep 21, 2026
Issue Evaluation
Category:
bug| Status: Confirmed | Severity: High (code-engine assessment was critical; downgraded one notch here because it only manifests when multiple writers share one versioned store, not in single-node usage)Verified against
main(10b8a99a7). Both windows you describe are real, and the scope is a bit wider than reported.1.
ReActAgent.persistAgentStateCas— confirmedagentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:544-555: theUNVERSIONEDbranch doesstateStore.save(...)and then a separatestateStore.getVersioned(...). The version read there is cached viaslotVersions.put(slot, after.version())(:550) and is later used as the CAS expected version (saveAgentStateat:4652-4653), so a writer that commits inside that gap gets its version adopted by this caller — exactly the stale-write-protection loss you describe.One correction on reachability: for versioning backends the constructor/restart paths set
loadedVersion = 0, so they take the CAS branch rather than theUNVERSIONEDbranch. TheUNVERSIONEDbranch is reached whenscope.loadedVersion == UNVERSIONED(no slot entry yet, e.g. first persist of a new session/slot). The shutdown saver (:368-390) callssaveIfVersiondirectly rather thanpersistAgentStateCas, but it still hits the same store-level window.2.
InMemoryAgentStateStore.saveIfVersion(..., UNVERSIONED)— confirmedagentscope-core/src/main/java/io/agentscope/core/state/InMemoryAgentStateStore.java:90-97:save()entersSessionData.setSingleState(synchronized,:218-222) and releases the lock on return; the version is then read by a separate unlockedlookup(...)+getVersionedSingleState(...)(:94-96). BecausesetSingleStateandcasSingleState(:224) are independent synchronized methods, another thread sharing the same store instance can bump the version in that window. This violates the interface contract that a successfulsaveIfVersionreturns the version produced by its own write.Your repro is valid on current
main:InMemoryAgentStateStoreis public and non-final,save(...)is public and non-final, andAgentStateStore.UNVERSIONED/State/VersionedStateare all accessible, so the subclass-based injection compiles.3. Same pattern exists in the other SQL stores
MysqlAgentStateStore.java:457-459andPostgresAgentStateStore.java:361-363show the same save-then-read-version sequence. Already atomic:JedisAgentStateStore.java:120-124,RedissonAgentStateStore.java:126-130,MongoAgentStateStore.java:389-433.JsonFileAgentStateStore/JpaAgentStateStore/OssAgentStateStoredo not support versioning, so they are not in scope.Root cause & suggested direction
#3220 fixed the JDBC store by running the upsert and the version read inside one write transaction (
JdbcAgentStateStore.java:259-261) so the returned version belongs to the just-committed write. The cleanest fix is at the store level for the remaining versioning backends:saveIfVersion(..., UNVERSIONED)must atomically return its own write's version (forInMemoryAgentStateStore, compute and return the next version inside the samesynchronizedblock as the state update). HardeningpersistAgentStateCasto avoidsave(...)+getVersioned(...)is complementary, but the store-level fix also covers the shutdown-saver path.Impact: shared-store / multi-node deployments — precisely the configurations where versioning matters. The failure is silent: the adopted version matches the store, so later CAS checks pass and neither
ConflictPolicy.APPEND_MERGEnorFAILtriggers.No linked PR found for this issue. Marking as confirmed and needs-info-free; a fix proposal can proceed from the store-level change described above.
Automated evaluation by github-manager-bot
pengmoubuaixuexi commentedon Sep 21, 2026
Thanks for splitting this out. I checked
mainat10b8a99and prepared a local boundary regression for the ReActAgent part.With a store fixture that atomically captures its own write version (so this is independent of the InMemory store bug), the current helper returns the competing writer's version, and a subsequent public
saveAgentState(...)incorrectly succeeds underConflictPolicy.FAIL. Two assertions fail on unchanged main; the other two control tests pass.The minimal local change is to retain the plain-save branch only for
!stateStore.supportsVersioning(), removing its read-back block. Versioning stores then reach the existingsaveIfVersion(..., expectedVersion)call, including when the expected version isUNVERSIONED. With that change, all 4 audit cases and 38 existing related tests pass (42 total, no failures/errors/skips); Spotless and diff checks pass. This remains a local candidate, not a competing PR.One scope qualification: these two regressions explicitly invoke the private persistence helper with
UNVERSIONEDvia reflection and inject a deterministic competing commit; they are not an end-to-end restart reproduction or a thread stress test. In my ordinary publicgetAgentState -> saveAgentStatecontrol, a fresh slot uses version 0 and a new agent loading the persisted slot uses version 1. BothgetAgentStateandactivateSlotForContextinitialize the slot version. I have not established a normal restart-only trigger for that unknown-version branch. Also, the shutdown saver already callssaveIfVersiondirectly, so its unknown-version case depends on the backend implementation rather than this helper's save/read-back window.For the InMemory part, existing issue #3076 and my PR #3077 already cover it, including a deterministic regression and a 4-writer/800-write test. I noticed #3077 is now closed without merging, while #3076 remains open and main still contains the old branch. Those changes/tests are available to reuse for this follow-up; I have not reopened it or created a duplicate PR.
Codex assisted with this source audit, local candidate and tests; the commands were executed locally on Windows/JDK 17. No model calls or database integration tests were involved in this core-layer audit.
Runnable local boundary tests (ReActAgentUnknownVersionAuditTest.java)
Place the class below in
agentscope-core/src/test/java/io/agentscope/core/agent/and run:mvn -B -pl agentscope-core -am -Dtest=ReActAgentUnknownVersionAuditTest -Dsurefire.failIfNoSpecifiedTests=false testfix(core): agent_state 无条件保存后缓存自身写入的版本 (agentscope-ai#3236)