Repository navigation
Description
Describe the bug
JdbcAgentStateStore.saveIfVersion(..., UNVERSIONED) commits an upsert and then reads the version on a separate connection. Another store instance can commit between these operations, so both successful callers return the later version. The earlier writer can subsequently reuse that version for a conditional update, bypassing the stale-write protection.
To Reproduce
Start with an existing row at version 1. Use two independent JdbcAgentStateStore instances sharing a real H2 database. Coordinate connection close after closing the actual write connection, so both committed writes finish before either caller performs its separate version read. Both calls return 3 instead of distinct versions 2 and 3. No database operation or version value is mocked.
Place the test below under agentscope-extensions/agentscope-extensions-jdbc/src/test/java/io/agentscope/extensions/jdbc/state/JdbcUnconditionalVersionTest.java, then run:
mvn -B -pl agentscope-extensions/agentscope-extensions-jdbc -am -Dtest=JdbcUnconditionalVersionTest -Dsurefire.failIfNoSpecifiedTests=false -Dspotless.skip=true testExpected behavior
Each successful call returns the version assigned to its own write. The returned versions must be 2 and 3, with the latest stored value belonging to the writer that returned 3. A subsequent CAS with version 2 must be rejected without changing that value.
Error messages
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
each successful write must return its own version ==> expected: not equal but was: <3>
Environment
- AgentScope Java 2.0.4-SNAPSHOT, main
5b99145343f55da1c0523f8e943f3ec862886fd7 - Windows, Temurin JDK 17.0.15, Maven 3.9.12, H2 2.4.240
- Local embedded database only; no model provider or API key required.
Additional context
The fix direction is to execute the unconditional upsert and version read on the same connection, inside the existing write transaction and before commit releases the write lock. This must work across store instances; a Java monitor on one instance is insufficient.
I checked open/closed reports using JdbcAgentStateStore version, unconditional race, readVersion, and JDBC atomic, and read #3048/#3064, #3165, #2146 and #2731. #3048 fixes marker-interface deserialization, #3165 fixes migrated version-0 rows, and #3076/#3077 concern the separate in-memory implementation. None addresses this JDBC return-version interleaving. Similar SQL-store shapes merit follow-up, but the executable evidence and proposed patch here target the unified JDBC store.
Investigation and test preparation used Codex assistance; the H2 failure above was executed locally. I am preparing a focused fix and regression coverage.
Complete H2 regression 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.extensions.jdbc.state;
import static org.junit.jupiter.api.Assertions.*;
import io.agentscope.core.state.AgentStateStore;
import io.agentscope.core.state.State;
import io.agentscope.extensions.jdbc.H2TestSupport;
import io.agentscope.extensions.jdbc.dialect.vendor.H2Dialect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
class JdbcUnconditionalVersionTest {
record Value(String text) implements State {}
@Test
@Timeout(30)
void returnsOwnVersionEvenWhenAnotherWriterCommitsBeforeConnectionCloses() throws Exception {
DataSource delegate = H2TestSupport.createDataSource("unconditional_versions");
new JdbcAgentStateStore(delegate, new H2Dialect(), true)
.save("u", "s", "k", new Value("initial"));
CyclicBarrier committed = new CyclicBarrier(2);
DataSource coordinated = (DataSource) Proxy.newProxyInstance(
DataSource.class.getClassLoader(), new Class<?>[] {DataSource.class},
(proxy, method, args) -> {
Object result = invoke(delegate, method, args);
if (!(result instanceof Connection connection)) {
return result;
}
AtomicBoolean wrote = new AtomicBoolean();
return Proxy.newProxyInstance(Connection.class.getClassLoader(),
new Class<?>[] {Connection.class}, (p, m, a) -> {
if (m.getName().equals("prepareStatement")
&& ((String) a[0]).startsWith("MERGE INTO")) {
wrote.set(true);
}
Object value = invoke(connection, m, a);
// The database connection is closed and locks are released first.
// Both real writes finish before either saveIfVersion can return.
if (m.getName().equals("close") && wrote.get()) {
committed.await(10, TimeUnit.SECONDS);
}
return value;
});
});
JdbcAgentStateStore first = new JdbcAgentStateStore(coordinated, new H2Dialect(), true);
JdbcAgentStateStore second = new JdbcAgentStateStore(coordinated, new H2Dialect(), true);
var executor = Executors.newFixedThreadPool(2);
try {
var a = executor.submit(() -> first.saveIfVersion("u", "s", "k", new Value("A"), AgentStateStore.UNVERSIONED));
var b = executor.submit(() -> second.saveIfVersion("u", "s", "k", new Value("B"), AgentStateStore.UNVERSIONED));
long av = a.get(15, TimeUnit.SECONDS);
long bv = b.get(15, TimeUnit.SECONDS);
assertNotEquals(av, bv, "each successful write must return its own version");
assertEquals(Set.of(2L, 3L), Set.of(av, bv));
var latest = first.getVersioned("u", "s", "k", Value.class);
assertEquals(3L, latest.version());
assertEquals(av == 3 ? "A" : "B", latest.value().text());
assertEquals(AgentStateStore.UNVERSIONED, first.saveIfVersion("u", "s", "k", new Value("stale"), 2));
assertEquals(latest, first.getVersioned("u", "s", "k", Value.class));
} finally {
executor.shutdownNow();
}
}
private static Object invoke(Object target, Method method, Object[] args) throws Throwable {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
}
Activity
oss-maintainer commentedon Sep 21, 2026
Issue Evaluation
Category:
bug| Status: ConfirmedVerified against
mainat5b99145343f55da1c0523f8e943f3ec862886fd7— the exact commit named in this report.Root cause: the unconditional path of
saveIfVersionis not atomic.JdbcAgentStateStore.java:255-257callssave()(upsert + commit on its own connection, committed at:534) and only then callsreadVersion(...), which opens a fresh connection (:241) toSELECTthe version. Any writer that commits inside that gap determines the returned version, which contradicts theAgentStateStorecontract "On success returns the new version" (AgentStateStore.java:122).Reproduced: with the verbatim H2 dialect upsert (
version = t.version + 1,H2Dialect.java:107-122) and the same two-connection pattern on a real H2 database, both writers returned3although the first writer's own write produced2; the superseded writer's next CAS with the borrowed version then succeeded, silently discarding the intervening write. The stale-write protection is therefore genuinely bypassable (lost update with no conflict signal), not merely a wrong return value.Impact:
JdbcAgentStateStoreunder concurrent writers to the same session key. The window is commit-to-read, so it is rare under light load and realistic under concurrency. The CAS/conflict path itself is unaffected.Scope beyond this issue: the identical shape exists in
MysqlAgentStateStore.java:457-459(readVersionnew conn at:441),PostgresAgentStateStore.java:361-363(new conn at:345), andInMemoryAgentStateStore.java:92-96(read-back after a separately synchronized save).MongoAgentStateStore.java:415-424(findOneAndUpdate+ReturnDocument.AFTER) andRedisAgentStateStore.java:272-276(atomic Lua script) are already correct and show the intended pattern.Fix direction: sound — perform the upsert and the version read on the same connection inside the existing write transaction, before commit, so the row lock held by the upsert makes the in-transaction read return this writer's own version. A per-instance Java monitor cannot fix it across store instances/processes, as stated here.
Duplication: the author opened PR #3220 shortly after this issue, which fixes
JdbcAgentStateStoreplus a regression test, with green CI on ubuntu/windows. No separate fix proposal will be generated for the JDBC store to avoid competing work. The MySQL/Postgres/in-memory variants above remain open and would be better addressed as follow-ups.Needs maintainer judgment: whether returning "the latest version" instead of "this write's version" was ever an intentional contract for
UNVERSIONEDwrites, and whether the MySQL/Postgres stores should be fixed in the same release.Automated evaluation by github-manager-bot
fix(jdbc): return unconditional write versions atomically (agentscope…