Skip to content

fix(extensions): use a binary collation for MySQL key columns - #3288

Merged
xzxiaoshan merged 10 commits into
agentscope-ai:mainfrom
lzcGeek:fix-mysql-key-collation
Sep 26, 2026
Merged

xzxiaoshan merged 10 commits into
agentscope-ai:mainfrom
lzcGeek:fix-mysql-key-collation

Conversation

@lzcGeek

@lzcGeek lzcGeek commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What

Pin COLLATE utf8mb4_bin on the MySQL key columns only, so that keys are compared case-sensitively the way the other backends already compare them:

file table columns
MysqlDialect.storeCreateTableDdls() agentscope_store namespace_path, item_key
MysqlDialect.sessionStateCreateTableDdls() agentscope_sessions session_id, state_key
MysqlDialect.snapshotCreateTableDdls() agentscope_snapshots snapshot_id (+ explicit ENGINE=InnoDB DEFAULT CHARSET=utf8mb4)
MysqlJdbcStoreDialect.getCreateTableSql() legacy store namespace_path, item_key
MysqlAgentStateStore.createTableIfNotExist() legacy sessions session_id, state_key
JdbcRemoteSnapshotClient.initSchema() legacy snapshots snapshot_id (+ explicit charset and engine)

Payload columns (value_json, state_data, data) stay on the table default.

Why

DEFAULT CHARSET=utf8mb4 without COLLATE resolves to the charset default, which is case- and accent-insensitive: utf8mb4_0900_ai_ci on MySQL 8.0+, utf8mb4_general_ci on 5.7 and MariaDB. The session tables were explicit about it (COLLATE utf8mb4_unicode_ci). Both are arbitrary caller-supplied strings, so:

  • put(ns, "README.md", a) then put(ns, "readme.md", b) takes the ON DUPLICATE KEY UPDATE branch — a is silently lost, with no error, warning or version conflict.
  • agentscope_sessions packs session_id as {userSegment}:{sessionId}, so two users whose ids differ only in case share session state.
  • snapshot_id is a primary key too, so on the legacy path (MysqlDistributedStore -> JdbcSnapshotSpec -> JdbcRemoteSnapshotClient) two ids differing only in case were one row and the second upload won.

PostgreSQL (plain VARCHAR, DB default), H2 (H2 default) and SQLite (TEXT + BINARY) all compare these columns case-sensitively, so identical application code returned different rows depending on the backend.

utf8mb4_bin stays 4 bytes per character, so the index-width budget is unchanged: (512 + 255) * 4 = 3068 bytes, still under InnoDB's 3072. MysqlJdbcStoreDialectTest.createTablePrimaryKeyFitsInnoDbUtf8mb4Limit() keeps guarding that.

Scope

Collation only, as agreed. No drift detection: earlier revisions of this PR added an AbstractJdbcDialect probe that read INFORMATION_SCHEMA on every build() to warn about pre-existing tables. That is gone, together with the MysqlAgentStateStore constructor probe, the binaryCollationColumns() / attachedCollation() / verifyBinaryCollation() hooks, the builder call and their tests.

Existing-table migration is a documented operator action instead, in docs/v2/{en,zh}/integration/session/mysql.md:

ALTER TABLE agentscope_store
    MODIFY namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL,
    MODIFY item_key       VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;

ALTER TABLE agentscope_sessions
    MODIFY session_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
    MODIFY state_key  VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;

ALTER TABLE agentscope_snapshots
    MODIFY snapshot_id VARCHAR(512) COLLATE utf8mb4_bin NOT NULL;

The docs also record that the collation changes read semantics (= and LIKE 'prefix%' become case-sensitive, so migrate outside a busy window) and that a deployment which already wrote case-variant keys has already lost one of those rows. Both paths that create agentscope_snapshots now pin the same collation, so no path-specific caveat is needed.

The adjacent findings stay out of scope for separate issues: the redundant idx_namespace / idx_session indexes, and the TIMESTAMP -> DATETIME leftovers plus the version BIGINT NOT NULL DEFAULT 0 in the legacy sessions DDL versus DEFAULT 1 in ensureVersionColumn().

How verified

Local, MySQL-collation-specific behaviour cannot be covered by the H2/SQLite suites, so the tests assert the generated DDL:

mvn -pl agentscope-extensions/agentscope-extensions-jdbc test
  Tests run: 94, Failures: 0, Errors: 0, Skipped: 0

mvn -pl agentscope-extensions/agentscope-extensions-mysql test
  Tests run: 11, Failures: 0, Errors: 0, Skipped: 0

mvn -pl agentscope-extensions/agentscope-extensions-jdbc,agentscope-extensions/agentscope-extensions-mysql spotless:check
  BUILD SUCCESS
  • DialectSqlTests.mysqlKeyColumnsUseBinaryCollation asserts the per-column COLLATE on namespace_path, item_key, session_id, state_key and snapshot_id, compared against whitespace-normalised DDL.
  • DialectSqlTests.mysqlPayloadColumnsKeepDefaultCollation asserts payload columns keep the table default and that no COLLATE leaks into the PostgreSQL / H2 / SQLite DDL, which are already case-sensitive.
  • MysqlJdbcStoreDialectTest, MysqlAgentStateStoreTest and JdbcRemoteSnapshotClientTest pin the three legacy DDLs the same way.

I did not add a MySQL-gated integration test that writes README.md / readme.md and asserts two rows — that needs a real MySQL (Testcontainers/Docker), which is not available in my environment. Happy to add it if you want it here.

Closes #3217

Copilot AI lite review requested due to automatic review settings September 24, 2026 23:58
@CLAassistant

CLAassistant commented Sep 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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

🟡 Changes recommended

Add session-table migration guidance and fix the legacy session test stubbing; documentation alignment is also needed.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 Low severity

Open (1)
What changed in this PR

Updates MySQL key columns to use utf8mb4_bin, preventing case-insensitive key collisions across current and legacy schemas.

Changes:

  • Applied binary collation to store and session key columns.
  • Added generated-DDL tests for collation placement and index limits.
  • Preserved payload-column and other-backend behavior.
File Summary
agentscope-extensions/​agentscope-extensions-mysql/​src/​test/​java/​io/​agentscope/​extensions/​mysql/​store/​MysqlJdbcStoreDialectTest.java Tests legacy store DDL collation.
agentscope-extensions/​agentscope-extensions-mysql/​src/​test/​java/​io/​agentscope/​extensions/​mysql/​state/​MysqlAgentStateStoreTest.java Tests legacy session DDL; moderate issue (1 vote) remains with conditional next() stubbing.
agentscope-extensions/​agentscope-extensions-mysql/​src/​main/​java/​io/​agentscope/​extensions/​mysql/​store/​MysqlJdbcStoreDialect.java Updates legacy store schema.
agentscope-extensions/​agentscope-extensions-mysql/​src/​main/​java/​io/​agentscope/​extensions/​mysql/​state/​MysqlAgentStateStore.java Updates legacy session schema; documentation examples and Javadoc need alignment (nit, 4 votes).
agentscope-extensions/​agentscope-extensions-jdbc/​src/​test/​java/​io/​agentscope/​extensions/​jdbc/​dialect/​DialectSqlTests.java Tests modern dialect SQL and collation behavior.
agentscope-extensions/​agentscope-extensions-jdbc/​src/​main/​java/​io/​agentscope/​extensions/​jdbc/​dialect/​vendor/​MysqlDialect.java Updates modern MySQL DDL; session-table migration guidance is incomplete (moderate, 1 vote).

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

Comment on lines +245 to +246
+ " (session_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"
+ " state_key VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"
MySQL's utf8mb4 default collation is case-insensitive (utf8mb4_0900_ai_ci on
8.0+, utf8mb4_general_ci on 5.7 and MariaDB), and the session tables pinned
utf8mb4_unicode_ci explicitly. The key columns were therefore compared
case-insensitively while PostgreSQL, H2 and SQLite compare them
case-sensitively, so identical application code behaved differently per
backend:

- JdbcStore.put(ns, "README.md", a) followed by put(ns, "readme.md", b) took
  the ON DUPLICATE KEY UPDATE branch: `a` was lost with no error, warning or
  version conflict.
