Skip to content

fix(driver-sql): MySQL autonumber issues duplicate numbers when the first rows of an object are written concurrently #31608

Closed

Description

@objectstack-fleet

epic:#3814#1 · os-zhuang · session_01QUs3BrVu5TqwtmuhsjdEvM
Filing gate: ③ maintainer-dispatched task (child of #3814). Maintainer, (2026-11-08, 16:25 UTC): 「继续,现在派第二批」 (gate 1 after the card 0 inventory, cloud#3868 comment 6723322368).

Single-node defect S3, found by card 0 of #3814 (cloud#3868 comment 6723322368, V1b). Maintainer ruling D2 (2026-11-08, 16:25 UTC): 「现在修,按普通 bug 卡」. This is a single-node bug fix, so it is NOT bound by #3814's R3.

Problem (measured, MySQL 8.0)

On a new object, concurrent creates produced duplicate autonumbers every run: two processes gave 11-18 duplicates plus up to 21 ER_LOCK_DEADLOCK create errors, and a single process at concurrency 16 also gave 8/8/0 duplicates. A warm sequence passes. There is no unique index on the autonumber column. The likely cause (not proven) is that a deadlock rolls back past the savepoint during the cold seed. Postgres 16 passes the same probe (SELECT … FOR UPDATE). The probe scripts are in project files issue-3868/.

Do

  1. Root-cause the cold-seed path in driver-sql for MySQL and make it atomic (for example, seed the sequence row with an insert-ignore before the locking read, and retry the whole issue on deadlock).
  2. Consider the unique index the autonumber contract implies; if adding it is a schema change for existing installs, say so in the PR and keep it to new objects unless the migration is safe.
  3. Tests: the concurrent cold-seed probe on MySQL gives 1..N with no duplicates; Postgres unchanged.

Done when

PR merged; concurrent first writes on MySQL never duplicate an autonumber.

Activity

  1. added
    bug
    pm:queue
    domain:server
    on Nov 8, 2026
  2. objectstack-fleet commented on Nov 8, 2026

    @objectstack-fleet
    ContributorAuthor

    triage#1 · os-zhuang · session_01AavokzJ5DndAwitDXvKy4U

    Path: none

    Triage: confirmed · domain:server · p3 · pm:queue · 2026-11-08T17:03Z

    ⛔ Not a claim.

    • Lane: domain:server, for driver-sql (MySQL autonumber).
    • Grade: p3 as the seat graded it, on the maintainer's D2 (「现在修,按普通 bug 卡」). Triage notes duplicate autonumbers are a data-integrity defect. If it is confirmed on a warm production object (not only a cold sequence), raise it to p2.

    Generated by Claude Code

  3. added
    pm:dispatched
    and removed
    pm:queue
    on Nov 8, 2026
  4. objectstack-fleet commented on Nov 8, 2026

    @objectstack-fleet
    ContributorAuthor

    domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM

    Claim: PM loop round 5 · 2026-11-08T21:35Z
    Session: session_01ADHkmSaagzgP2FPBJq6Cre (card thread, dev) · seat session_01ADHkmQKZzp4DLtqiCkZZRM
    Account: os-steve
    Branch: claude/project-thread-867elb
    Worktree: objectstack-issue-31608
    Domain: domain:server
    Seat: domain:server#2
    File surface: packages/drivers/driver-sql/src/sql-driver-autonumber.ts, a new MySQL live cold-race test beside the #8269 one, root .changeset/. ⛔ No packages/spec/**, ui/**, helm/
    Container & model: M (live MySQL 8 cell), mode:thread, model: default tier, effort: high
    Clause-②: no
    Metadata-protocol: none
    Responsibility: epic #3814 card 0 single-node defect S3; maintainer D2 「现在修,按普通 bug 卡」, not bound by R3
    Thread-read: 6724416809
    Premise: as filed, cause unproven; read at claim on origin/main 5d1382a5: the cold seed in getNextSequenceValue is a savepointed SELECT … FOR UPDATE then INSERT with unique-violation recovery (#8269); the dev measures the MySQL deadlock path first
    Serial constraints cleared: no open PR touches sql-driver-autonumber.ts

    Scope: Fixes #31608. Root-cause the MySQL cold-seed duplicate on a live MySQL 8 cell, then make the one cold-seed path atomic for every dialect (idempotent seed before the locking read; whole-issue retry on deadlock only where the driver owns the transaction). Postgres and SQLite unchanged; no unique index on existing installs. Order: /mnt/project-files/server-seat2/standard-order.md + /mnt/project-files/server-seat2/31608-delta.md. Summons: the maintainer's 「并发都是5」 (project chat, 2026-11-08T16:13Z).

  5. objectstack-fleet commented on Nov 8, 2026

    @objectstack-fleet
    ContributorAuthor

    domain:server#2 · os-steve · session_01ADHkmSaagzgP2FPBJq6Cre
    os-dev-report

    {
      "issue": 31608,
      "status": "done",
      "branch": "claude/project-thread-867elb",
      "pr": "https://github.com/objectstack-ai/objectstack/pull/31709",
      "head": "b0670417",
      "session": "session_01ADHkmSaagzgP2FPBJq6Cre",
      "premise_still_valid": true,
      "summary": "Root cause measured on a live mysql:8.0 cell: the cold seed's SELECT ... FOR UPDATE on the missing counter row takes a shared next-key gap lock (lock_mode X on the supremum), so the concurrent INSERTs deadlock; InnoDB rolls back the WHOLE transaction (ROLLBACK TO SAVEPOINT then answers ER_SP_DOES_NOT_EXIST), and the recovery SELECT ... FOR UPDATE + UPDATE ran on in autocommit as a lost update, issuing duplicates. Fix in getNextSequenceValue: a plain read decides existence, a missing row is seeded idempotently (ON CONFLICT DO NOTHING on PG/SQLite; a no-op ON DUPLICATE KEY UPDATE on MySQL, measured 0 deadlocks where INSERT IGNORE gave 8-14 per burst), then the row is locked; ER_LOCK_DEADLOCK is retried as a whole issue (max 5) only when the driver owns the transaction, and refused with the server's error inside a caller transaction (main went on in autocommit there). New live MySQL cold-race file beside the #8269 one, plus SQLite-injected retry pins. No unique index added (measured absent; follow-up).",
      "tests": "Red on main (live mysql:8.0, base 09df5711): probe 16 cold creates x5 rounds: one driver dups 8/8/7/8/0 with 2/0/3/0/0 ER_LOCK_DEADLOCK; two drivers dups 8/10/9/9/9 with 6/4/5/5/5 ER_LOCK_DEADLOCK, counter stuck at 2. New test file on base source: Tests 6 failed | 2 passed (8). After (b0670417): probe 20 rounds x 3 modes (one driver, two drivers, caller transactions) ok=16 dups=0 errors=0, server lock_deadlocks delta 0; PG16 probe 5 rounds x 3 modes clean; live PG16+MySQL8 all 12 autonumber files 113/113 (#8269 suite untouched, green); driver-sql test (sqlite) Test Files 246 passed | 13 skipped, Tests 4170 passed | 223 skipped, lock VERDICT command-exit 0; typecheck exit 0 (new test in --listFiles); eslint --no-inline-config packages/drivers/driver-sql exit 0. Ablations via scripts/ablation-replace.mjs on the committed fix, each restored (blob == HEAD, git diff HEAD empty), no dist leg (tests import ../src): A1 retry inside caller trx -> 'never retries inside a caller transaction' + live deadlock pin red ('promise resolved ... instead of rejecting'); A2 no retry -> 'expected scanMaxNumericTail to be called 5 times, but got 1 times'; A3 classify any error -> 'does not retry an error that leaves the transaction alive' red; A5 INSERT IGNORE on MySQL -> caller-trx burst red ('expected [ ER_LOCK_DEADLOCK, ...(13) ] to deeply equal []'); A7 fallback after whole-trx rollback -> live deadlock pin red.",
      "gates": "dispatch-gates --commands --repo objectstack-ai/objectstack at b0670417: 69 commands; 66 exit 0 first pass; 3 exit 3 on container prerequisites rerun exit 0 on the same head (check-plugin-teardown-shape --self-test after fetching fixture 621a4876; check:dual-build-cjs-loads and check:lean-entry-closure after full pnpm build under the lock, VERDICT command-exit 0). --ran reconciliation: '69 derived famil(ies) accounted for — 69 run, 0 NOT-MEASURED', exit 0. Package lint (root eslint --no-inline-config on packages/drivers/driver-sql): exit 0. CI check-runs on #31709: in_progress at report time (not waited on).",
      "line_budget": "4 files, +362 / -43 (PR additions/deletions): sql-driver-autonumber.ts, sql-driver.ts (+2 lines, host getter), new test file, changeset",
      "files_changed": [
        "packages/drivers/driver-sql/src/sql-driver-autonumber.ts",
        "packages/drivers/driver-sql/src/sql-driver.ts",
        "packages/drivers/driver-sql/src/sql-driver-autonumber-cold-race-mysql.test.ts",
        ".changeset/31608-mysql-cold-autonumber-duplicates.md"
      ],
      "deviations": [
        "File surface: sql-driver.ts gains two lines (the getNextSequenceValue host literal's isMysql getter) to choose the MySQL seed spelling; the claim named only sql-driver-autonumber.ts.",
        "Live MySQL 8.0.46 and Postgres 16 cells are container-only (docker; postgres pulled via mirror.gcr.io after Docker Hub 429). CI runs the new live file only in Temporal Conformance (live PG + MySQL), which is main-push/schedule only; on PRs the live describes are named skips and the SQLite pins run.",
        "The full driver-sql suite was not run against the live servers locally: the container servers are UTC and the temporal matrices assert a skewed server zone; only the 12 autonumber files ran live.",
        "Session-context asks to set the PR assignee/reviewer via MCP writes; not done: the seat's standard order forbids MCP writes and os-dev forbids PR assignees.",
        "Probe server-deadlock counts are read after the burst is dispatched, so a deadlock in the first milliseconds could be missed; the before/after duplicate and error counts do not depend on it."
      ],
      "dogfood_battery": "n/a — no `!` in the PR title and no (narrowing) arm",
      "mcp_calls": "3 — issue_read get, issue_read get_comments, pull_request_read get (all reads)",
      "api_writes": "2 — fleet-write relay pr_create (PR #31709); this os-dev-report comment on #31608 via post-stamped.mjs",
      "open_questions": [
        {
          "question": "Unique index on the autonumber column (seat ruling 3): measured absent for new objects (MySQL SHOW INDEX on a new autonumber object: only PRIMARY(id)). File a follow-up card?",
          "options": [
            "A file a follow-up card: composite unique (tenant column, autonumber column) for NEW objects first, with existing installs behind a migration that reports rows this defect already duplicated",
            "B no card: the counter fix is sufficient"
          ],
          "recommendation": "A, because the index is the only guard that makes a future counter regression loud instead of silent, and existing installs may already hold duplicates from this defect that a migration must surface before it can add the index"
        },
        {
          "question": "Every issue now makes one non-locking primary-key read of the counter row before locking it (all dialects). Accept the extra read?",
          "options": [
            "A accept: one PK lookup per issued number",
            "B lock first and seed only after a locking miss: no extra read on the warm path, but on MySQL the gap lock comes back, so cold bursts deadlock and only driver-owned transactions recover by retry"
          ],
          "recommendation": "A, because B reintroduces deadlocks for issues inside caller transactions, which are refused"
        }
      ],
      "security_findings": "none",
      "out_of_scope_findings": [
        "carrier: none · noted, not filed — knex's MySQL client logs 'Transaction was implicitly committed, do not mix transactions and DDL' when its ROLLBACK TO SAVEPOINT meets ER_SP_DOES_NOT_EXIST after a deadlock; misleading wording, third-party, in PR Acceptance notes",
        "carrier: none · noted, not filed — MySQL ER_LOCK_WAIT_TIMEOUT is not classified as a whole-transaction rollback; it is one only on servers with innodb_rollback_on_timeout=ON (default OFF), where a lock timeout would still take the existing fallback; in PR Acceptance notes"
      ]
    }

    Stamped 2026-11-08T22:38Z.


    Generated by Claude Code

  6. objectstack-fleet commented on Nov 8, 2026

    @objectstack-fleet
    ContributorAuthor

    domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM

    ACCEPT → PR #31709 comment 6728406904 · head b0670417 · 2026-11-08T23:05Z · landing: pr_ready + automerge_enable

  7. objectstack-fleet commented on Nov 9, 2026

    @objectstack-fleet
    ContributorAuthor

    domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM

    落地 · 2026-11-09T00:03Z

    reading value
    PR #31709 MERGED 2026-11-09T00:02Z, merge commit 82a3ed2e (ACCEPT 6728406904; Clause-② no, no governed path, no contract review face)
    #31608 closed by the merge (Fixes #31608)

    Landed:

  8. removed
    pm:dispatched
    on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugdomain:serverpriority:p3

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions