Skip to content

[Bug]: MySQL key columns use a case-insensitive collation — agentscope_store silently overwrites keys differing only in case #3217

Closed

Description

@zhangqian7741

Describe the bug

MysqlDialect.storeCreateTableDdls() (L66-81) creates the KV store table with no explicit COLLATE:

CREATE TABLE IF NOT EXISTS agentscope_store (
  namespace_path VARCHAR(512)  NOT NULL,
  item_key       VARCHAR(255)  NOT NULL,
  value_json     LONGTEXT      NOT NULL,
  version        BIGINT        NOT NULL,
  updated_at     BIGINT        NOT NULL,
  PRIMARY KEY (namespace_path, item_key),
  INDEX idx_namespace (namespace_path)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

DEFAULT CHARSET=utf8mb4 without COLLATE resolves to the charset's default collation — utf8mb4_0900_ai_ci on MySQL 8.0+, utf8mb4_general_ci on MySQL 5.7 and MariaDB. All of these are case-insensitive, and utf8mb4_0900_ai_ci is additionally accent-insensitive.

Both primary-key columns hold arbitrary caller-supplied strings:

// JdbcStore L109
public void put(List<String> namespace, String key, Map<String, Object> value) {

So on MySQL:

  • put(ns, "README.md", a) followed by put(ns, "readme.md", b) produces one row. a is silently lost — no error, no warning, no version conflict.
  • storeSearch filters with WHERE namespace_path LIKE ?, so a search scoped to namespace ["Foo"] also returns items written under ["foo"].
  • On MySQL 8.0, résumé and resume are the same key.

agentscope_sessions has the same problem, via an explicit COLLATE utf8mb4_unicode_ci (MysqlDialect L118) — also a _ci collation. Per docs/v2/en/integration/session/mysql.md, session_id packs the user id as {userSegment}:{sessionId}, so two users whose ids differ only in case would share session state.

The other three dialects are case-sensitive: Postgres under a deterministic collation, H2, and SQLite's default BINARY. The result is that identical application code produces different results depending on the backend, which works against the shared-dialect goal of #2503.

Expected behavior

Key columns should carry a binary / case-sensitive collation, applied per column so that payload columns (value_json, state_data) keep a normal collation:

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

and likewise for session_id / state_key. (utf8mb4_0900_as_cs is an alternative on 8.0+.)

This does not affect the index-width budget from #1765 / #1781: utf8mb4_bin is still 4 bytes per character, so (512 + 255) * 4 = 3068 bytes is unchanged and stays under the InnoDB 3072-byte limit.


Secondary: the MySQL DDL is not consistent across the codebase

While tracing the above I inventoried every hand-written MySQL CREATE TABLE in the repo. There are 9, using 4 different combinations of table options and 3 different representations of time:

Table Source ENGINE charset syntax COLLATE time column
agentscope_store MysqlDialect L70-80 ENGINE=InnoDB DEFAULT CHARSET= — BIGINT epoch
agentscope_sessions MysqlDialect L107-119 — DEFAULT CHARACTER SET utf8mb4_unicode_ci DATETIME
agentscope_snapshots MysqlDialect L153-160 — — — TIMESTAMP
agentscope_distributed_locks AbstractJdbcDialect L300-303 — — — —
agentscope_store (legacy) MysqlJdbcStoreDialect L24-31 ENGINE=InnoDB DEFAULT CHARSET= — BIGINT epoch
agentscope_sessions (legacy) MysqlAgentStateStore L240-247 — DEFAULT CHARACTER SET utf8mb4_unicode_ci DATETIME
snapshots (legacy) JdbcRemoteSnapshotClient L63-69 — — — TIMESTAMP
agentscope_skills MysqlSkillRepository L299-307 — DEFAULT CHARACTER SET utf8mb4_unicode_ci TIMESTAMP
agentscope_skill_resources MysqlSkillRepository L311-320 — DEFAULT CHARACTER SET utf8mb4_unicode_ci TIMESTAMP

Three things follow from this.

1. The TIMESTAMP → DATETIME decision from #991 / #1006 was only applied to one table.

#1006 ("Use DATETIME instead of TIMESTAMP for mysql field") closed #991, but the snapshot tables and both skill tables still use TIMESTAMP, which caps at 2038-01-19 03:14:07 UTC and is silently converted according to the session time_zone variable — unlike DATETIME. Worth noting too that #991 specifically asked for datetime(3) to preserve milliseconds; the merged change used second-precision DATETIME, so the original request is only partly satisfied.

2. idx_namespace and idx_session are redundant.

INDEX idx_namespace (namespace_path) duplicates the leftmost prefix of PRIMARY KEY (namespace_path, item_key), and INDEX idx_session (session_id) duplicates the leftmost prefix of PRIMARY KEY (session_id, state_key, item_index). In both cases the primary key already serves any range scan or LIKE 'prefix%' on the leading column, so these indexes only add write amplification and storage.

The comments that justify them are inaccurate:

  • SessionStateDialect L31-34 — "session_id LIKE 'prefix%' queries require an index on session_id"
  • SqliteDialect L54-55 — "SQLite cannot express a secondary index inside CREATE TABLE; without it, the LIKE prefix search degrades to a full table scan"

This applies to all four dialects — MySQL inlines the indexes, while Postgres / H2 / SQLite emit a separate CREATE INDEX IF NOT EXISTS — so there are 8 redundant indexes in total. Note that DialectSqlTests L148-189 asserts their presence, so removing them requires updating those assertions.

3. The documented schema is missing columns the code actually requires.

docs/v2/en/integration/session/mysql.md L75-83 and its zh counterpart both document agentscope_sessions without the version column and without INDEX idx_session. MysqlAgentStateStore's own class Javadoc (L49-57) has the same omission. A user who pre-creates the table from the docs and runs with createIfNotExist=false ends up with an incomplete table — and #3213 explains why that mode matters in environments where the application account has no DDL privileges.


Root cause

Unlike the Go service under agentscope-service/aistio, which has 111 numbered up/down migration files, the Java side has no migration mechanism at all. Every DDL is a concatenated Java string executed behind CREATE TABLE IF NOT EXISTS, which means any schema evolution is silently skipped on tables that already exist. That is the common thread behind this issue, #3162, and #3213.

Environment

  • AgentScope-Java Version: main @ 5b99145
  • Modules: agentscope-extensions-jdbc, agentscope-extensions-mysql, agentscope-extensions-skill-mysql-repository

Activity

  1. oss-maintainer commented on Sep 20, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed | Severity: high

    Verified against main @ 5b99145. The primary claim (case-insensitive key collation on MySQL) reproduces from the DDL as written, and the divergence from the other three dialects is real. Of the secondary inventory claims, four verified and one is only partly supported — details below.

    Root cause

    MysqlDialect.storeCreateTableDdls() (agentscope-extensions/agentscope-extensions-jdbc/.../dialect/vendor/MysqlDialect.java:70-80) emits DEFAULT CHARSET=utf8mb4 with no COLLATE, so namespace_path / item_key inherit the charset default — utf8mb4_0900_ai_ci on MySQL 8. Both are arbitrary caller-supplied strings (JdbcStore.put(List<String> namespace, String key, ...) at :109), so the composite PK is case- and accent-insensitive: put(ns,"README.md",a) then put(ns,"readme.md",b) hits the ON DUPLICATE KEY UPDATE branch and loses a with no error, warning, or version conflict. The legacy MysqlJdbcStoreDialect.getCreateTableSql() (agentscope-extensions-mysql/.../store/MysqlJdbcStoreDialect.java:22-31) has the identical shape.

    agentscope_sessions is worse only in the sense that it is explicit rather than accidental: MysqlDialect.java:108-119 and MysqlAgentStateStore.createTableIfNotExist() (:247) both pin COLLATE utf8mb4_unicode_ci on (session_id, state_key, item_index). Since session_id packs {userSegment}:{sessionId} (per docs/v2/en/integration/session/mysql.md), two users whose ids differ only in case share session state.

    Backend divergence — confirmed

    Dialect Key column collation Case-sensitive?
    MysqlDialect.java:70-80 / :108-119 utf8mb4_0900_ai_ci (implicit) / utf8mb4_unicode_ci (explicit) no
    PostgresDialect.java:55-73 / :100-120 plain VARCHAR, DB default yes
    H2Dialect.java:42-59 / :84-104 plain VARCHAR, H2 default yes
    SqliteDialect.java:43-60 / :85-104 TEXT + default BINARY yes

    So identical application code returns different rows depending on the backend — which is exactly what the shared-dialect work (#2503) is meant to prevent.

    Assessment of the secondary claims

    • Inconsistent hand-written MySQL DDL / TIMESTAMP vs DATETIME: partly verified. The inconsistency is real — MysqlDialect.snapshotCreateTableDdls() (:152-161), JdbcRemoteSnapshotClient.initSchema() (:61-69), and MysqlSkillRepository.createTablesIfNotExist() (:298-320) still use TIMESTAMP while session tables use DATETIME (MysqlDialect.java:114-115, MysqlAgentStateStore.java:244-247) and the store uses BIGINT epoch. The exact count of 9 tables and the attribution to [Feature]: MysqlSession should use datetime(3) instead of timestamp to create table #991/feat(session): Improve mysql session sql #1006 are not derivable from source alone. I'd treat this as a separate follow-up rather than mixing it into the collation fix.
    • Redundant idx_namespace / idx_session: verified. MysqlDialect.java:79 and :117 index the leftmost PK column, and DialectSqlTests.mysqlDdlInlinesIndexes() (:147-161) asserts their presence, so removal needs the assertions updated.
    • Docs missing the version column: verified. docs/v2/en/integration/session/mysql.md:74-84 omits version, which the code requires.
    • One nuance the report does not mention: MysqlAgentStateStore.createTableIfNotExist() writes version BIGINT NOT NULL DEFAULT 0 (:244) and only the runtime ensureVersionColumn() uses DEFAULT 1 (:197). Per [Bug]: ensureVersionColumn() backfills version=0, the same sentinel getVersioned() uses for "row absent" — every pre-existing session hits a phantom CAS conflict after upgrading #3162, 0 is the "row absent" sentinel, so the fresh-install DDL in the legacy class is itself inconsistent with the migration path — worth folding into whatever change touches these tables.

    Fix direction

    1. Add per-column COLLATE utf8mb4_bin to the key columns only (namespace_path, item_key; session_id, state_key) in MysqlDialect, leaving payload columns (value_json, state_data) on the table default. utf8mb4_bin stays 4 bytes/char, so the index-width budget from [Bug]:Failed to initialize JdbcStore schema for table agentscope_store #1765/fix(mysql): 修复 JdbcStore 在 utf8mb4 下初始化表失败 #1781 is unchanged: (512 + 255) * 4 = 3068 bytes, still under InnoDB's 3072.
    2. Same fix for the legacy MysqlJdbcStoreDialect / MysqlAgentStateStore DDLs so both paths agree, and note in the release notes that existing MySQL tables are not fixed by a DDL change — ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin is an operator action, and any deployment that already wrote case-variant keys has already lost data. That upgrade note is arguably the more important half of this change.
    3. Decide explicitly whether the redundant indexes and the TIMESTAMP → DATETIME leftovers are in scope; if not, file them separately so the collation fix stays reviewable.
    4. Tests: extend DialectSqlTests to assert the per-column COLLATE on key columns only, and add a MySQL-gated case that writes README.md / readme.md and asserts two rows. (H2/SQLite suite coverage will not catch this — the bug is MySQL-collation-specific.)

    Related: #3216 (same tables, missing version migration on the agentscope-extensions-jdbc path), #3213 (ensureVersionColumn DDL permissions), #2503 (shared dialect tracking), #1765/#1781 (index width).

    If you'd like an automated fix PR from this direction, reply /approve. To change the approach — e.g. utf8mb4_0900_as_cs instead of utf8mb4_bin, scoping to agentscope_store only, or including the index/DATETIME cleanup — reply /revise <what to change>. To skip, reply /reject.


    Automated evaluation by github-manager-bot

  2. added
    bug
    area/ext/memory
    on Sep 20, 2026
  3. oss-maintainer commented on Sep 23, 2026

    @oss-maintainer
    Collaborator

    Status: 72 h feedback window expired — no automated PR will be generated, the proposal window here is closed

    The evaluation CTA above (5750306036, posted 2026-09-20T14:08:10Z) reached its 72-hour feedback limit at 2026-09-23T14:08:10Z with no own-line /approve, /revise, or /reject command in the thread, so per our workflow we skip PR generation and no competing PR will be filed from this proposal window. No action is needed from anyone.

    This is a timing stand-down, not a verdict on the report. The thread did get a follow-up question — 5790561079 (2026-09-23T07:05:46Z, @samanthacartaya) asks whether deployments use a case-sensitive collation or a binary compare for store keys — but it carried no directive token and did not claim the fix, so there was nothing for us to act on within the window, and no linked PR exists for this issue as of this check.

    The evaluation itself stands as recorded: the agentscope_store key columns inherit MySQL's default utf8mb4_0900_ai_ci collation, so two keys differing only in letter case hash to the same row and the second write silently overwrites the first — a lost update rather than an error. The reported direction was a case-sensitive collation or a binary comparison on the key column, plus an explicit collision test.

    If a maintainer or contributor would like an automated fix proposal for this after all, leave a one-line approve on this issue and the spec will be regenerated.

    Automated by github-manager-bot

  4. lzcGeek commented on Sep 24, 2026

    @lzcGeek
    Contributor

    I would like to work on this and can submit a PR.

    The evaluation matches what I found locally, and I agree with the scoping point #3: this PR stays on collation only, and the redundant idx_namespace / idx_session indexes and the TIMESTAMP -> DATETIME leftovers are left for separate issues.

    Scope I would submit, unless you want it narrower:

    1. MysqlDialect - COLLATE utf8mb4_bin on the key columns only (namespace_path, item_key; session_id, state_key), payload columns stay on the table default. Verified the index-width budget is unchanged: (512 + 255) * 4 = 3068, still under InnoDB's 3072.
    2. The legacy path, so both paths agree as the evaluation asks: MysqlJdbcStoreDialect.getCreateTableSql() (store) and MysqlAgentStateStore.createTableIfNotExist() (sessions, currently explicit utf8mb4_unicode_ci).
    3. Tests: extend DialectSqlTests to assert the per-column COLLATE on key columns only, plus a guard that no COLLATE leaks into the Postgres / H2 / SQLite DDL, since those are already case-sensitive.

    Two notes:

    • On the upgrade half: I could not find a release-notes file with an "Unreleased" section (docs/v2/*/docs/others/release-notes.md is organised per released version), so rather than invent an entry I plan to carry the required operator action in the PR description: existing MySQL tables are not fixed by a DDL change, ALTER TABLE ... MODIFY ... COLLATE utf8mb4_bin is an operator action, and any deployment that already wrote case-variant keys has already lost data. If you would rather have that in the docs, tell me which file to touch.
    • On approach: the evaluation suggests utf8mb4_bin; I have kept that. If you prefer utf8mb4_0900_as_cs, it is a one-line change per column.

    Local verification so far: DialectSqlTests goes from 27 successful / 1 failed (new assertion red) to 28 successful / 0 failed with the fix, and spotless:check passes.

  5. added 7 commits that reference this issue on Sep 24, 2026
    acd8ab4
    4107686
    d6afa68
    2984253
    d5ba8ad
    8ecc6ff
    901fcb2
  6. added a commit that references this issue on Sep 26, 2026
    2349533
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/ext/memorybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions