Skip to content

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

Closed

Description

@xzxiaoshan

多个 agent 实例(或多个节点)共享同一个 state store 时,agent 靠 slotVersions 缓存的版本号做 CAS 防过期写。槽位首次持久化(expectedVersion == UNVERSIONED)走的是"先写入、再取版本"路径,这两步不是原子的:中间如果别的写入方提交,agent 缓存到的就是对方的版本号,后续 CAS 的过期写保护失效(ConflictPolicy.APPEND_MERGE / FAIL 都不会触发)。

PR #3220 修掉了 JDBC store 的这个问题,目前还剩两个窗口:

  1. ReActAgent.persistAgentStateCas(ReActAgent.java:543-555):UNVERSIONED 分支先调 stateStore.save(...),再单独调 stateStore.getVersioned(...),两次调用之间可能插入别人的提交。触发场景:agent 构造或重启后某槽位首次持久化,或 shutdown 保存器(ReActAgent.java:373)在不知道版本号时保存。

  2. 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

  1. added
    bug
    on Sep 21, 2026
  2. oss-maintainer commented on Sep 21, 2026

    @oss-maintainer
    Collaborator

    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 — confirmed

    agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:544-555: the UNVERSIONED branch does stateStore.save(...) and then a separate stateStore.getVersioned(...). The version read there is cached via slotVersions.put(slot, after.version()) (:550) and is later used as the CAS expected version (saveAgentState at :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 the UNVERSIONED branch. The UNVERSIONED branch is reached when scope.loadedVersion == UNVERSIONED (no slot entry yet, e.g. first persist of a new session/slot). The shutdown saver (:368-390) calls saveIfVersion directly rather than persistAgentStateCas, but it still hits the same store-level window.

    2. InMemoryAgentStateStore.saveIfVersion(..., UNVERSIONED) — confirmed

    agentscope-core/src/main/java/io/agentscope/core/state/InMemoryAgentStateStore.java:90-97: save() enters SessionData.setSingleState (synchronized, :218-222) and releases the lock on return; the version is then read by a separate unlocked lookup(...) + getVersionedSingleState(...) (:94-96). Because setSingleState and casSingleState (: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 successful saveIfVersion returns the version produced by its own write.

    Your repro is valid on current main: InMemoryAgentStateStore is public and non-final, save(...) is public and non-final, and AgentStateStore.UNVERSIONED / State / VersionedState are all accessible, so the subclass-based injection compiles.

    3. Same pattern exists in the other SQL stores

    MysqlAgentStateStore.java:457-459 and PostgresAgentStateStore.java:361-363 show the same save-then-read-version sequence. Already atomic: JedisAgentStateStore.java:120-124, RedissonAgentStateStore.java:126-130, MongoAgentStateStore.java:389-433. JsonFileAgentStateStore / JpaAgentStateStore / OssAgentStateStore do 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 (for InMemoryAgentStateStore, compute and return the next version inside the same synchronized block as the state update). Hardening persistAgentStateCas to avoid save(...) + 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_MERGE nor FAIL triggers.

    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

  3. added
    area/core/memory
    area/ext/memory
    on Sep 21, 2026
  4. pengmoubuaixuexi commented on Sep 21, 2026

    @pengmoubuaixuexi
    Contributor

    Thanks for splitting this out. I checked main at 10b8a99 and 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 under ConflictPolicy.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 existing saveIfVersion(..., expectedVersion) call, including when the expected version is UNVERSIONED. 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 UNVERSIONED via reflection and inject a deterministic competing commit; they are not an end-to-end restart reproduction or a thread stress test. In my ordinary public getAgentState -> saveAgentState control, a fresh slot uses version 0 and a new agent loading the persisted slot uses version 1. Both getAgentState and activateSlotForContext initialize the slot version. I have not established a normal restart-only trigger for that unknown-version branch. Also, the shutdown saver already calls saveIfVersion directly, 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 test
    /*
     * Copyright 2024-2026 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    package io.agentscope.core.agent;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.junit.jupiter.api.Assertions.assertSame;
    import static org.junit.jupiter.api.Assertions.assertThrows;
    
    import io.agentscope.core.ReActAgent;
    import io.agentscope.core.message.Msg;
    import io.agentscope.core.model.ChatModelBase;
    import io.agentscope.core.model.ChatResponse;
    import io.agentscope.core.model.GenerateOptions;
    import io.agentscope.core.model.ToolSchema;
    import io.agentscope.core.state.AgentState;
    import io.agentscope.core.state.AgentStateStore;
    import io.agentscope.core.state.ConcurrentSessionModificationException;
    import io.agentscope.core.state.ConflictPolicy;
    import io.agentscope.core.state.InMemoryAgentStateStore;
    import io.agentscope.core.state.State;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    import org.junit.jupiter.api.Test;
    import reactor.core.publisher.Flux;
    
    /** Local boundary audit: reflection deliberately supplies an unknown version, not a restart repro. */
    class ReActAgentUnknownVersionAuditTest {
        private static ReActAgent agent(AgentStateStore store) {
            return ReActAgent.builder()
                    .name("audit")
                    .model(
                            new ChatModelBase() {
                                @Override
                                public String getModelName() {
                                    return "unused";
                                }
    
                                @Override
                                protected Flux<ChatResponse> doStream(
                                        List<Msg> messages,
                                        List<ToolSchema> tools,
                                        GenerateOptions options) {
                                    return Flux.error(new AssertionError("No model call expected"));
                                }
                            })
                    .stateStore(store)
                    .conflictPolicy(ConflictPolicy.FAIL)
                    .build();
        }
    
        private static long persistUnknown(ReActAgent agent, AgentState state) throws Exception {
            Method method =
                    ReActAgent.class.getDeclaredMethod(
                            "persistAgentStateCas",
                            String.class,
                            String.class,
                            String.class,
                            AgentState.class,
                            long.class,
                            int.class);
            method.setAccessible(true);
            return (long) method.invoke(agent, "u", "s", "u/s", state, AgentStateStore.UNVERSIONED, 0);
        }
    
        @Test
        void unknownVersionReturnsOwnWriteVersion() throws Exception {
            InterleavingStore store = new InterleavingStore();
            ReActAgent agent = agent(store);
            AgentState mine = agent.getAgentState("u", "s");
            store.injectOtherWrite = true;
            long version = persistUnknown(agent, mine);
            assertEquals(2, store.getVersioned("u", "s", "agent_state", AgentState.class).version());
            assertSame(
                    store.other, store.getVersioned("u", "s", "agent_state", AgentState.class).value());
            assertEquals(1, version, "Version 2 belongs to the interleaved writer");
        }
    
        @Test
        void unknownVersionMustNotPoisonNextPublicSave() throws Exception {
            InterleavingStore store = new InterleavingStore();
            ReActAgent agent = agent(store);
            AgentState mine = agent.getAgentState("u", "s");
            store.injectOtherWrite = true;
            persistUnknown(agent, mine);
            assertThrows(
                    ConcurrentSessionModificationException.class, () -> agent.saveAgentState("u", "s"));
            assertEquals(1, agent.getStateConflictCount());
            assertSame(
                    store.other, store.getVersioned("u", "s", "agent_state", AgentState.class).value());
        }
    
        @Test
        void ordinaryFreshAndReloadedSlotsAlreadyHaveVersions() {
            InterleavingStore store = new InterleavingStore();
            ReActAgent first = agent(store);
            first.getAgentState("u", "s");
            first.saveAgentState("u", "s");
            ReActAgent restarted = agent(store);
            restarted.getAgentState("u", "s");
            restarted.saveAgentState("u", "s");
            assertEquals(List.of(0L, 1L), store.expectedVersions);
            assertEquals(0, store.plainSaves);
        }
    
        @Test
        void nonVersioningBackendKeepsPlainSave() {
            InterleavingStore store =
                    new InterleavingStore() {
                        @Override
                        public boolean supportsVersioning() {
                            return false;
                        }
                    };
            ReActAgent agent = agent(store);
            AgentState mine = agent.getAgentState("u", "s");
            agent.saveAgentState("u", "s");
            assertEquals(1, store.plainSaves);
            assertEquals(List.of(), store.expectedVersions);
            assertSame(mine, store.getVersioned("u", "s", "agent_state", AgentState.class).value());
        }
    
        /**
         * Injects a legal competing commit after a write. Captures the version atomically in the
         * versioned API, independently of the known InMemory UNVERSIONED bug (#3077).
         * This is deterministic interleaving injection, not a thread stress test.
         */
        private static class InterleavingStore extends InMemoryAgentStateStore {
            final AgentState other = AgentState.builder().userId("u").sessionId("s").build();
            final List<Long> expectedVersions = new ArrayList<>();
            boolean injectOtherWrite;
            int plainSaves;
    
            @Override
            public synchronized void save(String u, String s, String k, State value) {
                plainSaves++;
                super.save(u, s, k, value);
                inject(u, s, k);
            }
    
            @Override
            public synchronized long saveIfVersion(
                    String u, String s, String k, State value, long expected) {
                expectedVersions.add(expected);
                long compare =
                        expected == UNVERSIONED
                                ? super.getVersioned(u, s, k, State.class).version()
                                : expected;
                long assigned = super.saveIfVersion(u, s, k, value, compare);
                if (assigned != UNVERSIONED) {
                    inject(u, s, k);
                }
                return assigned;
            }
    
            private void inject(String u, String s, String k) {
                if (injectOtherWrite) {
                    injectOtherWrite = false;
                    super.save(u, s, k, other);
                }
            }
        }
    }
  5. added a commit that references this issue on Sep 21, 2026
    7d08f8f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/core/memoryarea/ext/memorybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions