Skip to content

fix(jdbc): return unconditional write versions atomically - #3220

Merged
jujn merged 2 commits into
agentscope-ai:mainfrom
pengmoubuaixuexi:fix/jdbc-unconditional-version
Sep 21, 2026
Merged

jujn merged 2 commits into
agentscope-ai:mainfrom
pengmoubuaixuexi:fix/jdbc-unconditional-version

Conversation

@pengmoubuaixuexi

@pengmoubuaixuexi pengmoubuaixuexi commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.4-SNAPSHOT, based on main at 5b99145343f55da1c0523f8e943f3ec862886fd7.

Description

Fixes #3219.

Two JdbcAgentStateStore instances writing unconditionally to the same key can both return the later writer's version: the upsert commits before a separate connection reads the version. That gives the earlier writer a version it can incorrectly reuse for a subsequent CAS.

Run the unconditional upsert and version read on the same connection within the existing write transaction, capturing the version before commit releases the write lock. Plain save and the unconditional versioned path share an upsert helper; the version read still avoids deserializing the State marker interface. Conditional CAS and version-0 migration handling are unchanged. Javadoc explicitly documents that saveIfVersion no longer invokes the public overridable save method.

Both concurrency tests run against H2Dialect on H2 and MysqlDialect on H2 in MySQL compatibility mode. The deterministic regression coordinates two real store instances after their write connections close, without mocking SQL or versions. It detects writes by intercepting PreparedStatement.executeUpdate(), independently of SQL spelling, and asserts exactly two coordinated closes so a missing barrier cannot silently weaken the test. Both dialect variants fail on the baseline because both writers return 3, and pass after the fix with versions 2 and 3. A second test uses four independent store instances with no connection interception, each performing 25 writes; it verifies unique contiguous versions, the latest version/value association, and rejection of a stale CAS without changing stored state. SQL-generation tests also assert the MySQL and PostgreSQL upsert version-increment clauses.

Validation

  • Before: deterministic regression on unmodified main 5b991453, both H2/MySQL-dialect variants fail with duplicate version 3 (2 assertion failures, 0 errors/skips).
  • After: 96 tests passed, 0 failures/errors/skips (all 90 default local JDBC tests plus 6 core versioning contract tests).
  • Target JDBC module and its reactor dependencies: clean package succeeded, including Spotless checks and Javadoc generation. The Windows rerun used JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 after an initial AG-UI Javadoc encoding failure.
  • Targeted Spotless apply/check and git diff --cached --check passed.
  • Windows, Temurin JDK 17.0.15, Maven 3.9.12. The MySQL dialect is executed on H2 with MODE=MySQL, not a real MySQL server. PostgreSQL upsert syntax is checked via SQL-generation assertions, not executed on H2. No model calls or real MySQL/PostgreSQL integration tests; Testcontainers profile was not enabled.
mvn -B -pl agentscope-extensions/agentscope-extensions-jdbc -am -Dtest=JdbcStoreH2Test,JdbcUnconditionalVersionTest,JdbcAgentStateStoreH2Test,JdbcRemoteSnapshotClientH2Test,JdbcSandboxExecutionGuardSqliteTest,JdbcSandboxExecutionGuardH2Test,JdbcDistributedStoreH2Test,DialectSqlTests,AbstractJdbcDialectFromTest,AgentStateStoreVersioningContractTest -Dsurefire.failIfNoSpecifiedTests=false clean package

Scope is the unified JDBC store. This does not modify the separate in-memory fix #3077 or claim to fix the legacy standalone MySQL/PostgreSQL stores.

Checklist

  • Changed code formatted with Spotless.
  • Relevant tests and target reactor package pass.
  • Full repository mvn test (not run locally).
  • Javadoc documents the transaction and subclass delegation behavior.
  • Focused change ready for review.

Codex assistance was used for source review, implementation and test preparation. All validation results above were executed locally.

Copilot AI lite review requested due to automatic review settings September 21, 2026 00:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