- agentscope_sessions stores session_id as "{userSegment}:{sessionId}", so two
  users whose ids differ only in case shared session state.

Pin COLLATE utf8mb4_bin on the key columns only (namespace_path / item_key,
session_id / state_key) and leave payload columns on the table default. Because
both the shared dialect and the legacy MySQL classes build these tables, fix
both paths so they agree:

- MysqlDialect.storeCreateTableDdls / sessionStateCreateTableDdls
- MysqlJdbcStoreDialect.getCreateTableSql
- MysqlAgentStateStore.createTableIfNotExist

utf8mb4_bin stays 4 bytes per character, so the index-width budget is unchanged:
(512 + 255) * 4 = 3068 bytes, still under InnoDB's 3072.

The published schema examples are aligned with the generated DDL, since a table
pre-created from an outdated example keeps the case-insensitive default and
misses the behaviour this change provides:

- docs/v2/en/integration/session/mysql.md
- docs/v2/zh/integration/session/mysql.md
- the table-schema Javadoc of MysqlAgentStateStore

Tests: DialectSqlTests asserts the per-column COLLATE on the key columns and
that no COLLATE leaks into the PostgreSQL / H2 / SQLite DDL, since those are
already case-sensitive. MysqlJdbcStoreDialectTest asserts the store DDL, and
MysqlAgentStateStoreTest captures the CREATE TABLE issued during construction
and asserts the sessions DDL.

Note for operators: a DDL change does not fix existing tables. Tables created
before this change keep their case-insensitive collation until they are
migrated with ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin, and any
deployment that already wrote case-variant keys has already lost rows.

Closes agentscope-ai#3217
@lzcGeek
lzcGeek force-pushed the fix-mysql-key-collation branch from acd8ab4 to 4107686 Compare September 25, 2026 00:03
@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the open finding in 4107686:

  • docs/v2/en/integration/session/mysql.md and docs/v2/zh/integration/session/mysql.md: schema examples now show COLLATE utf8mb4_bin on session_id and state_key, with a note that the table default stays utf8mb4_unicode_ci and that pre-existing tables need ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin. You were right that pre-creating a table from the old example would have kept the case-insensitive default and missed the point of the change.
  • MysqlAgentStateStore: the table-schema Javadoc now matches the generated DDL, plus a paragraph on why only the key columns pin the binary collation.

On the remaining note about MysqlAgentStateStoreTest: the resultSet.next() stubbing is deliberately order-independent. The existing @BeforeEach already stubs it as true, true, true; the new test only adds a lenient() thenReturn(true) when no stubbing is registered yet, and then picks the DDL out of the captured statements instead of depending on the constructor's statement order:

if (Mockito.mockingDetails(resultSet).getStubbings().isEmpty()) {
    lenient().when(resultSet.next()).thenReturn(true);
}
ArgumentCaptor<String> sqlCaptor = ArgumentCaptor.forClass(String.class);
new MysqlAgentStateStore(dataSource, "agentscope", "agentscope_sessions", true);
verify(connection, atLeastOnce()).prepareStatement(sqlCaptor.capture());
String ddl = sqlCaptor.getAllValues().stream()
        .filter(sql -> sql.startsWith("CREATE TABLE"))
        .findFirst()
        .orElseThrow(() -> new AssertionError("No CREATE TABLE was issued: " + sqlCaptor.getAllValues()));

The intent is to keep the assertion stable if the constructor issues a different number of statements, rather than to paper over a failure. Happy to harden it if you would prefer explicit stubbing.

@codecov

codecov Bot commented Sep 25, 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

Pins utf8mb4_bin on the MySQL primary-key columns of the store and session-state tables so keys that differ only by letter case stop colliding and silently overwriting each other. The diagnosis is correct, the blast radius is well contained (key columns only, payload columns untouched), Postgres/H2/SQLite are left alone because they compare case-sensitively by default, and both docs trees are updated. CI is green; mergeState is still BLOCKED on review requirements.

Two things keep this from an approve, both about the other half of the problem: the change only fixes tables that do not exist yet, and it changes read semantics for tables that do.

Findings

  • [Warning] MysqlDialect.java:78 — no detection/migration for pre-existing tables, so already-deployed stores stay exposed with no signal
  • [Warning] MysqlAgentStateStore.java:250 — this class already runs an ALTER TABLE for the version column; the collation fix-up belongs in the same path. The key columns also become case-sensitive on the read side (=, LIKE 'prefix%'), which deserves an explicit sentence in the migration note
  • [Info] MysqlJdbcStoreDialect.java:29 — sibling MySQL key tables (snapshot_id, lock_name) are untouched; either cover them or record why not
  • [Info] DialectSqlTests.java:136 — assertions pin DDL whitespace character-for-character; a normalised/regex form would be less brittle

Suggestions

A minimal version of the migration guard, reusing the shape that already exists in MysqlAgentStateStore:

// after the existing table check
String q = "SELECT COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS "
         + "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?";
// if the key column is not utf8mb4_bin -> log.warn once, or ALTER when createIfNotExist opt-in says "migrate"

Either way the outcome an operator wants is: a fresh install gets the fix automatically, an existing install is told loudly that it does not.

Nice test coverage on the negative side too — asserting that no COLLATE leaks into the other dialects is exactly the guard that keeps this fix from spreading by accident.


Automated review by github-manager-bot

+ " ("
+ " namespace_path VARCHAR(512) NOT NULL,"
+ " item_key VARCHAR(255) NOT NULL,"
+ " namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL,"

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.

The collation is only pinned inside CREATE TABLE IF NOT EXISTS, so every table that already exists keeps the case-insensitive default and keeps silently overwriting README.md vs readme.md. The docs note the manual ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin, but nothing tells an operator their deployment is still exposed. Would you consider a detection step here — e.g. on the existing-table check, read INFORMATION_SCHEMA.COLUMNS.COLLATION_NAME for the key columns and log a WARN (or run the ALTER behind an opt-in flag)? A wrong-but-silent store is worse than a noisy one.

"CREATE TABLE IF NOT EXISTS "
+ getFullTableName()
+ " (session_id VARCHAR(255) NOT NULL, state_key VARCHAR(255) NOT NULL,"
+ " (session_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"

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.

This class already issues an ALTER TABLE for the version column further up, so a collation fix-up has an established home in the same code path — worth reusing that pattern instead of leaving migration to the docs. Note also that this DDL only runs when createIfNotExist=true; users who pre-create the table by hand get no signal at all that their key columns are still utf8mb4_unicode_ci. Related: switching the key columns to utf8mb4_bin also flips the read path (WHERE session_id = ?, session_id LIKE 'prefix%') from case-insensitive to case-sensitive, so a caller that has been relying on the accidental CI match starts seeing misses after migrating. That is the intended semantics, but it deserves one explicit sentence in the migration note in both docs files.

return "CREATE TABLE IF NOT EXISTS %s ("
+ " namespace_path VARCHAR(512) NOT NULL,"
+ " item_key VARCHAR(255) NOT NULL,"
+ " namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL,"

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.

Coverage question for the same bug class: the sibling MySQL key tables are untouched — MysqlDialect.snapshotCreateTableDdls() (snapshot_id VARCHAR(512) PRIMARY KEY), JdbcRemoteSnapshotClient.initSchema() and AbstractJdbcDialect's lock table (lock_name VARCHAR(255) PRIMARY KEY). For the lock table the failure mode is inverted (two lock names differing only in case collapse into one row → false contention instead of silent data loss), and snapshot_id is documented as a session UUID, so both may be deliberate exclusions. Either folding them in or stating the rationale in the PR description would help the next person who greps for utf8mb4_bin.

var d = new MysqlDialect();

String store = d.storeCreateTableDdls().get(0);
assertTrue(store.contains("namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL"));

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.

Nit: the new assertions match the SQL text character-for-character, including the double spaces the DDL happens to use (VARCHAR(512) COLLATE, LONGTEXT COLLATE). A spotless run or an alignment tweak will fail these tests with no behaviour change. This file already has a regex helper (varcharLength); asserting on a normalised form such as namespace_path\s+VARCHAR\(512\)\s+COLLATE\s+utf8mb4_bin would keep the test honest about the collation without pinning whitespace. Same for the assertFalse(...contains("LONGTEXT COLLATE")) guards — the negative assertion is the one most likely to break on reformatting.

