Repository navigation
fix(jdbc): return unconditional write versions atomically - #3220
Conversation
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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 overridablesave()); 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 overridesaveIfVersionas 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")) { |
There was a problem hiding this comment.
这里靠 SQL 前缀 "MERGE INTO" 认写语句,跟 H2 方言的实现绑死了。哪天 H2Dialect 的 upsert SQL 改了写法,wrote 永远是 false,屏障不会等,这个测试就悄悄退化成碰运气的测试——基线坏了也可能过。建议改成认 executeUpdate(写操作都走它,读走 executeQuery,不会误判),另外加个计数器,两个 future 都结束后断言协调发生了 2 次,协调丢了测试就直接红。
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
这行用了全限定名,改成静态导入的 assertTrue,跟文件里其他断言保持一致。
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
只跑 H2 不够,MysqlDialect / PostgresDialect 的 upsert SQL 一行都没执行过。不用连真库:H2 换 MySQL 兼容模式(URL 加 MODE=MySQL),挂 MysqlDialect 把这两个用例再跑一遍;PostgreSQL 的 ON CONFLICT 语法 H2 跑不了,就在 DialectSqlTests 里把 MySQL / PostgreSQL 的 upsert 断言补到 version = version + 1 子句——这是本修复成立的关键。
There was a problem hiding this comment.
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.
|
ReActAgent.java 的 persistAgentStateCas 在 expectedVersion == UNVERSIONED 时执行 save() 后再调 getVersioned() 读版本——两次调用分属不同事务,中间其他写入者可提交,slotVersions 会缓存一个不属于自己的版本号,下次 CAS 可能绕过并发冲突检测。本 PR 修复 JDBC store 后,saveIfVersion(UNVERSIONED) 已能原子返回自身版本,该分支可直接改用它消除窗口。 @jujn 这个 ReActAgent 里的点,是单开 PR 处理,还是让贡献者在当前 PR 一并修了?你定一下。 其他方面 review 我认为没什么问题了。 |
你来定吧,你更熟悉这块 |
oss-maintainer
left a comment
There was a problem hiding this comment.
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:
- Write detection no longer bound to the H2
MERGE INTOprefix — the connection proxy now wraps eachPreparedStatementand flags successfulexecuteUpdate()calls, so the test cannot silently degrade into a lucky-pass if the dialect SQL changes. - Coordination is now asserted, not assumed —
coordinatedClosesmust reach exactly 2 before the futures' results are trusted, andcoordinateWritesis 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. - Vendor SQL coverage — both concurrency tests are parameterized over H2 native and H2
MODE=MySQL(so the real MySQLON DUPLICATE KEY UPDATEstatement actually executes), andDialectSqlTestspins the PostgreSQLON CONFLICT ... version = <table>.version + 1increment 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 proxiedexecuteUpdate()per writer connection. If the store ever issues a second write statement in the same transaction, the second close will hitcommitted.await()with a parties=2 barrier and burn the 30s test timeout instead of failing fast. AcoordinateWrites.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
我记录一下,单独起一个 issue 修 reactagent 的这个相关问题,这个 PR 先合入。 |
AgentScope-Java Version
2.0.4-SNAPSHOT, based on main at
5b99145343f55da1c0523f8e943f3ec862886fd7.Description
Fixes #3219.
Two
JdbcAgentStateStoreinstances 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
saveand the unconditional versioned path share an upsert helper; the version read still avoids deserializing theStatemarker interface. Conditional CAS and version-0 migration handling are unchanged. Javadoc explicitly documents thatsaveIfVersionno longer invokes the public overridablesavemethod.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
5b991453, both H2/MySQL-dialect variants fail with duplicate version 3 (2 assertion failures, 0 errors/skips).clean packagesucceeded, including Spotless checks and Javadoc generation. The Windows rerun usedJAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8after an initial AG-UI Javadoc encoding failure.git diff --cached --checkpassed.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
mvn test(not run locally).Codex assistance was used for source review, implementation and test preparation. All validation results above were executed locally.