Repository navigation
fix(cli): os migrate apply takes a database lock so concurrent migrators run one at a time - #31714
Conversation
…ors serialize Two os migrate apply runs against one Postgres or MySQL database (one per replica, from an init container on each pod) both read the same pending work and both performed it. A deferred boot that can apply now takes a session-level advisory lock on the primary (pg_advisory_lock / GET_LOCK) after its DDL-free boot and before the first read of pending work, and releases it in shutdown. Uncontended it is silent; contended it prints one line, waits a bounded time and refuses on timeout. SQLite takes none. Claude-Session: https://claude.ai/code/session_01ADHkmNs71AKtAebnmL7SxF Co-authored-by: Claude <noreply@anthropic.com>
…n live Postgres Claude-Session: https://claude.ai/code/session_01ADHkmNs71AKtAebnmL7SxF Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ADHkmNs71AKtAebnmL7SxF Co-authored-by: Claude <noreply@anthropic.com>
…mporting a test helper from src Claude-Session: https://claude.ai/code/session_01ADHkmNs71AKtAebnmL7SxF Co-authored-by: Claude <noreply@anthropic.com>
Its pins then load the lock alone, not the migration stack whose dynamic imports check:test-source-alias would otherwise ask them to pay up front. Claude-Session: https://claude.ai/code/session_01ADHkmNs71AKtAebnmL7SxF Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift Check9 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run. What this run could not see
Coarse fallback — 35 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 55b0eed54cf81fe767c00921a7422a469e75a350 && git checkout 55b0eed54cf81fe767c00921a7422a469e75a350
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin b126c13065db29c80996efc7e0527a40f651c923 53aea71cf3cae9820396e0642854ee88cf3694db && git checkout -B drift-repro b126c13065db29c80996efc7e0527a40f651c923 && git merge --no-ff 53aea71cf3cae9820396e0642854ee88cf3694db
node scripts/docs-audit/affected-docs.mjs --json b126c13065db29c80996efc7e0527a40f651c923 |
|
domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM 维护者速读
席位核对 — ACCEPT · domain:server#2 · Head-sha
|
Requested by Steve · project thread
Fixes #31598
Clause-②: no
Metadata-protocol: none
维护者速读
os migrate apply在真正读取待办表结构变更之前,先在主库上拿一把数据库级的会话锁(Postgrespg_advisory_lock、MySQLGET_LOCK,锁名固定为objectstack:schema-migrate),命令结束时释放;SQLite 不加锁。packages/cli/src/utils/schema-migration-lock.ts的acquireSchemaMigrationLock;②packages/cli/src/utils/schema-migrate.ts中bootSchemaStack里migrationLock的取锁点与shutdown()的释放;③schema-migration-lock.integration.test.ts。OS_TEST_POSTGRES_URL=postgres://… pnpm --filter @objectstack/cli exec vitest run src/utils/schema-migration-lock.integration.test.ts,预期 4/4 通过:两个迁移排队等锁、只有一个建表、另一个报告in_sync。The one exception to R3 this card accepts
R3 on #3814 (「同意:每张卡都只在"声明多副本并接上 Redis 驱动"时才生效」) keeps the single-node default path unchanged. This card names the one exception it accepts, in its item 2:
So, stated plainly: on a single node, every applying
os migrate applynow runs one extra statement (select pg_try_advisory_lock(…)on Postgres,select GET_LOCK(…, 0)on MySQL) on a connection of its own, plus the matching unlock at the end. It is not gated behind declared replicas or a Redis driver, because the collision happens before any replica count is known to the migrator. Uncontended it prints nothing. Measured: oneos migrate apply --yeson a fresh Postgres database, human face, gives byte-identical stdout and stderr onorigin/mainand on this diff over the same base once ISO timestamps and durations are normalized (stdout sha2568980fba0…1eda0, 41,920 bytes, both sides; stderr empty, both sides). SQLite (and the Turso and WASM drivers on it) runs no statement at all.What changes
packages/cli/src/utils/schema-migration-lock.ts(new).acquireSchemaMigrationLock(driver, { database, warn, waitMs? }). It reads the dialect from the driver's own knex client:postgresqltakespg_advisory_lock,mysqltakesGET_LOCK, and every other dialect answersnulland runs nothing. The flow is a no-wait try first (silent when it succeeds); on contention it prints ONE line naming the database and waits, bounded (Postgreslock_timeout, MySQLGET_LOCK's seconds argument). If the wait runs out it throws a refusal naming the database, and the run migrates nothing.release()unlocks on the same session, then closes it. It is idempotent and never throws. Its own module, importing onlynode:crypto, so its pins load the lock and not the migration stack (check:test-source-aliasasked for exactly that).SCHEMA_MIGRATION_LOCK_NAME = 'objectstack:schema-migrate', named once. The Postgres key is derived from it: the first 8 bytes of SHA-256 as a signed 64-bit integer,255402229896085448. The unit file pins the value, because a changed key would let an old and a new CLI migrate side by side during a rolling upgrade. It is not per-database: a Postgres advisory lock is already scoped to its database. MySQL'sGET_LOCKis server-wide, see Acceptance notes.SCHEMA_MIGRATION_LOCK_WAIT_MS = 10 * 60_000, a constant. No environment override exists for migration timeouts, so none is added.packages/cli/src/utils/schema-migrate.ts,bootSchemaStack. A boot that can apply (a deferred boot that is not a read-only probe) takes the lock on the primary right afterruntime.start(), before the coverage pass and before the firstpreviewDeferredSchemaWork(). That boot held all its DDL back, so nothing has been written yet. A migrator that waited then reads only the work the first one left, which is none.shutdown()releases the lock first, in afinally. If one of the three post-lock reads (coverage, preview, package-table plan) throws,underLockreleases it before the throw leaves. Which commands take it:os migrate apply, plus the--applymodes that boot deferred,os migrate organization-ownership --applyandos migrate multi-value-columns --apply.os migrate planand every other read-only probe take none.acquireRawConnection/destroyRawConnection. See Acceptance note 1 for why not a pooled connection.@objectstack/clipatch, with the claim's two lines at line start.Tests
packages/cli/src/utils/schema-migration-lock.test.ts(new, unit, 16 cases, fake knex recording every statement and the session it ran on). The key value is pinned. SQLite / MSSQL / Oracle / no dialect / no knex answernullwith no connection opened and no line. Postgres and MySQL each cover: uncontended, one statement and no line; release on the same session, once; contended, exactly one line naming the database, then the bounded wait (lock_timeoutin ms,GET_LOCKin whole seconds); a wait that runs out refuses and closes the session. MySQLGET_LOCKanswering0orNULLrefuses. Any other wait failure is handed on unchanged.packages/cli/src/utils/schema-migration-lock.integration.test.ts(new, integration tier, live Postgres viaOS_TEST_POSTGRES_URL, named skip without it). The contention is staged, not raced. The test holds the lock on its own session, spawns twoos migrate apply --yes --json(bin/run-dev.js), waits untilpg_locksshows both queued (an advisory lock not granted), then releases. Assertions: both queued (2); both exit 0 and each printed the wait line exactly once, on stderr, with stdout still one JSON document; exactly one created the schema and the other answeredin_syncwith nothing created; the table exists. A third, uncontended run is the control: no wait line,in_sync.Acceptance notes
OS_DATABASE_POOL_MAX=1pool would have no connection left for the migration itself, so it would deadlock until the acquire timeout. So the lock takes its own session through the driver's own client and configuration. The seat may re-rule.helm/lives in the cloud repository, which this session cannot read. The card namesschema-migrate.ts, whosebootSchemaStackis theos migrate applypath, so that is what is locked. If the chart's init container runs a SERVING boot withOS_MIGRATE_AND_EXIT=1(os serve,packages/cli/src/commands/serve.ts) instead, its boot-time schema sync does not go throughbootSchemaStackand this lock does not cover it. The same holds for any replica's own serving boot, whose additive sync runs at start. carrier: the cloud C2 card (the Helm hook Job), which decides which command the Job runs; noted, not filed.--applydata commands (os migrate meta --stored --apply,value-shapes --applyand the others that boot plain) run their schema sync insideruntime.start(), before any point a lock could be taken without adding a kernel plugin. A plugin would add three INFO lines to every boot and break the byte-identical control. They are not locked. They are data repairs, not the schema migration this card names.GET_LOCKis server-wide, not per-database: two migrations of different databases on one MySQL server now run one after the other. That is harmless, only slower, and the seat ruled out per-database-name keys. NOT MEASURED live: the container has no MySQL server. The statements and result shapes are pinned in the unit file against mysql2's[rows, fields]shape.resolveStandaloneDatabaserefuses their URL schemes ("Supported schemes: postgres://, pg://, mysql://, mysql2://, mongodb://, mongodb+srv://, libsql://, file:"). A declared datasource can be MSSQL, but the lock lives on the primary, which every migrator of the deployment shares.Errorwhose message names the database and the remedy, andos migrate applyprints it and exits 1 the way it handles any boot failure. A new ADR-0112 code would be a new public name, so it is listed as an open question for the seat rather than coined.Verification
Head
53aea71cf3cae9820396e0642854ee88cf3694db, a clean merge withorigin/mainatb126c1306. Every reading below the ablations is on that head.Red on main, green after: three concurrent os migrate apply against one fresh Postgres 16 database
CONTROL: one uncontended migration, byte-identical to main
Ablations (scripts/ablation-replace.mjs, each restored to the HEAD blob, git diff HEAD empty) on ba38138
Tests and gates on 53aea71 (after pnpm install --frozen-lockfile and a full pnpm build, 119/119)
Generated by Claude Code