Addresses the review on agentscope-ai#3288: the previous commit only fixed tables that do
not exist yet, and CREATE TABLE IF NOT EXISTS is a silent no-op on a table that
already exists. A deployment created before the key columns pinned
utf8mb4_bin therefore kept the case-insensitive default and stayed exposed with
no signal at all.

Detection, not silent repair:

- AbstractJdbcDialect gains binaryCollationColumns() plus verifyBinaryCollation(),
  which reads INFORMATION_SCHEMA.COLUMNS and warns once per key column whose
  collation is not utf8mb4_bin, including the exact ALTER TABLE ... MODIFY ...
  COLLATE statement that fixes it. The default declaration is empty because
  PostgreSQL, H2 and SQLite already compare keys case-sensitively.
- AbstractJdbcDialectBuilder calls it right after the auto-create DDL, where the
  silent no-op would otherwise hide the drift.
- MysqlAgentStateStore gets ensureKeyColumnCollation() next to the existing
  ensureVersionColumn(), reusing the same check-then-act shape the review asked
  for.

It deliberately does not ALTER anything: changing a column's collation rewrites
the index and also changes read semantics (= and LIKE 'prefix%' become
case-sensitive), which is an operator decision rather than something a store
should do on startup. The docs now say so explicitly in both languages.

Also from the review:

- snapshot_id is a primary key and a caller-supplied identifier, so
  MysqlDialect.snapshotCreateTableDdls() pins utf8mb4_bin on it too instead of
  leaving it on the case-insensitive default.
- DialectSqlTests compares whitespace-normalised DDL so the assertions pin the
  column/collation contract rather than the column layout, and a new test pins
  the declared key columns against the ones the DDL actually fixes.

Tests: agentscope-extensions-jdbc 96/96, agentscope-extensions-mysql 12/12,
spotless:check clean. Detection is covered both ways: a column still on a
case-insensitive collation is reported, a migrated one is not, and an
unreadable INFORMATION_SCHEMA degrades to "nothing to report" instead of
failing the store.

Refs agentscope-ai#3217
@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in d6afa687. Thank you — the two warnings were the right call, and the "a fresh install gets the fix, an existing install is told loudly that it does not" framing is exactly what I aimed for.

Warning — MysqlDialect.java:78, no detection for pre-existing tables

AbstractJdbcDialect now has binaryCollationColumns() plus verifyBinaryCollation(), which reads INFORMATION_SCHEMA.COLUMNS and warns once per key column whose collation is not utf8mb4_bin, including the exact statement that fixes it. The builder calls it immediately after the auto-create DDL, which is precisely where the silent CREATE TABLE IF NOT EXISTS no-op hides the drift:

// CREATE TABLE IF NOT EXISTS is a no-op on an existing table, so the DDL above cannot fix
// a deployment whose key columns still carry a case-insensitive collation. Report the
// drift instead of leaving it silent; detection never alters a table.
dialect.verifyBinaryCollation();

binaryCollationColumns() defaults to empty, so PostgreSQL / H2 / SQLite are untouched.

I kept it detection-only rather than adding the ALTER variant you sketched. Your text allowed either, and I picked the conservative half for one reason worth stating explicitly: the ALTER rewrites the index and simultaneously changes read semantics, so doing it implicitly at store startup would be a surprise on a large table. If you would rather have the opt-in migrate mode driven by createIfNotExist, say so and I will add it as a separate flag rather than overloading the existing one.

Warning — MysqlAgentStateStore.java:250, and the read-side sentence

ensureKeyColumnCollation() sits next to the ensureVersionColumn() you pointed at and reuses that check-then-act shape. The read-side consequence is now spelled out in both docs, not just the migration command:

Be aware that the binary collation also changes read semantics on those two columns: comparisons and prefix lookups (session_id = ?, LIKE 'prefix%') become case-sensitive, so a lookup that previously matched SESS-1 for sess-1 will no longer match. ... a deployment which already stored two ids differing only in case has already lost one of those rows.

Info — sibling key tables

I covered snapshot_id instead of documenting around it: it is a primary key and a caller-supplied identifier, so snapshotCreateTableDdls() pins utf8mb4_bin on it as well. I did not find a lock_name column in the DDL — the MySQL lock path uses GET_LOCK(name, timeout) with a runtime advisory lock name, and AbstractJdbcDialect#lockTableName() / TableLease is the portable table-lock fallback, so there is no MySQL key column there to cover. If you had a different table in mind, point me at it.

Info — brittle assertions

DialectSqlTests now compares whitespace-normalised DDL, so the assertions pin the column/collation contract rather than the column layout:

private static String normalise(final String ddl) {
    return ddl.replaceAll("\\s+", " ").trim();
}

A new test also pins the declared key columns against the ones the DDL actually fixes, so the two cannot drift apart silently.

Verification

agentscope-extensions-jdbc   (full module)   96 / 96
agentscope-extensions-mysql  (full module)   12 / 12
spotless:check                               BUILD SUCCESS

Detection is tested both ways — a column still on a case-insensitive collation is reported, a migrated one is not — and an unreadable INFORMATION_SCHEMA degrades to "nothing to report" rather than failing the store. One caveat on the numbers: the module results are from JDK 25; CI's JDK 17 run on this commit is the authoritative one, and DangerousPathBypassTest in agentscope-core fails locally only because Windows refuses symlink creation without the privilege.

The drift detection added in d6afa68 was only covered indirectly: patch coverage
reported 51.5%, with AbstractJdbcDialect itself at 6.25%, because nothing
exercised verifyBinaryCollation against a catalog.

Adds AbstractJdbcDialectBinaryCollationTest, driving the INFORMATION_SCHEMA.COLUMNS
read with a mocked catalog so no MySQL is needed:

- only the columns that are not on utf8mb4_bin are reported
- every declared key column is reported when none has been migrated yet
- nothing is reported once every key column is migrated
- a catalog that returns no rows reports nothing (fresh install / table absent)
- an unreadable catalog degrades to "nothing to report" instead of failing
  store assembly
- dialects that compare keys case-sensitively read no catalog at all

The key columns are listed once in the test rather than read from the dialect,
because binaryCollationColumns() is protected and this test sits outside the
vendor package; DialectSqlTests asserts the same set against the generated DDL,
so the two have to move together.

Refs agentscope-ai#3217

@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

The new commit turns the silent half of the previous round's two warnings into a signal: AbstractJdbcDialect.binaryCollationColumns() / verifyBinaryCollation() read INFORMATION_SCHEMA.COLUMNS and warn once per MySQL key column still on a case-insensitive collation, MysqlAgentStateStore runs the same probe from its constructor next to ensureVersionColumn(), snapshot_id now pins utf8mb4_bin as well, and both doc pages gained the operator ALTER plus the read-semantics note. Every previous point is addressed in shape, and the docs match the detection-only behaviour. Not an approve yet: the warning itself mis-renders (7 placeholders against 10 arguments) and prints an ALTER MySQL rejects, and the dialect-side probe is skipped whenever autoCreateTable=false — the case that needs it most. Verdict: comment.

Previous round's findings

  • [Warning] MysqlDialect.java:78 no detection/migration for pre-existing tables — partially resolved (the probe and the declaration exist and are wired into the builder, but the call sits inside createTablesIfNeeded(), so it never runs with autoCreateTable=false; migration stays manual, which the PR argues for explicitly)
  • [Warning] MysqlAgentStateStore.java:250 reuse the existing check-then-act path, and state the read-side consequence — resolved (detection runs unconditionally at MysqlAgentStateStore.java:194-266; both docs now say that = and LIKE 'prefix%' become case-sensitive)
  • [Info] MysqlJdbcStoreDialect.java:29 sibling MySQL key tables — resolved (snapshot_id pins the collation at MysqlDialect.java:167 and is declared for the drift check; lock_name is moot because MysqlDialect.tryEnter uses GET_LOCK and never creates the table-lock table)
  • [Info] DialectSqlTests.java:136 whitespace exact assertions — resolved for that file via normalise(); the sibling MysqlJdbcStoreDialectTest still pins exact spacing (see findings)