No unresolved issues were identified that would block approval.

Review effort: Lite
Findings: None

What changed in this PR

Fixes JDBC unconditional-write version races by reading the assigned version before the write transaction commits.

Changes:

  • Reuses an upsert helper for plain and versioned writes.
  • Reads unconditional-write versions on the same transaction connection.
  • Adds H2 concurrency regression tests.
File Description
agentscope-extensions/​agentscope-extensions-jdbc/​src/​test/​java/​io/​agentscope/​extensions/​jdbc/​state/​JdbcUnconditionalVersionTest.java Updated as part of this pull request.
agentscope-extensions/​agentscope-extensions-jdbc/​src/​main/​java/​io/​agentscope/​extensions/​jdbc/​state/​JdbcAgentStateStore.java Updated as part of this pull request.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Sep 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@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

Reworks JdbcAgentStateStore.saveIfVersion so an unconditional write (expectedVersion == UNVERSIONED) performs the upsert and reads back the resulting version inside the same write transaction, instead of delegating to save() and re-reading in a second connection/transaction. That closes a real lost-update hazard: a concurrent writer could bump the row between the two transactions, so the caller (e.g. ReActAgent, which feeds the returned value straight back in as the next expectedVersion) would believe it wrote a version it did not write.

Verified against the interface contract in AgentStateStore (UNVERSIONED = -1L), so the UNVERSIONED / 0L branch ordering is safe, and the new behaviour now matches InMemoryAgentStateStore. readVersion(Connection, …) throwing SQLException is fine — every call site is inside the try { … } catch (Exception) that wraps it in a RuntimeException, and rollback handling in executeInWriteTransaction still applies. The new regression test is the right shape: it forces the interleaving via a proxied Connection and asserts each successful write gets its own version, plus a multi-worker monotonicity check.

Findings

  • [Info] JdbcAgentStateStore.java:124 — the javadoc correctly documents the behavioural change (versioned writes no longer route through the overridable save()); this is the only observable API-adjacent change and it is necessary for atomicity. Worth calling out in the PR description/changelog so downstream subclasses of this store know to override saveIfVersion as well.

LGTM — atomicity fix with a targeted regression test.


Automated review by github-manager-bot

