Repository navigation
fix(extensions): use a binary collation for MySQL key columns - #3288
Conversation
There was a problem hiding this comment.
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
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.
| + " (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
acd8ab4 to
4107686
Compare
|
Addressed the open finding in 4107686:
On the remaining note about 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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
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 anALTER TABLEfor theversioncolumn; 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," |
There was a problem hiding this comment.
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," |
There was a problem hiding this comment.
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," |
There was a problem hiding this comment.
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")); |
There was a problem hiding this comment.
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
|
Addressed in Warning —
// 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();
I kept it detection-only rather than adding the Warning —
Info — sibling key tables I covered Info — brittle assertions
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 Detection is tested both ways — a column still on a case-insensitive collation is reported, a migrated one is not — and an unreadable |
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
left a comment
There was a problem hiding this comment.
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:78no detection/migration for pre-existing tables — partially resolved (the probe and the declaration exist and are wired into the builder, but the call sits insidecreateTablesIfNeeded(), so it never runs withautoCreateTable=false; migration stays manual, which the PR argues for explicitly) - [Warning]
MysqlAgentStateStore.java:250reuse the existing check-then-act path, and state the read-side consequence — resolved (detection runs unconditionally atMysqlAgentStateStore.java:194-266; both docs now say that=andLIKE 'prefix%'become case-sensitive) - [Info]
MysqlJdbcStoreDialect.java:29sibling MySQL key tables — resolved (snapshot_idpins the collation atMysqlDialect.java:167and is declared for the drift check;lock_nameis moot becauseMysqlDialect.tryEnterusesGET_LOCKand never creates the table-lock table) - [Info]
DialectSqlTests.java:136whitespace exact assertions — resolved for that file vianormalise(); the siblingMysqlJdbcStoreDialectTeststill 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 printedALTER ... 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-runnableALTER - [Warning]
agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/AbstractJdbcDialectBuilder.java:165— the drift probe is unreachable whenautoCreateTable=false - [Info]
agentscope-extensions/agentscope-extensions-jdbc/src/main/java/io/agentscope/extensions/jdbc/dialect/AbstractJdbcDialect.java:172— onegetConnection()/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;publicsurface 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— positionalnext()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 toList.of()(AbstractJdbcDialect.java:147) and no vendor except MySQL overrides it, so no probe SQL is issued for Postgres/H2/SQLite, andDialectSqlTestsasserts both the empty declaration (lines 180-185) and that noCOLLATEleaks into their DDL (lines 213-217) - Missing table or unreadable catalog degrade quietly:
findCollationreturnsnullwhen no row matches (line 206) and both probes catchSQLExceptionand return instead of failing (lines 208-215, store 243-247), sobuild()and store construction cannot break —collationProbeFailureIsNotFatalcovers the store side - The store probe inspects the object the DDL creates:
TABLE_SCHEMA = databaseName/TABLE_NAME = tableNamematchgetFullTableName()'s`database`.`table`(lines 225-233 vs 412-413), andequalsIgnoreCaseis 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
ALTERrestates the type andNOT 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 bothcreateIfNotExistpaths - 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 aResultSet—insertIfAbsent/updateIfVersioncallexecuteUpdateonly — so the new trailingfalsecannot flip them snapshot_idis a clean addition: onlyMysqlDialect.snapshotCreateTableDdls()changed (line 167), the other vendors' snapshot DDL is untouched, and the DDL/declaration pairing is pinned bymysqlKeyColumnsUseBinaryCollationandmysqlDeclaresTheKeyColumnsItPins
Automated review by github-manager-bot
| } | ||
| for (BinaryCollationColumn each : mismatched) { | ||
| LOG.warn( | ||
| "Column {}.{} is not {}.{} — keys that differ only in letter case still collide" |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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")); |
There was a problem hiding this comment.
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
|
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 You were right on both counts: 10 arguments went to a 7-placeholder message, so it rendered The probe was unreachable when 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. A third defect appeared once the probe moved With the probe running on every The probe caught only 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
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. The remaining notes
Verification Everything above is in |
oss-maintainer
left a comment
There was a problem hiding this comment.
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:78no detection/migration for pre-existing tables — resolved (the probe now runs frombuild()after table creation in bothautoCreateTablepaths, catchesRuntimeException, and the DDL/declaration pairing is asserted) - [Warning]
MysqlAgentStateStore.java:250reuse 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:29sibling MySQL key tables — resolved (snapshot_idnow pinsutf8mb4_binand is declared inbinaryCollationColumns()) - [Info]
DialectSqlTests.java:136whitespace exact assertions — resolved (bothDialectSqlTestsandMysqlJdbcStoreDialectTestnow normalise DDL whitespace) - [Warning]
AbstractJdbcDialect.java:179placeholder/argument mismatch — resolved (six{}placeholders match six arguments and the printedALTER TABLE ... MODIFY ... COLLATE utf8mb4_binis valid) - [Warning]
MysqlAgentStateStore.java:250placeholder/argument mismatch — resolved (same fix as the dialect-side warning) - [Warning]
AbstractJdbcDialectBuilder.java:165probe unreachable whenautoCreateTable=false— resolved (verifyBinaryCollation()is called frombuild()aftercreateTablesIfNeeded()) - [Info]
AbstractJdbcDialect.java:172MySQL-only SQL in base class — resolved (catalog lookup moved toMysqlDialect.attachedCollation(); the base default returnsnullwithout querying) - [Info]
MysqlAgentStateStore.java:88constant and probe duplicated across modules — resolved (BINARY_COLLATIONis now private in both modules; duplication is bounded by the existing module dependency structure) - [Info]
DialectSqlTests.java:195reflection helper avoidable — resolved (uses the new package-localAbstractJdbcDialect.keyColumnsOf()accessor) - [Info]
MysqlAgentStateStoreTest.java:80positionalnext()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 positionalnext()sequence tied to constructor order) - [Info]
MysqlJdbcStoreDialectTest.java:55exact DDL padding — resolved (usesnormalise(ddl))
Findings
- [Info]
AbstractJdbcDialectBinaryCollationTest.java:60—MYSQL_KEY_COLUMNSis 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 runnableALTER TABLE ... MODIFY ... COLLATE utf8mb4_binstatement. AbstractJdbcDialectBuilder.build()callsverifyBinaryCollation()aftercreateTablesIfNeeded(), so the probe runs even whenautoCreateTable=false.MysqlDialect.attachedCollation()overrides the vendor-neutral default and catchesSQLException | RuntimeException, returningnullso a failed probe never aborts dialect assembly.MysqlAgentStateStore.findKeyColumnsWithNonBinaryCollation()also catchesSQLException | RuntimeExceptionand degrades to no warning.- Non-MySQL dialects keep
binaryCollationColumns()defaulting toList.of()and issue no catalog queries. DialectSqlTestsderives expected key columns from the generated DDL via regex, preventing DDL/declaration drift.MysqlAgentStateStoreTestno longer contains the deadMockito.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"); |
There was a problem hiding this comment.
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.
只修大小写问题,检测性补充,这些目前不要(文档写清楚即可)bug 分析和 DDL 改动都没问题,utf8mb4_bin 不吃索引宽度的判断也对,这部分认可。 主要意见: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,都有用。 改完再看。 |
…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
|
明白了,已按此收敛,在 检测链整个删掉
DDL 的 存量表迁移写进文档
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;另附两点运维提示:该排序规则会改变读语义( 顺带修正:文档原有一句「store 检测到差异时会输出 warning」,检测删除后已不成立,一并去掉了。 保留的两条测试按你的判断留着:
本地: |
oss-maintainer
left a comment
There was a problem hiding this comment.
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 establishutf8mb4as its table character set.utf8mb4_binis not valid for a VARCHAR inheriting a latin1 or utf8mb3 database default, so snapshot auto-creation now fails for such DataSources. DeclareCHARACTER SET utf8mb4on this column or table, and cover a non-utf8mb4 database default. (line outside diff) - [WARNING]
docs/v2/en/integration/session/mysql.md:356—MysqlDistributedStorestill constructs the documented legacyJdbcSnapshotSpec, whoseJdbcRemoteSnapshotClientcontinues to create a case-insensitivesnapshot_idprimary 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)
|
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
|
两条都在 1、snapshot 建表 DDL 补表级字符集
+ " created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");2、legacy 的 snapshot_id 直接修,不再只写文档 你说得对,我上一轮把这条路径的分裂写进文档就算了,但 + "snapshot_id VARCHAR(512) COLLATE utf8mb4_bin NOT NULL PRIMARY KEY, "
...
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";这样 测试:新增 本地: |
oss-maintainer
left a comment
There was a problem hiding this comment.
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— deadLOGfield 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_binis 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 formatsCREATE TABLEfails andinitSchema()only logs a warning. - [Info]
JdbcRemoteSnapshotClientTest.java:37— the premise that no MySQL server is available in tests is inaccurate; a testcontainersmysql:8.0suite 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); |
There was a problem hiding this comment.
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," |
There was a problem hiding this comment.
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, " |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
|
Both parts of the warning are resolved:
While editing the same file I also fixed the inaccurate "no MySQL server" premise in The two remaining infos (PAD SPACE wording, |
|
Both remaining infos are addressed in |
oss-maintainer
left a comment
There was a problem hiding this comment.
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
|
The full build went through cleanly on Ready for another look when you have a moment. |
oss-maintainer
left a comment
There was a problem hiding this comment.
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
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

What
Pin
COLLATE utf8mb4_binon the MySQL key columns only, so that keys are compared case-sensitively the way the other backends already compare them:MysqlDialect.storeCreateTableDdls()agentscope_storenamespace_path,item_keyMysqlDialect.sessionStateCreateTableDdls()agentscope_sessionssession_id,state_keyMysqlDialect.snapshotCreateTableDdls()agentscope_snapshotssnapshot_id(+ explicitENGINE=InnoDB DEFAULT CHARSET=utf8mb4)MysqlJdbcStoreDialect.getCreateTableSql()namespace_path,item_keyMysqlAgentStateStore.createTableIfNotExist()session_id,state_keyJdbcRemoteSnapshotClient.initSchema()snapshot_id(+ explicit charset and engine)Payload columns (
value_json,state_data,data) stay on the table default.Why
DEFAULT CHARSET=utf8mb4withoutCOLLATEresolves to the charset default, which is case- and accent-insensitive:utf8mb4_0900_ai_cion MySQL 8.0+,utf8mb4_general_cion 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)thenput(ns, "readme.md", b)takes theON DUPLICATE KEY UPDATEbranch —ais silently lost, with no error, warning or version conflict.agentscope_sessionspackssession_idas{userSegment}:{sessionId}, so two users whose ids differ only in case share session state.snapshot_idis 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_binstays 4 bytes per character, so the index-width budget is unchanged:(512 + 255) * 4 = 3068bytes, 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
AbstractJdbcDialectprobe that readINFORMATION_SCHEMAon everybuild()to warn about pre-existing tables. That is gone, together with theMysqlAgentStateStoreconstructor probe, thebinaryCollationColumns()/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:The docs also record that the collation changes read semantics (
=andLIKE '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 createagentscope_snapshotsnow 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_sessionindexes, and theTIMESTAMP->DATETIMEleftovers plus theversion BIGINT NOT NULL DEFAULT 0in the legacy sessions DDL versusDEFAULT 1inensureVersionColumn().How verified
Local, MySQL-collation-specific behaviour cannot be covered by the H2/SQLite suites, so the tests assert the generated DDL:
DialectSqlTests.mysqlKeyColumnsUseBinaryCollationasserts the per-columnCOLLATEonnamespace_path,item_key,session_id,state_keyandsnapshot_id, compared against whitespace-normalised DDL.DialectSqlTests.mysqlPayloadColumnsKeepDefaultCollationasserts payload columns keep the table default and that noCOLLATEleaks into the PostgreSQL / H2 / SQLite DDL, which are already case-sensitive.MysqlJdbcStoreDialectTest,MysqlAgentStateStoreTestandJdbcRemoteSnapshotClientTestpin the three legacy DDLs the same way.I did not add a MySQL-gated integration test that writes
README.md/readme.mdand 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