Findings

  • [Warning] agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/AbstractJdbcDialect.java:179 — 7 {} vs 10 arguments; renders "is not utf8mb4_bin.item_key", and the printed ALTER ... MODIFY item_key COLLATE ... is invalid MySQL
  • [Warning] agentscope-extensions/agentscope-extensions-mysql/src/main/java/io/agentscope/extensions/mysql/state/MysqlAgentStateStore.java:250 — same placeholder/argument mismatch and same non-runnable ALTER
  • [Warning] agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/AbstractJdbcDialectBuilder.java:165 — the drift probe is unreachable when autoCreateTable=false
  • [Info] agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/AbstractJdbcDialect.java:172 — one getConnection()/query per column; MySQL-only SQL in the vendor-neutral base class
  • [Info] agentscope-extensions/agentscope-extensions-mysql/src/main/java/io/agentscope/extensions/mysql/state/MysqlAgentStateStore.java:88 — constant and probe duplicated across modules; public surface nothing outside the jdbc module can consume
  • [Info] agentscope-extensions/agentscope-extensions-jdbc/src/test/java/io/agentscope/extensions/jdbc/dialect/DialectSqlTests.java:195 — reflection helper avoidable (verified with javac); its justification comment is inaccurate
  • [Info] agentscope-extensions/agentscope-extensions-mysql/src/test/java/io/agentscope/extensions/mysql/state/MysqlAgentStateStoreTest.java:80 — positional next() sequence couples the whole file to constructor order; the guard at line 248 is dead code
  • [Info] agentscope-extensions/agentscope-extensions-mysql/src/test/java/io/agentscope/extensions/mysql/store/MysqlJdbcStoreDialectTest.java:55 — still pins the exact DDL padding instead of a normalised form