(p, m, a) -> {
if (m.getName().equals("prepareStatement")
&& ((String) a[0])
.startsWith("MERGE INTO")) {

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.

这里靠 SQL 前缀 "MERGE INTO" 认写语句,跟 H2 方言的实现绑死了。哪天 H2Dialect 的 upsert SQL 改了写法,wrote 永远是 false,屏障不会等,这个测试就悄悄退化成碰运气的测试——基线坏了也可能过。建议改成认 executeUpdate(写操作都走它,读走 executeQuery,不会误判),另外加个计数器,两个 future 都结束后断言协调发生了 2 次,协调丢了测试就直接红。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 41b4748. The connection proxy now wraps PreparedStatement and detects successful executeUpdate() calls, without inspecting SQL text. After both futures complete, the test asserts exactly two coordinated closes before disabling coordination for the stale-CAS check. I reran this deterministic test against unmodified main 5b99145: both H2Dialect and MysqlDialect (H2 MODE=MySQL) fail with duplicate version 3; both pass with the fix.

}
assertEquals(workers * rounds, writesByVersion.size());
for (long version = 2; version <= workers * rounds + 1; version++) {
org.junit.jupiter.api.Assertions.assertTrue(writesByVersion.containsKey(version));

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.

这行用了全限定名,改成静态导入的 assertTrue,跟文件里其他断言保持一致。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 41b4748: assertTrue now uses a static import, consistent with the other assertions. Spotless apply/check passed.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

class JdbcUnconditionalVersionTest {

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.

只跑 H2 不够,MysqlDialect / PostgresDialect 的 upsert SQL 一行都没执行过。不用连真库:H2 换 MySQL 兼容模式(URL 加 MODE=MySQL),挂 MysqlDialect 把这两个用例再跑一遍;PostgreSQL 的 ON CONFLICT 语法 H2 跑不了,就在 DialectSqlTests 里把 MySQL / PostgreSQL 的 upsert 断言补到 version = version + 1 子句——这是本修复成立的关键。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 41b4748. Both concurrency tests are now parameterized over H2Dialect and MysqlDialect with H2 MODE=MySQL, so the actual MySQL upsert SQL executes in both cases. DialectSqlTests also asserts the MySQL and PostgreSQL stored-version increment clauses, normalizing whitespace. PostgreSQL is a SQL-generation assertion only, not an H2 execution. Final validation: 90 JDBC tests plus 6 core version-contract tests passed, and the target reactor clean package passed (UTF-8 JVM encoding on Windows). The PR description now states these coverage boundaries explicitly.

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

ReActAgent.java 的 persistAgentStateCas 在 expectedVersion == UNVERSIONED 时执行 save() 后再调 getVersioned() 读版本——两次调用分属不同事务,中间其他写入者可提交,slotVersions 会缓存一个不属于自己的版本号,下次 CAS 可能绕过并发冲突检测。本 PR 修复 JDBC store 后,saveIfVersion(UNVERSIONED) 已能原子返回自身版本,该分支可直接改用它消除窗口。

@jujn 这个 ReActAgent 里的点,是单开 PR 处理,还是让贡献者在当前 PR 一并修了?你定一下。

其他方面 review 我认为没什么问题了。

@jujn

jujn commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

@jujn 这个 ReActAgent 里的点,是单开 PR 处理,还是让贡献者在当前 PR 一并修了?你定一下。

其他方面 review 我认为没什么问题了。

你来定吧,你更熟悉这块

@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

Re-review after 41b47482 (test-only hardening). All three points from the previous round are addressed and the production diff is unchanged from the previously approved commit 20253a37:

  1. Write detection no longer bound to the H2 MERGE INTO prefix — the connection proxy now wraps each PreparedStatement and flags successful executeUpdate() calls, so the test cannot silently degrade into a lucky-pass if the dialect SQL changes.
  2. Coordination is now asserted, not assumed — coordinatedCloses must reach exactly 2 before the futures' results are trusted, and coordinateWrites is flipped off afterwards so a future code change that stops closing the write connection fails the assertion instead of hanging the barrier. Good deadlock-avoidance ordering.
  3. Vendor SQL coverage — both concurrency tests are parameterized over H2 native and H2 MODE=MySQL (so the real MySQL ON DUPLICATE KEY UPDATE statement actually executes), and DialectSqlTests pins the PostgreSQL ON CONFLICT ... version = <table>.version + 1 increment as a string assertion where H2 cannot execute the syntax.

The earlier [Info] note (versioned writes no longer route through the overridable save()) is now documented directly in the save / saveIfVersion javadoc. CLA signed.

Findings

  • [Info] JdbcUnconditionalVersionTest.java — assertEquals(2, coordinatedCloses.get()) assumes exactly one proxied executeUpdate() per writer connection. If the store ever issues a second write statement in the same transaction, the second close will hit committed.await() with a parties=2 barrier and burn the 30s test timeout instead of failing fast. A coordinateWrites.compareAndSet(true, false) guard at the trigger site (or parties=3) would make the failure mode immediate. Non-blocking.

Favourable correctness note: the MySQL-compatibility parameterization also exercises readVersion(conn, ...) on the same transaction-scoped connection used by executeUpsert, which is where the atomicity fix actually lives.


Automated review by github-manager-bot

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

Copy link
Copy Markdown
Collaborator

@jujn 这个 ReActAgent 里的点,是单开 PR 处理,还是让贡献者在当前 PR 一并修了?你定一下。
其他方面 review 我认为没什么问题了。

你来定吧,你更熟悉这块

我记录一下,单独起一个 issue 修 reactagent 的这个相关问题,这个 PR 先合入。

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]: JdbcAgentStateStore unconditional writes can return another writer's version

5 participants