Repository navigation
fix(jdbc): fail fast with actionable migration DDL when adopting the deprecated stores' legacy table - #3244
fix(jdbc): fail fast with actionable migration DDL when adopting the deprecated stores' legacy table#3244aiyili wants to merge 5 commits into
Conversation
官方迁移路径(agentscope-extensions-mysql/-postgresql → jdbc)落在同名的 agentscope_sessions 表上,而 JdbcAgentStateStore 只有 CREATE TABLE IF NOT EXIST 和存在性探针两条 schema 路径,无法为遗留表补列:读不受影响,每个 写操作却都会报 Unknown column 'version'(生产环境难以定位)。 按维护者评估方向实现: - SessionStateDialect 新增 sessionStateEnsureVersionColumnDdl()(默认空, H2/SQLite 的表只可能来自本模块的 CREATE,无需迁移)与只读探针 sessionStateCheckVersionColumnExists();MysqlDialect 返回 ALTER ... ADD COLUMN version BIGINT NOT NULL DEFAULT 1(无 IF NOT EXISTS, 探针先行),PostgresDialect 返回 IF NOT EXISTS 变体 - 探针对表名与列名均做大小写不敏感比较:H2 将未加引号标识符存为大写; MySQL 探针用 SCHEMA() 而非 DATABASE()——H2 的 MySQL 兼容模式下 DATABASE() 返回 catalog 而 INFORMATION_SCHEMA 按 schema 组织 - createIfNotExist=true:建表后条件迁移;false:verifyVersionColumnExists 快速失败并引用需手动执行的 DDL(与 agentscope-ai#3213 相同形态),DEFAULT 1 语义保留 - 顺带修正 H2Dialect.sessionStateCheckTableExists 的大小写敏感比较 (否则 false 路径在 H2 上永远误报表不存在) 测试:遗留表(无 version)构造即迁移+首次写/getVersioned 往返;二次构造 不重复 ALTER(H2 上重复加列必报错,以此证幂等);false 路径报错含完整 DDL;无迁移 DDL 的方言跳过检查;方言 DDL 内容断言;探针失败路径。 Fixes agentscope-ai#3216
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Codecov 对 PR agentscope-ai#3244 报 3 行缺失(2 缺失 + 1 partial): - migrationDdlFailureThrows:探针通过但 ALTER 语句本身执行失败 → RuntimeException 指向 add version column(覆盖 ensureVersionColumn 的 catch 分支) - verifyPathPassesOnMigratedTable:createIfNotExist=false 在已含 version 列的表上直接通过并可写(补齐 verifyVersionColumnExists 的 列存在分支) 模块 100/100;JaCoCo 四个新方法行/分支全部 0 缺失
cb4a9ac to
d747b89
Compare
|
Added two tests covering the reported gaps: migrationDdlFailureThrows (the ALTER itself fails -> RuntimeException pointing at the migration DDL, covering the ensureVersionColumn catch) and verifyPathPassesOnMigratedTable (createIfNotExist=false passes on a table that already has the column, covering the remaining verify branch). Module suite 100/100; local JaCoCo reports 0 missed lines and 0 missed branches for all four new methods. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Closes #3216 correctly: adopting a sessions table left behind by the deprecated agentscope-extensions-mysql / -postgresql stores used to blow up on the first write with Unknown column 'version'. Splitting the migration into a dialect hook (sessionStateEnsureVersionColumnDdl) plus a scoped existence probe, wired into both constructor paths (createIfNotExist=true migrates, false fails fast quoting the exact DDL), is the right shape and keeps vendor DDL out of the store. The DEFAULT 1 / 0 == "row absent" reasoning matches what saveIfVersion's insert-if-absent fallback already assumes, and mirrors the logic in MysqlAgentStateStore#ensureVersionColumn. Verdict: comment — no blocking issue, two robustness gaps worth a follow-up commit.
Findings
- [Warning]
dialect/vendor/MysqlDialect.java:157— non-strictsql_modemakesADD COLUMN ... NOT NULL DEFAULT 1backfill0, reintroducing the "row absent" sentinel the migration exists to avoid. - [Warning]
state/JdbcAgentStateStore.java:120— check-then-alter races two adopting instances intoSQLException 1060, failing cold start on MySQL only. - [Info]
state/JdbcAgentStateStore.java:134— the fail-fast message impliescreateIfNotExist=truealways migrates, which is not true for a non-default table name / customtablePrefix. - [Info]
test/.../JdbcAgentStateStoreH2Test.java:622— the MySQL/Postgres schema predicates (SCHEMA(),current_schema()) are only asserted as strings, so a wrong one would still pass CI.
Notes
- The
H2Dialect#sessionStateCheckTableExistscase-insensitivity fix is an independent bug fix: H2 stores unquoted identifiers upper-case, so the oldTABLE_NAME = ?comparison could never see an existing table andcreateIfNotExist=falsefailed with "Table does not exist" against a table that was there. Fine to bundle — the new column probe needs the same treatment — but worth a line in the PR description so it is not lost in release notes. - Static review only this cycle: the local mirror is synced to
main@c0d03cceabut I did not compile or run the module here, so CI (build (ubuntu-latest)/build (windows-latest), both still pending at review time) remains the authority on build and test status. - CLA is signed (
license/cla: pass); current queue state isMERGEABLE/BLOCKEDonly because the required checks had not finished.
Automated review by github-manager-bot
| public Optional<String> sessionStateEnsureVersionColumnDdl() { | ||
| return Optional.of( | ||
| "ALTER TABLE %s ADD COLUMN version BIGINT NOT NULL DEFAULT 1" | ||
| .formatted(sessionStateTableName())); |
There was a problem hiding this comment.
[Warning] MySQL has no ADD COLUMN IF NOT EXISTS, so this path relies on the probe below — but on a server (or session) running in non-strict sql_mode, ALTER TABLE ... ADD COLUMN version BIGINT NOT NULL DEFAULT 1 backfills existing rows with 0 and only raises warning 1138, not an error. That is exactly the "row absent" sentinel that migrationDdlOrNull() (state store, line 145) argues against, and it would silently turn every migrated row into a CAS insert-if-absent candidate.
Suggest hardening the migration with an explicit backfill after the ALTER:
ALTER TABLE t ADD COLUMN version BIGINT NOT NULL DEFAULT 1;
UPDATE t SET version = 1 WHERE version = 0;The UPDATE is a no-op under strict mode, so it costs nothing when the ALTER behaved. One extra dialect hook, or even just documenting the strict-mode requirement in this javadoc, closes the gap.
| stmt.execute(ddl); | ||
| } catch (SQLException e) { | ||
| throw new RuntimeException("Failed to add version column to session table", e); | ||
| } |
There was a problem hiding this comment.
[Warning] Check-then-alter is not atomic (versionColumnExists() at line 113, stmt.execute(ddl) at line 118): if two instances adopt the same legacy table concurrently, the loser of the race gets SQLException 1060 / Duplicate column name 'version' here and startup fails — a cold-start flake that only shows up on MySQL and only on multi-replica deployments.
Postgres is immune thanks to IF NOT EXISTS; MySQL is not. Consider treating the duplicate-column case as success:
} catch (SQLException e) {
if (isDuplicateColumn(e)) {
return; // another instance migrated first — idempotent by definition
}
throw new RuntimeException("Failed to add version column to session table", e);
}(SQLState 42S21 / vendor code 1060; the existing isDuplicateKey(...) helper already establishes the pattern.)
| return; | ||
| } | ||
| throw new IllegalStateException( | ||
| "Table " |
There was a problem hiding this comment.
[Info] The migration only ever targets dialect.sessionStateTableName(), i.e. agentscope_sessions by default. Adopting a legacy table under a custom tablePrefix is a no-op that then fails at the first write — and this message ("Apply the migration DDL ... or use createIfNotExist=true to auto-migrate") would be misleading in that case, because createIfNotExist=true will not migrate a table under a name the dialect does not use.
If that limitation is intentional, one extra sentence here is enough: "only the default table name is auto-migrated; run the DDL against <your table> yourself".
| assertTrue(postgresProbe.sql().contains("current_schema()")); | ||
| BoundSql mysqlProbe = new MysqlDialect().sessionStateCheckVersionColumnExists("t"); | ||
| assertTrue(mysqlProbe.sql().contains("UPPER(COLUMN_NAME)")); | ||
| } |
There was a problem hiding this comment.
[Info] Good coverage of the H2-executable paths (migrate, idempotent re-construction, fail-fast, no-op vendors, probe failure, DDL failure).
The two dialects that actually ship this migration — MysqlDialect#sessionStateCheckVersionColumnExists (TABLE_SCHEMA = SCHEMA()) and the Postgres one (table_schema = current_schema()) — are only asserted as strings here, so a broken schema predicate would still pass CI. H2 in MODE=MySQL would exercise the MySQL shape end-to-end (the javadoc at MysqlDialect:164 already claims that mode works); the same trick or a lightweight PG harness would cover the Postgres predicate.
794f7e1 to
d747b89
Compare
…tateStore - Inline executeUpsert into save() (BoundSql + bindParams + try-with-resources) - readVersion(Connection, slotId, key) -> readVersion(userId, sessionId, key): validates slot id, opens own connection, no longer reuses caller's conn - Keep a transactional readVersion(Connection, slotId, key) overload for saveIfVersion's UNVERSIONED path so the write+version-read stays atomic (version captured before the write lock is released) - Move if (expectedVersion == UNVERSIONED) early-return OUT of the CAS transaction in saveIfVersion (avoids mixing unconditional and CAS logic) - Delete the now-unused executeUpsert(Connection, slotId, key, String) helper Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
…tateStore - Inline executeUpsert into save() (BoundSql + bindParams + try-with-resources) - readVersion(Connection, slotId, key) -> readVersion(userId, sessionId, key): validates slot id, opens own connection, no longer reuses caller's conn - Keep a transactional readVersion(Connection, slotId, key) overload for saveIfVersion's UNVERSIONED path so the write+version-read stays atomic (version captured before the write lock is released) - Move if (expectedVersion == UNVERSIONED) early-return OUT of the CAS transaction in saveIfVersion (avoids mixing unconditional and CAS logic) - Delete the now-unused executeUpsert(Connection, slotId, key, String) helper Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
…tateStore - Inline executeUpsert into save() (BoundSql + bindParams + try-with-resources) - readVersion(Connection, slotId, key) -> readVersion(userId, sessionId, key): validates slot id, opens own connection, no longer reuses caller's conn - Keep a transactional readVersion(Connection, slotId, key) overload for saveIfVersion's UNVERSIONED path so the write+version-read stays atomic (version captured before the write lock is released) - Move if (expectedVersion == UNVERSIONED) early-return OUT of the CAS transaction in saveIfVersion (avoids mixing unconditional and CAS logic) - Delete the now-unused executeUpsert(Connection, slotId, key, String) helper Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
…tStateStore - Inline executeUpsert into save() (BoundSql + bindParams + try-with-resources) - Move if (expectedVersion == UNVERSIONED) early-return OUT of the CAS transaction in saveIfVersion (avoids mixing unconditional and CAS logic); the unconditional write+version-read still happens in a single transaction (version captured before the write lock is released) - Delete the now-unused executeUpsert(Connection, slotId, key, String) helper Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
- Move the expectedVersion == UNVERSIONED early-return out of the CAS transaction in saveIfVersion: the unconditional write+version-read runs in its own single transaction (version still captured before the write lock is released) - Rename executeUpsert -> upsertSingleState and call it from both save() and the UNVERSIONED branch, so the unconditional write keeps a single definition - Add javadoc on save() noting that subclasses intercepting writes should override both save and saveIfVersion Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
|
建议将迁移逻辑简化为一层通用检查:启动时以 SELECT * FROM <表名> WHERE 1=0 获取 ResultSetMetaData 与期望列对比,发现缺列即抛出阻断性异常,错误信息中明确具体表名和缺失字段名,同时在日志中打印当前版本的完整建表 DDL 供用户对比调整数据库表——检测、定位、参照均已齐备,足以给开发者可靠的行动基础;框架无需再提供方言定制的 DDL 语句,也不应做任何自动 DDL 执行,框架的DDL 控制收窄。 |
- 启动时以 SELECT * FROM <表名> WHERE 1=0 取 ResultSetMetaData,与期望列 (session_id, state_key, item_index, state_data, version)大小写不敏感对比; 缺列即抛阻断性 IllegalStateException,错误信息明确表名与全部缺失列名 - 抛错前将该版本完整建表 DDL 逐条 LOG.error 打印,供用户对比调整数据库表 - 删除 SessionStateDialect.sessionStateEnsureVersionColumnDdl() 与 sessionStateCheckVersionColumnExists() 及 MySQL/Postgres 的 ALTER 实现: 框架不再提供方言定制的迁移 DDL,也不再自动执行任何迁移 DDL; createIfNotExist=true 遇遗留缺列表同样阻断,不再自动补列 - 测试重写:遗留表两条路径均启动阻断并点名缺列;多列缺失按序全部列出 (同时验证大小写不敏感);完整表 false 路径通过且可写;探针失败指向表名
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the follow-up commit that narrows migration to a generic startup schema check. The code side is clean: the removed dialect methods have zero remaining references in the head tree (and never existed on base, so this is not a public-API removal), unused imports were dropped, the metadata-only probe is correct for the legacy shape (labels lowercased with Locale.ROOT), both auto-create and verify paths report the table and every missing column, and the tests were reworked consistently — including a real case-insensitive UPPER(TABLE_NAME) fix in H2Dialect.sessionStateCheckTableExists. Two guidance items remain: the failure message's only remedy is reference DDL that is a silent no-op on an existing table, and the title/description still promise auto-migration that the code deliberately no longer performs.
Previous-round follow-up
All four earlier inline findings (MySQL non-strict backfill, check-then-alter race, custom tablePrefix gap, missing vendor probe tests) are resolved by removing the executed DDL.
Automated review by github-manager-bot
| for (String ddl : dialect.sessionStateCreateTableDdls()) { | ||
| LOG.error("Reference CREATE TABLE DDL for table {}: {}", table, ddl); | ||
| } | ||
| throw new IllegalStateException( |
There was a problem hiding this comment.
The failure names the table and the missing columns, but its only remedy is the reference CREATE TABLE DDL logged on the line above, and those statements are CREATE TABLE IF NOT EXISTS in all four vendors - pasted into a migration run they are a silent no-op on the pre-existing legacy table, so the next start fails identically. It also withholds the one non-obvious value: an ALTER's DEFAULT backfills the existing rows, while the logged CREATE TABLE declares DEFAULT 0 (the deprecated mysql/postgresql stores deliberately add this column with DEFAULT 1 for exactly these rows). Logging/emitting the concrete ALTER TABLE <table> ADD COLUMN <missing> ... per vendor would make this a one-step fix.
| * @param dialect the session-state dialect | ||
| * @param createIfNotExist when true, auto-creates the sessions table | ||
| * @param createIfNotExist when true, auto-creates the sessions table when absent; an | ||
| * existing table is never altered either way — a schema mismatch fails the store at |
There was a problem hiding this comment.
This javadoc correctly states that an existing table is never altered, but the PR title and description still promise the opposite ("migrate the legacy version column", "use createIfNotExist=true to auto-migrate", plus the now-deleted sessionStateEnsureVersionColumnDdl), and the title becomes the release note for the adoption path the module README documents under "Migration from Deprecated Modules". Please retitle/re-describe this as a fail-fast schema check that requires the operator to add version themselves.
…JdbcAgentStateStore (#3273) ## Summary Orthogonal refactor of the JDBC single-state write path, extracted from the work on #3216 / #3244 so the migration PR stays focused. - **Lift the `UNVERSIONED` case out of the CAS transaction** in `saveIfVersion` - the unconditional write path no longer mixes with CAS logic. The write+version-read still happens in a single transaction (version captured before the write lock is released); an inline comment now documents that invariant. - **Rename `executeUpsert` -> `upsertSingleState`** and call it from both `save()` and the UNVERSIONED branch, so the unconditional single-state write keeps a single definition. - **Add javadoc on `save()`** noting that subclasses intercepting writes should override both `save` and `saveIfVersion`. No behavioral change to any public API. All existing tests pass.
|
问题定位清晰,实现也完整,感谢! 但这两天从模块整体层面重新想了一遍:现在各 store 各自建表、各自校验的做法,缺的不只是这一张表的列检查,而是统一的 schema 收口。我打算把散落的建表 DDL 执行与列校验集中到一处(方言 + builder),三张表一次覆盖,届时这个 PR 的机制可以直接吸收进去。方案我会尽快整理成 issue 同步,这个 PR 建议先 hold,方向对齐后再决定是改造还是关闭。 该PR,暂时挂起。 |
参考 CREATE TABLE IF NOT EXISTS 对被报告的遗留表本身是静默 no-op, 照抄进迁移脚本后下次启动仍以同样方式失败;且参考 DDL 声明的 DEFAULT 0 会误导迁移——ALTER 会以默认值回填既有行,而 0 是 saveIfVersion 的'行不存在'哨兵,废弃模块当年即因此特意用 DEFAULT 1。 version 是唯一现实的遗留缺口(废弃存储的表形状包含其余全部列), 且 BIGINT 类型四方言一致,单条 ALTER 即可覆盖所有方言。缺其他列 意味着表并非来自废弃模块,继续指向参考建表 DDL。 两个 legacy 测试加强断言:报错必须包含完整的 ALTER TABLE ... ADD COLUMN version BIGINT NOT NULL DEFAULT 1
|
Both guidance items addressed:
Module suite 92/92 green. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
The follow-up commit does what my previous review asked: the startup failure now carries an immediately executable ALTER TABLE ... ADD COLUMN version BIGINT NOT NULL DEFAULT 1 instead of only a reference CREATE TABLE that cannot apply to the table in question, and the reasoning for DEFAULT 1 (backfill semantics vs the 0 row-absent sentinel) is both commented and pinned by the new H2 assertions. Combined with the earlier fail-fast design, this is good to go - LGTM.
Findings
- [Info]
JdbcAgentStateStore.java:160- the recommendedALTERleaves a different columnDEFAULTthan the reference DDL creates; harmless via the store (which always writesversion) but worth a sentence for operators whose own SQL omits the column.
Notes
- All five checks are green on the current head, and
license/clais signed.
Automated review by github-manager-bot
| // and its type is vendor-uniform, so one statement serves all four dialects. | ||
| // DEFAULT 1 deliberately, not the reference DDL's DEFAULT 0: an ALTER backfills | ||
| // pre-existing rows with the default, and 0 is the "row absent" CAS sentinel. | ||
| String versionRemedy = |
There was a problem hiding this comment.
[Info] This is the right fix for the problem I flagged - CREATE TABLE IF NOT EXISTS is a no-op on the very table being reported, so quoting an executable ALTER is the only remedy that actually unblocks an operator. One small asymmetry to consider documenting: the suggested ALTER leaves the column DEFAULT as 1 on the migrated table, whereas a table created by the reference DDL has DEFAULT 0. The store always writes version explicitly so behaviour is identical today, but a hand-written INSERT that omits version would now get 1 on migrated tables and 0 on fresh ones. Either a sentence in the message ("the migrated table keeps DEFAULT 1; align it with the reference DDL if your own SQL relies on the column default") or a follow-up ALTER COLUMN ... SET DEFAULT 0 in the operator docs would make the two schemas converge.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
The follow-up commit does what my previous review asked: the startup failure now carries an immediately executable ALTER TABLE ... ADD COLUMN version BIGINT NOT NULL DEFAULT 1 instead of only a reference CREATE TABLE that cannot apply to the table in question, and the reasoning for DEFAULT 1 (backfill semantics vs the 0 row-absent sentinel) is both commented and pinned by the new H2 assertions. Combined with the earlier fail-fast design, this is good to go - LGTM.
Findings
- [Info]
JdbcAgentStateStore.java:160- the recommendedALTERleaves a different columnDEFAULTthan the reference DDL creates; harmless via the store (which always writesversion) but worth a sentence for operators whose own SQL omits the column.
Notes
- All five checks are green on the current head, and
license/clais signed.
Automated review by github-manager-bot
按复审建议向运维说明:ALTER 之后的列 DEFAULT 保持 1(参考 DDL 建的是 0), 经 store 使用无影响(store 总是显式写 version),但运维自写 SQL 省略 version 列时插入的行会落 DEFAULT 1 而非 0——1 不是哨兵值,行为安全, 只是与参考建表 DDL 的形状不同,值得一句提醒。
|
Thanks — the Info item is addressed in c51896a: the remedy now tells operators that the column DEFAULT stays 1 afterwards (unlike the reference DDL's 0), harmless through the store since it always writes version explicitly, but worth knowing if their own SQL omits the column. Module suite 97/97 green. Ready to merge whenever you are. |
|
Good news: this asymmetry is exactly what the previous commit (c51896a, the response to your earlier Info item) already documents — the remedy message now continues:
That covers both halves of your suggestion: it states the migrated-table DEFAULT (1) and warns hand-written INSERTs that omit the column. No further change needed — the PR remains ready to merge as-is. |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of c51896a1 (previous approval was on 88d76726). The delta is docs-only: the fail-fast message now also states that the column DEFAULT stays 1 after the suggested ALTER, unlike the reference DDL's 0, and explains why that is harmless for the store (it always writes version explicitly). That closes the last open [Info] about the asymmetry between the remediation DDL and the reference schema.
No functional change versus the previously approved state: the startup check still never alters an existing table, so the earlier check-then-alter atomicity concern no longer applies, and the title/description now match the fail-fast behaviour.
CLA signed, CI green at c51896a1 (build ubuntu/windows, Check License, codecov/patch).
Automated review by github-manager-bot
|
Thanks @xzxiaoshan — consolidating the schema work into the dialect builder with Closing #3244 as superseded — the fail-fast-with-actionable-DDL behavior my iterations converged on (case-insensitive column probe, the DEFAULT 1 vs 0 backfill semantics, the H2 |
Fixes #3216
What this does now
A fail-fast startup schema check — no automatic DDL beyond
CREATE TABLE IF NOT EXISTSon a fresh table. Adopting the deprecated mysql/postgresql stores' table (agentscope_sessions) no longer fails with an opaqueUnknown column 'version'on the first write: both construction paths probe the table's shape via JDBC metadata (case-insensitive column names) and fail at startup naming the table and every missing required column.The remedy is actionable. The reference
CREATE TABLE IF NOT EXISTSDDL is logged, but the exception quotes the statement that actually repairs an existing table:DEFAULT 1deliberately (not the reference DDL'sDEFAULT 0): anALTERbackfills pre-existing rows, and0is the "row absent" CAS sentinel — the deprecated stores added this column withDEFAULT 1for exactly those rows.versionis the only realistic legacy gap (the deprecated shape has every other required column) and its type is vendor-uniform, so one statement serves all four dialects; a table missing other columns did not originate from the deprecated stores and is pointed at the reference DDL.Also included:
H2Dialect.sessionStateCheckTableExistsnow comparesUPPER(TABLE_NAME) = UPPER(?)(H2 stores unquoted identifiers uppercase — the exact-match probe mis-reported existing tables on thefalsepath).Why checks instead of auto-migration
Earlier iterations of this PR executed the
ALTERautomatically; review findings (non-strict MySQL backfill semantics, check-then-alter race under concurrent startups, custom tablePrefix gap, DDL-permission concerns per #3213) led to deliberately narrowing to a check — the operator runs the one quoted statement through their own migration process.Tests
Legacy-shape table (no
version) blocks both construction paths with a message naming the table, the missing column(s), and the actionableALTER; every missing required column is named (generic gate); migrated/complete tables construct and round-trip on both paths; probe failure surfaces asRuntimeException; dialect DDL content assertions.