Verified good

  • Non-MySQL vendors stay untouched: binaryCollationColumns() defaults to List.of() (AbstractJdbcDialect.java:147) and no vendor except MySQL overrides it, so no probe SQL is issued for Postgres/H2/SQLite, and DialectSqlTests asserts both the empty declaration (lines 180-185) and that no COLLATE leaks into their DDL (lines 213-217)
  • Missing table or unreadable catalog degrade quietly: findCollation returns null when no row matches (line 206) and both probes catch SQLException and return instead of failing (lines 208-215, store 243-247), so build() and store construction cannot break — collationProbeFailureIsNotFatal covers the store side
  • The store probe inspects the object the DDL creates: TABLE_SCHEMA = databaseName / TABLE_NAME = tableName match getFullTableName()'s `database`.`table` (lines 225-233 vs 412-413), and equalsIgnoreCase is correct because MySQL collation names are case-insensitive
  • Docs are consistent with the implementation: en and zh both describe detection-only behaviour, call the migration an operator action, and their ALTER restates the type and NOT NULL (docs/v2/*/integration/session/mysql.md:89-97) — valid MySQL, unlike the log message; the "the store logs a warning" claim holds because the store probe runs on both createIfNotExist paths
  • The fixture change does not disturb the rest of the file: the two tests that do not re-stub next() (saveIfVersionZero*, lines 205-236) never read a ResultSet — insertIfAbsent/updateIfVersion call executeUpdate only — so the new trailing false cannot flip them
  • snapshot_id is a clean addition: only MysqlDialect.snapshotCreateTableDdls() changed (line 167), the other vendors' snapshot DDL is untouched, and the DDL/declaration pairing is pinned by mysqlKeyColumnsUseBinaryCollation and mysqlDeclaresTheKeyColumnsItPins

Automated review by github-manager-bot

}
for (BinaryCollationColumn each : mismatched) {
LOG.warn(
"Column {}.{} is not {}.{} — keys that differ only in letter case still collide"

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.

Placeholders and arguments do not match: this message has 7 {} and 10 arguments. Rendered against slf4j-api 2.0.17 it produces Column agentscope_store.item_key is not utf8mb4_bin.item_key — ... and silently discards the last three args — the stray {} after is not {} is the typo.

The emitted migration is not runnable either: MySQL requires the data type in MODIFY ("the definition must include the data type and all attributes", 8.0 manual), so the printed ALTER TABLE agentscope_store MODIFY item_key COLLATE utf8mb4_bin is a syntax error, while docs/v2/*/integration/session/mysql.md shows the correct form. Suggest carrying the column definition in BinaryCollationColumn and printing that, dropping the extra {}/args; a test asserting the formatted string would have caught both.

}
for (String column : stale) {
LOG.warn(
"Column {}.{} is not {}.{}. Keys that differ only in letter case still collide"

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.

Same two defects as AbstractJdbcDialect.verifyBinaryCollation(): 7 {} against 10 arguments, so the warning renders as Column agentscope_sessions.session_id is not utf8mb4_bin.session_id. and drops three args; and the printed ALTER TABLE agentscope_sessions MODIFY session_id COLLATE utf8mb4_bin is invalid MySQL — MODIFY must restate the type and attributes, e.g. MODIFY session_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL, which is exactly what the two doc pages now tell operators to run.

Both columns are known here (VARCHAR(255) NOT NULL), so the message can print a runnable statement; the three new tests assert return values only, so nothing pins the text.

// CREATE TABLE IF NOT EXISTS is a no-op on an existing table, so the DDL above cannot fix
// a deployment whose key columns still carry a case-insensitive collation. Report the
// drift instead of leaving it silent; detection never alters a table.
dialect.verifyBinaryCollation();

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.

createTablesIfNeeded() returns early at lines 149-151 when autoCreateTable == false, so this call never happens for dialects built with a pre-created schema — the population that actually owns a table with the old case-insensitive collation. A freshly auto-created table is already correct, so the check is skipped precisely where it matters most. MysqlAgentStateStore runs its equivalent probe unconditionally (line 195), regardless of createIfNotExist, so the two entry points disagree.

Suggest moving dialect.verifyBinaryCollation() into build() after bindDataSource(), outside the autoCreateTable branch: it is read-only, non-fatal, and a missing table yields no row, hence no warning.

public List<BinaryCollationColumn> verifyBinaryCollation() {
List<BinaryCollationColumn> mismatched = new ArrayList<>();
for (BinaryCollationColumn each : binaryCollationColumns()) {
String collation = findCollation(each);

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.

findCollation() opens a DataSource#getConnection() and issues one query per declared column — five checkouts and five round trips per build() for MySQL. One connection plus a single SELECT COLUMN_NAME, COLLATION_NAME ... AND COLUMN_NAME IN (?, ?) answers for every column, which is what MysqlAgentStateStore.findKeyColumnsWithNonBinaryCollation() already does (line 224). Consider hoisting the connection/query out of the loop so both probes share the same shape.

Also note this method embeds MySQL's INFORMATION_SCHEMA/DATABASE() SQL in the vendor-neutral base class: only MysqlDialect declares columns today, but any third-party dialect that declares columns inherits MySQL-only SQL.

* constant of the same name on {@code AbstractJdbcDialect}, which this module does not depend
* on; both name the same collation that the generated DDL pins.
*/
private static final String BINARY_COLLATION = "utf8mb4_bin";

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.

The constant and the ~40-line probe are duplicated because agentscope-extensions-mysql does not depend on agentscope-extensions-jdbc (poms: mysql declares only core/harness/sqlite; jdbc is a sibling module built independently). The Javadoc notes the mirroring, but the pair can still drift: a collation change applied in one module leaves the other silently checking (or creating) the old value.

Meanwhile verifyBinaryCollation(), BINARY_COLLATION and BinaryCollationColumn are public on AbstractJdbcDialect even though no consumer outside that module can reach them — the one other implementation had to copy them. Either add a cheap cross-check that the store's generated CREATE TABLE contains the literal the probe compares against, or keep the surface protected until a real consumer exists.

@SuppressWarnings("unchecked")
private static List<AbstractJdbcDialect.BinaryCollationColumn> declaredBinaryCollationColumns(
final AbstractJdbcDialect dialect) throws Exception {
Method method = AbstractJdbcDialect.class.getDeclaredMethod("binaryCollationColumns");

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.

The reflection helper is avoidable, and its justification is inaccurate. A protected member declared in AbstractJdbcDialect is reachable from this package — only the vendor-typed reference is rejected. Verified with javac: AbstractJdbcDialect d = new MysqlDialect(); d.binaryCollationColumns() compiles from io.agentscope.extensions.jdbc.dialect, while var d = new MysqlDialect(); d.binaryCollationColumns() fails with "has protected access in MysqlDialect".

otherDialectsDeclareNoBinaryCollationColumns already loops over AbstractJdbcDialect, so typing this local the same way lets both tests call the method directly, dropping the unchecked cast and the runtime-only NoSuchMethodException risk.

// ensureVersionColumn — the first three need resultSet.next() → true. The sequence must be
// finite: a trailing false also ends the ensureKeyColumnCollation row loop, whose
// "while (rs.next())" would otherwise never terminate on a mock that always says true.
when(resultSet.next()).thenReturn(true, true, true, false);

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.

This positional sequence couples every test in the file to the constructor's exact query count: the third true is consumed by ensureVersionColumn(), the false only ends the new collation row loop, and any reordering of the constructor's checks makes an unrelated assertion fail or silently pass. The three new tests paper over it with reset(resultSet), which also discards the @BeforeEach stubs.

Related: the guard at line 248, if (Mockito.mockingDetails(resultSet).getStubbings().isEmpty()), can never be true because setUp() always stubs resultSet.next(), so the lenient() branch is dead code and its comment describes a state that does not occur.

// overwrites the first.
String ddl = new MysqlJdbcStoreDialect().getCreateTableSql();

assertTrue(ddl.contains("namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL"));

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.

Same brittleness the previous round flagged in DialectSqlTests (now fixed there with normalise()): these assertions pin the column padding character-for-character, so a whitespace-only reflow of the DDL breaks a test that is about collation, not layout. normalise(ddl).contains("namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL") pins the contract instead — worth aligning this file with the sibling test.

…e probe

Addresses the second review round on agentscope-ai#3288.

Two real defects:

- The drift warning passed 10 arguments to a message with 7 placeholders, so it
  rendered "is not utf8mb4_bin.item_key" and printed an ALTER statement MySQL
  rejects. Both call sites (the dialect probe and MysqlAgentStateStore) are
  fixed; the placeholders now line up with the arguments and the closing sentence
  says what the operator should expect instead of being assembled from leftovers.
- The dialect probe was called from createTablesIfNeeded(), so it never ran when
  autoCreateTable=false - the caller who manages its own schema is the one that
  needs the warning most. It now runs from build(), after table creation, in both
  paths.

Moving the probe out surfaced a third defect: it only caught SQLException, so an
unchecked exception from a driver or pool escaped and failed build() - exactly
what the probe promises never to do. Both probes now treat any failure as
"collation unknown" and log it at debug level.

Remaining review points:

- the MySQL catalog query moves out of the vendor-neutral base class into
  attachedCollation(column), which MysqlDialect overrides; the base default
  returns null without querying, since INFORMATION_SCHEMA, COLLATION_NAME and
  DATABASE() are not portable
- BINARY_COLLATION is no longer public: nothing outside this module reads it
- DialectSqlTests now derives the pinned key columns from the DDL itself and
  asserts the declaration matches, so the two cannot drift apart; that replaces
  the reflection helper and a restated column list
- MysqlAgentStateStoreTest stubs the constructor's actual query sequence and the
  dead stubbing guard is gone
- MysqlJdbcStoreDialectTest compares whitespace-normalised DDL like its sibling

Tests: agentscope-extensions-jdbc 102/102, agentscope-extensions-mysql 12/12,
spotless:check clean.

Refs agentscope-ai#3217
@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the precise review — both warnings were correct and the second one pointed at the case that mattered most.

The warning rendered wrong, and printed an unusable ALTER

You were right on both counts: 10 arguments went to a 7-placeholder message, so it rendered is not utf8mb4_bin.item_key and the statement it printed was not valid MySQL. Fixed at both call sites (AbstractJdbcDialect.verifyBinaryCollation and MysqlAgentStateStore.findKeyColumnsWithNonBinaryCollation); the placeholders line up now. The docs' ALTER was already correct, and it is the only place I would trust for the statement — the log now builds it from the same three values.

The probe was unreachable when autoCreateTable=false

Also correct, and it was the worst possible place for that gap: a caller managing its own schema is exactly who needs to be told. verifyBinaryCollation() now runs from build() after table creation, in both paths.

A third defect appeared once the probe moved

With the probe running on every build(), two existing tests (detectsMysql, detectsMariaDb, which use a mock DataSource with no catalog stubs) failed:

Cannot invoke "java.sql.PreparedStatement.setString(int, String)" because "stmt" is null
  at MysqlDialect.attachedCollation
  at AbstractJdbcDialect.verifyBinaryCollation
  at AbstractJdbcDialectBuilder.build

The probe caught only SQLException, so an unchecked exception from a driver or pool escaped and failed build() — the opposite of what the probe promises. Both probes now treat any failure as "collation unknown" and log at debug level. I would not have found this without your point that the probe belongs on the build() path, so thank you.

On the reflection helper

Your instinct to remove it was right, and the change made the test better. One implementation detail worth recording: I first tried the direct call you suggested and javac rejected it —

DialectSqlTests.java:[176,18] binaryCollationColumns() 在 io.agentscope.extensions.jdbc.dialect.vendor.MysqlDialect 中是 protected 访问控制

DialectSqlTests shares a package with AbstractJdbcDialect, but MysqlDialect lives in the vendor child package, and protected access through a reference of the subclass type is only permitted from the subclass itself. So rather than keep reflection, I reworked the test to be stronger than the list it replaced: it now derives the pinned columns from the DDL with a regex, and asserts the declaration matches that set:

assertEquals(keyColumnsPinnedByDdl(d), AbstractJdbcDialect.keyColumnsOf(d));

A stray declaration or a DDL column that forgot its collation now fails the test, which the previous fixed list could not catch. keyColumnsOf is a package-local accessor, so nothing was widened for the test's benefit. If you would prefer the base hook to be public instead, I am happy to change it.

The remaining notes

  • The MySQL catalog query left the vendor-neutral base class: attachedCollation(column) is the hook, MysqlDialect overrides it, and the base default returns null without querying, since INFORMATION_SCHEMA, COLLATION_NAME and DATABASE() are not portable. The per-column query stays, with a comment on why batching is not worth it for a handful of columns on a probe that runs once per assembly; MysqlAgentStateStore already reads its two columns in a single query.
  • BINARY_COLLATION is package-private now — nothing outside the module read it.
  • MysqlAgentStateStoreTest stubs the constructor's actual query sequence (three next() reads, then the probe's row loop) instead of a positional guess, and the dead stubbing guard is gone.
  • MysqlJdbcStoreDialectTest compares whitespace-normalised DDL like its sibling.

Verification

agentscope-extensions-jdbc   (full module)   102 / 102
agentscope-extensions-mysql  (full module)    12 / 12
spotless:check                               BUILD SUCCESS

Everything above is in d5ba8ad9. The JDK 17 run in CI on that commit is the authoritative one (my local runs are JDK 25).

@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

The new commit fixes the two real defects from the previous round: both SLF4J warning messages now have matching placeholders and arguments, so the rendered migration statement is valid MySQL, and the dialect-side collation probe is moved from inside createTablesIfNeeded() into build() so it runs regardless of autoCreateTable. The MySQL-only INFORMATION_SCHEMA lookup moved into MysqlDialect.attachedCollation(), BINARY_COLLATION was narrowed to package-private, and the tests were tightened to derive expected key columns from the generated DDL and to normalise whitespace. Verdict: approve.

Previous round's findings

  • [Warning] MysqlDialect.java:78 no detection/migration for pre-existing tables — resolved (the probe now runs from build() after table creation in both autoCreateTable paths, catches RuntimeException, and the DDL/declaration pairing is asserted)
  • [Warning] MysqlAgentStateStore.java:250 reuse the existing check-then-act path, and state the read-side consequence — resolved (the probe runs unconditionally from the constructor, the placeholders match, and the warning explicitly states the read-semantics consequence)
  • [Info] MysqlJdbcStoreDialect.java:29 sibling MySQL key tables — resolved (snapshot_id now pins utf8mb4_bin and is declared in binaryCollationColumns())
  • [Info] DialectSqlTests.java:136 whitespace exact assertions — resolved (both DialectSqlTests and MysqlJdbcStoreDialectTest now normalise DDL whitespace)
  • [Warning] AbstractJdbcDialect.java:179 placeholder/argument mismatch — resolved (six {} placeholders match six arguments and the printed ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin is valid)
  • [Warning] MysqlAgentStateStore.java:250 placeholder/argument mismatch — resolved (same fix as the dialect-side warning)
  • [Warning] AbstractJdbcDialectBuilder.java:165 probe unreachable when autoCreateTable=false — resolved (verifyBinaryCollation() is called from build() after createTablesIfNeeded())
  • [Info] AbstractJdbcDialect.java:172 MySQL-only SQL in base class — resolved (catalog lookup moved to MysqlDialect.attachedCollation(); the base default returns null without querying)
  • [Info] MysqlAgentStateStore.java:88 constant and probe duplicated across modules — resolved (BINARY_COLLATION is now private in both modules; duplication is bounded by the existing module dependency structure)
  • [Info] DialectSqlTests.java:195 reflection helper avoidable — resolved (uses the new package-local AbstractJdbcDialect.keyColumnsOf() accessor)
  • [Info] MysqlAgentStateStoreTest.java:80 positional next() sequence — partially resolved (the stub sequence is updated for the new probe and the dead guard is removed, but the file still relies on a positional next() sequence tied to constructor order)
  • [Info] MysqlJdbcStoreDialectTest.java:55 exact DDL padding — resolved (uses normalise(ddl))

Findings

  • [Info] AbstractJdbcDialectBinaryCollationTest.java:60 — MYSQL_KEY_COLUMNS is declared and documented but never referenced in assertions, so it is dead code and can drift from the actual test inputs.

Verified good

  • Both warning messages now have six {} placeholders and six arguments, producing a runnable ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin statement.
  • AbstractJdbcDialectBuilder.build() calls verifyBinaryCollation() after createTablesIfNeeded(), so the probe runs even when autoCreateTable=false.
  • MysqlDialect.attachedCollation() overrides the vendor-neutral default and catches SQLException | RuntimeException, returning null so a failed probe never aborts dialect assembly.
  • MysqlAgentStateStore.findKeyColumnsWithNonBinaryCollation() also catches SQLException | RuntimeException and degrades to no warning.
  • Non-MySQL dialects keep binaryCollationColumns() defaulting to List.of() and issue no catalog queries.
  • DialectSqlTests derives expected key columns from the generated DDL via regex, preventing DDL/declaration drift.
  • MysqlAgentStateStoreTest no longer contains the dead Mockito.mockingDetails(resultSet).getStubbings().isEmpty() guard.

Automated review by github-manager-bot

* asserts the same set against the generated DDL, so a change to one has to touch both.
*/
private static final List<String> MYSQL_KEY_COLUMNS =
List.of("namespace_path", "item_key", "session_id", "state_key", "snapshot_id");

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.

MYSQL_KEY_COLUMNS is declared and documented but never used in any assertion or helper; it is dead code and can drift from the actual List.of(...) inputs in the tests. Remove it, or use it to drive the per-column collation lists so the constant stays honest.

@xzxiaoshan

xzxiaoshan commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

只修大小写问题,检测性补充,这些目前不要(文档写清楚即可)

bug 分析和 DDL 改动都没问题,utf8mb4_bin 不吃索引宽度的判断也对,这部分认可。
What 的表格漏了 snapshot_id,代码里是改了的。

主要意见:AbstractJdbcDialect 那 105 行的检测链,整个删掉。binaryCollationColumns、attachedCollation、verifyBinaryCollation、keyColumnsOf 这些,连同 builder 里的调用和新加的测试文件一起。理由不复杂:这套东西只有 MySQL 一家方言用得上。PG 等值比较本来就按字节,SQLite 连 INFORMATION_SCHEMA 都没有,H2 是库级 collation。lock 放基类是因为四家方言里两家覆写、两家用默认,这个四家里只有一家,进不了基类。也不必收进 MysqlDialect 留着,一条提示日志,不值得每次 build 都查一遍目录,还多出三份要人肉同步的键列清单。

存量表怎么迁移,文档里说清楚就行,描述里那段 ALTER TABLE 挠进 mysql.md,sessions、snapshot 两张表的迁移语句一并补上,中英文都补。MysqlAgentStateStore 构造器里 ensureKeyColumnCollation 那条链(连同 findKeyColumnsWithNonBinaryCollation)同样删,DDL 的 COLLATE 保留。

DialectSqlTests 里依赖 keyColumnsOf 的删掉:mysqlDeclaresTheKeyColumnsItPins、otherDialectsDeclareNoBinaryCollationColumns 两条,连带 keyColumnsPinnedByDdl 那组 helper。mysqlKeyColumnsUseBinaryCollation 和 mysqlPayloadColumnsKeepDefaultCollation 留着,一条保证键列都钉了 COLLATE,一条防 COLLATE 扩到其他方言和 payload,都有用。

改完再看。

@lzcGeek

…DL fix

Follows the review on agentscope-ai#3288: only MySQL needs this, so it does not belong in the
shared dialect base class.

Removed, as asked:

- AbstractJdbcDialect: binaryCollationColumns(), attachedCollation(),
  verifyBinaryCollation(), keyColumnsOf(), BINARY_COLLATION and the
  BinaryCollationColumn record
- the verifyBinaryCollation() call in AbstractJdbcDialectBuilder.build()
- MysqlDialect's declaration and its INFORMATION_SCHEMA lookup
- MysqlAgentStateStore.ensureKeyColumnCollation() and
  findKeyColumnsWithNonBinaryCollation(), including the constructor call
- AbstractJdbcDialectBinaryCollationTest
- DialectSqlTests: mysqlDeclaresTheKeyColumnsItPins and
  otherDialectsDeclareNoBinaryCollationColumns plus their helpers

The DDL keeps COLLATE utf8mb4_bin, which is the actual fix.

Migrating pre-existing tables is documented instead of probed at startup, in
docs/v2/{en,zh}/integration/session/mysql.md, with the statements for all three
keyed tables (agentscope_store, agentscope_sessions, agentscope_snapshots),
the read-semantics change, and the note that rows already overwritten are not
recoverable. The docs no longer claim the store logs a warning, since it no
longer does.

Kept, both still useful: mysqlKeyColumnsUseBinaryCollation pins the collation on
every key column, and mysqlPayloadColumnsKeepDefaultCollation keeps it from
spreading to payload columns or to the case-sensitive dialects.

Tests: agentscope-extensions-jdbc 94/94, agentscope-extensions-mysql 9/9,
spotless:check clean.

Refs agentscope-ai#3217
@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

明白了,已按此收敛,在 8ecc6ff9 里完成。

检测链整个删掉

  • AbstractJdbcDialect:binaryCollationColumns()、attachedCollation()、verifyBinaryCollation()、keyColumnsOf()、BINARY_COLLATION 常量与 BinaryCollationColumn record,共 −105 行
  • AbstractJdbcDialectBuilder.build() 里的调用
  • MysqlDialect 里的键列声明与 INFORMATION_SCHEMA 查询,−44 行
  • MysqlAgentStateStore 的 ensureKeyColumnCollation() 与 findKeyColumnsWithNonBinaryCollation()(含构造器调用),−74 行
  • AbstractJdbcDialectBinaryCollationTest 整个文件
  • DialectSqlTests 的 mysqlDeclaresTheKeyColumnsItPins、otherDialectsDeclareNoBinaryCollationColumns 及 keyColumnsPinnedByDdl 那组 helper

DDL 的 COLLATE 保留。你关于「四家方言只有一家用得上」的判断我接受——PG 按字节比较、SQLite 没有 INFORMATION_SCHEMA、H2 是库级 collation,继续放在基类里确实站不住;而每次 build 查一遍目录只换来一条提示日志,还要多维护三份键列清单,不划算。

存量表迁移写进文档

docs/v2/en/integration/session/mysql.md 与 docs/v2/zh/integration/session/mysql.md 新增「迁移在此改动之前创建的表 / Migrating tables created before this change」一节,三张键表都给了语句:

ALTER TABLE agentscope_store
    MODIFY namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL,
    MODIFY item_key       VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;

ALTER TABLE agentscope_sessions
    MODIFY session_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
    MODIFY state_key  VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;

ALTER TABLE agentscope_snapshots
    MODIFY snapshot_id VARCHAR(512) COLLATE utf8mb4_bin NOT NULL;

另附两点运维提示:该排序规则会改变读语义(=、LIKE 'prefix%' 变大小写敏感,建议空闲窗口执行);以及若迁移前已写入两个仅大小写不同的键,被覆盖的那行无法从表中恢复。同时说明 agentscope_snapshots 由 legacy 的 agentscope-extensions-mysql 快照客户端创建时不带二进制排序规则,由 agentscope-extensions-jdbc 方言创建时才带。

顺带修正:文档原有一句「store 检测到差异时会输出 warning」,检测删除后已不成立,一并去掉了。

保留的两条测试按你的判断留着:mysqlKeyColumnsUseBinaryCollation(保证每个键列都钉了 COLLATE)与 mysqlPayloadColumnsKeepDefaultCollation(防止扩散到 payload 列和其他已大小写敏感的方言)。

What 表格已补上 snapshot_id 那一行,谢谢指出。

本地:agentscope-extensions-jdbc 94/94、agentscope-extensions-mysql 9/9、spotless:check 通过。PR 现在是 8 文件 +202/−17。

@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


Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [WARNING] agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/vendor/MysqlDialect.java:53 — This snapshot DDL is the only changed MySQL table definition that does not establish utf8mb4 as its table character set. utf8mb4_bin is not valid for a VARCHAR inheriting a latin1 or utf8mb3 database default, so snapshot auto-creation now fails for such DataSources. Declare CHARACTER SET utf8mb4 on this column or table, and cover a non-utf8mb4 database default. (line outside diff)
  • [WARNING] docs/v2/en/integration/session/mysql.md:356 — MysqlDistributedStore still constructs the documented legacy JdbcSnapshotSpec, whose JdbcRemoteSnapshotClient continues to create a case-insensitive snapshot_id primary key. It is deprecated but still supported, so two snapshot IDs differing only by case can still overwrite one another for its normal users. Apply the same collation to that client and add a regression test rather than documenting the behavioral split. (line outside diff)

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

1、snapshot 建表 DDL 缺表级字符集 ——给它补上 ) DEFAULT CHARSET=utf8mb4。

2、legacy 的 MysqlDistributedStore → JdbcRemoteSnapshotClient 建的 snapshot_id 主键仍是大小写不敏感,别只在文档里解释这个分裂——直接给该 DDL 也加 字符集处理。

…snapshot key

Follows the second review on agentscope-ai#3288.

- MysqlDialect.snapshotCreateTableDdls() stated neither engine nor charset, so the
  table depended on the schema default. It now ends with ENGINE=InnoDB
  DEFAULT CHARSET=utf8mb4, like the store table.
- JdbcRemoteSnapshotClient.initSchema() created snapshot_id without the binary
  collation, so the legacy path - MysqlDistributedStore -> JdbcSnapshotSpec ->
  this client - still had the original defect: two snapshot ids differing only in
  letter case collided on the primary key and the second upload overwrote the
  first. That DDL now pins COLLATE utf8mb4_bin on snapshot_id and states the
  charset and engine as well, so both paths that create agentscope_snapshots
  agree instead of only documented to disagree.

The docs no longer describe that split, since it no longer exists: the migration
statements for the three keyed tables remain the only thing an older deployment
needs.

Tests: JdbcRemoteSnapshotClientTest captures the DDL issued during construction
and asserts the collation on snapshot_id, the untouched payload column and the
table charset. agentscope-extensions-jdbc 94/94, agentscope-extensions-mysql
11/11, spotless:check clean.

Refs agentscope-ai#3217
@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

两条都在 901fcb2a 里处理了。

1、snapshot 建表 DDL 补表级字符集

MysqlDialect.snapshotCreateTableDdls() 之前既没写 engine 也没写 charset,表的字符集取决于库级默认。现在收尾与 store 表一致:

+ "  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

2、legacy 的 snapshot_id 直接修,不再只写文档

你说得对,我上一轮把这条路径的分裂写进文档就算了,但 snapshot_id 是主键,'Snap-A' 与 'snap-a' 本来就是同一行、后写覆盖先写——这正是本 PR 要修的缺陷,留在 legacy 路径上等于没修完。现在 JdbcRemoteSnapshotClient.initSchema() 的 DDL:

+ "snapshot_id VARCHAR(512) COLLATE utf8mb4_bin NOT NULL PRIMARY KEY, "
...
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

这样 agentscope_snapshots 由 agentscope-extensions-jdbc 方言与 legacy 的 agentscope-extensions-mysql 快照客户端创建时规则一致;文档里那段「两条路径不一致」的说明已删掉,因为分裂不存在了,旧部署只需要执行那三条 ALTER。

测试:新增 JdbcRemoteSnapshotClientTest,用 Mockito 捕获构造函数实际执行的建表语句,断言 snapshot_id 钉了 COLLATE utf8mb4_bin、payload 列未被污染、表级 charset 与 engine 都在。

本地:agentscope-extensions-jdbc 94/94、agentscope-extensions-mysql 11/11、spotless:check 通过。PR 现在 10 文件 +291/−20。

@xzxiaoshan xzxiaoshan self-assigned this Sep 25, 2026

@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

The latest commit is sound: COLLATE utf8mb4_bin is valid across MySQL 5.7/8.0/MariaDB, every column clause is paired with an explicit table-level utf8mb4, all composite keys stay within the 3072-byte InnoDB limit, CREATE TABLE IF NOT EXISTS keeps the change idempotent, and the legacy snapshot id remains readable on resume — so nothing here blocks the fix itself. Leaving this as COMMENT rather than an approval because of one gap worth an explicit decision from the author: CREATE TABLE IF NOT EXISTS is a no-op on already-deployed tables, so existing installations silently keep the case-insensitive collation and the migration rests entirely on an operator running the documented ALTER statements, while an unused LOG field and a stale test comment still describe a collation probe that was never implemented.

Findings

  • [Warning] MysqlAgentStateStore.java:78 — dead LOG field plus a test comment describing a key-column collation probe that does not exist; either restore an idempotent probe/warning for existing tables or drop both.
  • [Info] MysqlDialect.java:78 — utf8mb4_bin is PAD SPACE, so trailing-space keys still collide; the comments and docs over-state the guarantee.
  • [Info] JdbcRemoteSnapshotClient.java:69 — the pinned charset doubles the snapshot PK to 2048 bytes; on legacy 767-byte row formats CREATE TABLE fails and initSchema() only logs a warning.
  • [Info] JdbcRemoteSnapshotClientTest.java:37 — the premise that no MySQL server is available in tests is inaccurate; a testcontainers mysql:8.0 suite already exists.

Suggestions

For the upgrade path, an ensureBinaryCollation() helper modelled on the existing ensureVersionColumn() (read INFORMATION_SCHEMA.COLUMNS.COLLATION_NAME, then MODIFY ... COLLATE utf8mb4_bin) would make the fix self-healing; adding ROW_FORMAT=DYNAMIC to the snapshot DDL removes the legacy-limit failure mode.


Automated review by github-manager-bot

*/
public class MysqlAgentStateStore implements AgentStateStore {

private static final Logger LOG = LoggerFactory.getLogger(MysqlAgentStateStore.class);

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.

LOG is declared here but never used — this file has no other occurrence of the identifier, and nothing in the diff logs. It pairs with MysqlAgentStateStoreTest.createTablePinsBinaryCollationOnKeyColumnsOnly (test lines 233-234), whose comment claims the constructor "verifies existence after creating", "checks the version column" and "finally probes the key-column collations, whose row loop needs false to stop". No such probe exists: with createIfNotExist=true the constructor only issues CREATE DATABASE, CREATE TABLE and the version COUNT(*) read. Either a planned "existing table is still case-insensitive -> ALTER" step was dropped, or the logger and the comment are leftovers.

This matters because CREATE TABLE IF NOT EXISTS is a no-op on every already-deployed table, so the class gives no runtime signal and the whole migration rests on the operator running the SQL in the docs. Consider an idempotent probe mirroring ensureVersionColumn() (read INFORMATION_SCHEMA.COLUMNS.COLLATION_NAME for session_id/state_key and MODIFY ... COLLATE utf8mb4_bin, or at minimum log a warning); otherwise drop LOG and correct the test comment.

+ " ("
+ " namespace_path VARCHAR(512) NOT NULL,"
+ " item_key VARCHAR(255) NOT NULL,"
+ " namespace_path VARCHAR(512) COLLATE utf8mb4_bin NOT NULL,"

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.

utf8mb4_bin is a PAD SPACE collation on both MySQL 5.7 and 8.0 (utf8mb4_0900_bin is the NO PAD variant and does not exist on 5.7/MariaDB — MySQL manual 12.8.5), so trailing spaces stay insignificant in comparisons and in unique-index enforcement: README.md and README.md still collide on this primary key and the second ON DUPLICATE KEY UPDATE still silently overwrites the first.

utf8mb4_bin is the right portable choice for the 5.7/8.0/MariaDB matrix, but the new comments (and the docs) frame the fix as making keys "exact identifiers"/case-sensitive only. Worth stating the residual trailing-space caveat explicitly, or trimming keys at the call site, so the guarantee is not over-read.

+ tableName
+ " ("
+ "snapshot_id VARCHAR(512) NOT NULL PRIMARY KEY, "
+ "snapshot_id VARCHAR(512) COLLATE utf8mb4_bin NOT NULL PRIMARY KEY, "

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.

Pinning the charset grows this primary key from 512 bytes to 2048 bytes: previously snapshot_id inherited the target schema's default charset (latin1 on a stock MySQL 5.7 server), so the 512-char key even fit the legacy 767-byte key limit; it now requires the 3072-byte InnoDB limit (ROW_FORMAT=DYNAMIC + innodb_large_prefix, which are the 5.7/8.0 defaults, so stock servers are fine).

On a server left on COMPACT/REDUNDANT row format or innodb_large_prefix=OFF, the CREATE TABLE now fails with ER_TOO_LONG_KEY — and initSchema() swallows that in its catch (SQLException) with only a log.warn, so the breakage would surface much later as an upload failure. Consider adding ROW_FORMAT=DYNAMIC to the DDL, or failing fast instead of warning.

*
* <p>{@code snapshot_id} is the primary key and a caller-supplied identifier, so its collation is the
* difference between two ids differing only in letter case being two rows or one — with the second
* upload silently overwriting the first. A MySQL server is not available to the suite, so the test

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.

The premise "A MySQL server is not available to the suite" does not hold for this repo: MysqlIntegrationTest (agentscope-extensions-jdbc, @Testcontainers, mysql:8.0) already exercises the MySQL dialect's store/sessions/snapshot DDL against a real server. These assertions only pin the DDL text — they would pass just as happily for a misspelled collation name or a statement MySQL rejects — and nothing tests the behaviour the change exists for (two ids differing only in case must be two rows).

Adding one case to MysqlIntegrationTest (upload Snap-A and snap-a, assert both are exists() / that two rows result) would execute the new COLLATE utf8mb4_bin DDL on MySQL 8.0 and pin the intent rather than the string.

@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Both parts of the warning are resolved:

  • The dead LOG field was removed in 12a43b6.
  • The stale test comment describing the removed collation probe was corrected in a43acdc2 — it now matches the actual constructor flow (existence check plus the INFORMATION_SCHEMA version-column check, no probe loop).

While editing the same file I also fixed the inaccurate "no MySQL server" premise in JdbcRemoteSnapshotClientTest, which now points to the testcontainers-based MysqlIntegrationTest (mysql:8.0) that already exists in agentscope-extensions-jdbc.

The two remaining infos (PAD SPACE wording, ROW_FORMAT) are noted but left as-is for now.

@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Both remaining infos are addressed in 3ff0e217: the snapshot DDL now sets ROW_FORMAT=DYNAMIC (removing the legacy 767-byte index-limit failure mode for the 2048-byte primary key, assertion updated accordingly), and the "exact identifiers" wording in the comments and the en/zh docs was corrected to "case-sensitive identifiers" with an explicit note that utf8mb4_bin is PAD SPACE.

@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

Follow-up review of 3ff0e217 (three commits since my previous review on 901fcb2a). Everything I left open is now closed, and the two remaining [Info] items were addressed rather than argued away:

previous finding status on 3ff0e217
dead Logger LOG + slf4j imports in MysqlAgentStateStore removed in 12a43b60
stale constructor/test comments describing a collation probe that no longer exists corrected in a43acdc2
comments and docs over-stating the guarantee of utf8mb4_bin 3ff0e217 documents the PAD SPACE caveat in MysqlAgentStateStore, in both the en and zh integration/session/mysql.md pages
2048-byte snapshot primary key vs the legacy InnoDB limit ROW_FORMAT=DYNAMIC added to the snapshot DDL (and pinned in the DDL assertion), which was the fix I suggested
no migration path for already-created tables the en/zh docs now carry explicit ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin statements for all three tables, which is the shape the maintainer asked for in thread

The DDL itself is still correct on the points I re-checked: utf8mb4_bin exists on MySQL 5.7/8.0 and MariaDB, the composite store key stays at (512 + 255) * 4 = 3068 bytes under the 3072-byte limit, and every column-level COLLATE is paired with a table-level DEFAULT CHARSET=utf8mb4, and CREATE TABLE IF NOT EXISTS keeps startup idempotent.

Findings

  • No blocking findings on this head. The only [Warning] I had raised (dead logger / stale probe comments) is resolved, and the migration is documented rather than probed — consistent with @xzxiaoshan's direction in thread.

Suggestions

build (windows-latest) failed and build (ubuntu-latest) was cancelled on the previous head a43acdc2; both are still running on 3ff0e217 at the time of this review. I am deliberately leaving this as a comment instead of an approval until a full green build lands on this head — nothing in the code needs changing for that, and if the Windows leg turns red for an unrelated reason, just rebase and ping me.


Automated review by github-manager-bot

@lzcGeek

lzcGeek commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

The full build went through cleanly on 3ff0e217 — both ubuntu and windows are green this time. For the record, the earlier a43acdc2 windows failure turned out to be the upstream ToolConfirmationCoordinatorTest (introduced in #3080) hitting a Mockito void-stub issue on Windows only, unrelated to the MySQL changes here.

Ready for another look when you have a moment.

@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-reviewing 3ff0e217 at the author's request after the CI legs finished. No new commits landed since my previous review, and no code change was needed — the only open item was a green build on this head.

CI on 3ff0e217 is now fully green: build (ubuntu-latest) (16m37s) and build (windows-latest) (28m52s) both pass, together with validate, Check License, Check Module Sync and codecov/patch. The Windows failure on the earlier head a43acdc2 is confirmed as the upstream ToolConfirmationCoordinatorTest Mockito void-stub issue introduced in #3080, unrelated to the MySQL collation change here.

Everything left open in previous rounds stays closed: dead logger removed, stale comments corrected, ROW_FORMAT=DYNAMIC pinned on the snapshot DDL, PAD SPACE caveat and the ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin migration documented in both en and zh session docs. license/cla is signed.

Approving — good to merge from a review standpoint.


Automated review by github-manager-bot

@xzxiaoshan
xzxiaoshan merged commit 2349533 into agentscope-ai:main Sep 26, 2026
7 checks passed
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified fix to the 2.0.x implementation and retain its
existing public contracts where the upstream kernel differs.

(cherry picked from commit 2349533)
Constraint: No AgentScope Service or SDK migration
Confidence: high
Not-tested: Whole-repository verification pending after lane integration
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]: MySQL key columns use a case-insensitive collation — agentscope_store silently overwrites keys differing only in case

5 participants