Skip to content

fix(cli): os migrate apply takes a database lock so concurrent migrators run one at a time - #31714

Merged
objectstack-fleet[bot] merged 7 commits into
mainfrom
claude/project-thread-mbr5cz
Nov 9, 2026
Merged

objectstack-fleet[bot] merged 7 commits into
mainfrom
claude/project-thread-mbr5cz

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Steve · project thread

Fixes #31598

Clause-②: no
Metadata-protocol: none

维护者速读

  • 改了什么:os migrate apply 在真正读取待办表结构变更之前,先在主库上拿一把数据库级的会话锁(Postgres pg_advisory_lock、MySQL GET_LOCK,锁名固定为 objectstack:schema-migrate),命令结束时释放;SQLite 不加锁。
  • 为什么改:多副本部署时每个 Pod 的 init 容器都会跑一次迁移。实测 3 个迁移同时打同一个 Postgres:三个都报告"建了表"(82 + 86 + 37 张,库里实际 86 张),第三个还在别人建到一半的表上做了 drift 变更,而且全部退出码 0。
  • 风险与回滚:单机路径只多一条无竞争的加锁语句,输出逐字节不变(实测)。有竞争时多打印一行"正在等待",最多等 10 分钟,超时则拒绝、不做任何变更并以非零退出。回滚即 revert 本 PR。
  • 先看:① 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。
  • 两分钟验证:有本地 Postgres 时运行 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:

  1. The lock is harmless on a single node (uncontended); keep its output identical apart from no new lines when uncontended. Note: this changes the single-node code path by one uncontended lock call; say so in the PR.

So, stated plainly: on a single node, every applying os migrate apply now 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: one os migrate apply --yes on a fresh Postgres database, human face, gives byte-identical stdout and stderr on origin/main and on this diff over the same base once ISO timestamps and durations are normalized (stdout sha256 8980fba0…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: postgresql takes pg_advisory_lock, mysql takes GET_LOCK, and every other dialect answers null and 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 (Postgres lock_timeout, MySQL GET_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 only node:crypto, so its pins load the lock and not the migration stack (check:test-source-alias asked for exactly that).
  • The key. 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's GET_LOCK is server-wide, see Acceptance notes.
  • The bound. 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 after runtime.start(), before the coverage pass and before the first previewDeferredSchemaWork(). 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 a finally. If one of the three post-lock reads (coverage, preview, package-table plan) throws, underLock releases it before the throw leaves. Which commands take it: os migrate apply, plus the --apply modes that boot deferred, os migrate organization-ownership --apply and os migrate multi-value-columns --apply. os migrate plan and every other read-only probe take none.
  • The session. The lock rides a connection opened through the driver's own client (its configuration, credentials and TLS) but outside its pool, via knex acquireRawConnection / destroyRawConnection. See Acceptance note 1 for why not a pooled connection.
  • Changeset. @objectstack/cli patch, 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 answer null with 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_timeout in ms, GET_LOCK in whole seconds); a wait that runs out refuses and closes the session. MySQL GET_LOCK answering 0 or NULL refuses. Any other wait failure is handed on unchanged.
  • packages/cli/src/utils/schema-migration-lock.integration.test.ts (new, integration tier, live Postgres via OS_TEST_POSTGRES_URL, named skip without it). The contention is staged, not raced. The test holds the lock on its own session, spawns two os migrate apply --yes --json (bin/run-dev.js), waits until pg_locks shows 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 answered in_sync with nothing created; the table exists. A third, uncontended run is the control: no wait line, in_sync.
  • No forced test edits.

Acceptance notes

  1. Seat ruling 1 said "on the SAME connection the migration uses (a pooled second connection would not serialize)". Measured otherwise, and taken by its intent. Both locks are session-scoped and exclude every other session on the database, the migration's own pooled ones included. The integration pin shows a lock held on a session outside both migrators' pools serializing them. What a pool breaks is the release: knex's pool gives no promise that the unlock runs on the session that locked, its idle reaper can close a held connection (silently releasing the lock), and an OS_DATABASE_POOL_MAX=1 pool 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.
  2. Where the init container's command comes from. helm/ lives in the cloud repository, which this session cannot read. The card names schema-migrate.ts, whose bootSchemaStack is the os migrate apply path, so that is what is locked. If the chart's init container runs a SERVING boot with OS_MIGRATE_AND_EXIT=1 (os serve, packages/cli/src/commands/serve.ts) instead, its boot-time schema sync does not go through bootSchemaStack and 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.
  3. The non-deferred --apply data commands (os migrate meta --stored --apply, value-shapes --apply and the others that boot plain) run their schema sync inside runtime.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.
  4. MySQL. GET_LOCK is 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.
  5. MSSQL / Oracle are out of scope, measured. The CLI's primary database never is one: resolveStandaloneDatabase refuses 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.
  6. The refusal carries no error code. It is a plain Error whose message names the database and the remedy, and os migrate apply prints 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 with origin/main at b126c1306. 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
origin/main 5d1382a5, run 1:  migrator 0 created 82 · migrator 1 created 86 · migrator 2 created 37, applied 3 drift · all exit 0 · 86 tables
origin/main 5d1382a5, run 2:  created 12 · 86 · 41 · all exit 0 · 86 tables
origin/main 5d1382a5, 2 migrators:  created 86 · 85 · both exit 0
fix c8de894b, run 1:  created 86 · 0 (in_sync) · 0 (in_sync) · all exit 0 · 86 tables
fix c8de894b, run 2:  created 0 (in_sync) · 86 · 0 (in_sync) · one printed "Another schema migration is running on postgres://127.0.0.1:5432/…; waiting up to 600 s for it to finish…"
CONTROL: one uncontended migration, byte-identical to main
origin/main 5d1382a5  os migrate apply --yes (human face), fresh PG db: exit 0 · stdout 41,920 bytes sha256 8980fba0d8e1fb6a50c5511b88ede883c1d3f3465fadafca069c730fb0b1eda0 · stderr 0 bytes
ba381380 (this diff on that base)  same command, same fixture:   exit 0 · stdout 41,920 bytes sha256 8980fba0d8e1fb6a50c5511b88ede883c1d3f3465fadafca069c730fb0b1eda0 · stderr 0 bytes
(normalized: ISO timestamps -> TS, durations -> N ms; main ran twice first and was self-identical)
53aea71c (after the second main merge): one line differs from the 5d1382a5 reading, and it is main's, not this diff's:
  "[platform-objects] contributed platform translations (20 locale entries)" -> "(22 locale entries)",
  from b126c130 (#31588, the platform objects in Korean). No wait line and no other change.
Ablations (scripts/ablation-replace.mjs, each restored to the HEAD blob, git diff HEAD empty) on ba38138
A1 lock never taken (`false as boolean && deferral …` in bootSchemaStack) -> integration 3 failed | 1 passed:
   "both migrators queued" expected +0 to be 2; "applied ONCE" expected 2 creators to have a length of 1
A2 Postgres 55P03 proceeds instead of refusing   -> unit 1 failed | 15 passed ("a wait that runs out REFUSES")
A3 MySQL GET_LOCK 0/NULL proceeds                -> unit 2 failed | 14 passed (both GET_LOCK refusal cases)
A4 the wait line printed even uncontended        -> unit 4 failed | 12 passed (both "NOT ONE line printed", both "ONE line")
A5 dialect gate removed (SQLite etc. take a lock) -> unit 4 failed | 12 passed (sqlite3 / mssql / oracle / undefined)
Tests and gates on 53aea71 (after pnpm install --frozen-lockfile and a full pnpm build, 119/119)
pnpm --filter @objectstack/cli typecheck            tsc green · check:test-typecheck OK (3 files / 28 errors / 6 pinned signatures held, unchanged)
cli unit tier (vitest --project unit)               Test Files 406 passed (406) · Tests 5740 passed (5740)
schema-migration-lock.integration.test.ts (live PG) Tests 4 passed (4)   (integration tier run locally because this diff adds an integration file)
eslint packages/cli --no-inline-config              exit 0, no findings
dispatch-gates --commands                           67 derived families, each run: 67 exit 0
dispatch-gates --ran                                67 derived, 67 run, 0 NOT-MEASURED, 0 UNRUN
first round on ba381380 (before the second merge):  67/67 exit 0 after deepening for the teardown self-test fixture (exit 3 on the shallow clone, a container prerequisite)
earlier red, fixed in this PR: check:test-source-alias flagged both new test files for reaching the migration stack's dynamic imports; the lock moved to its own module (ba381380)

Generated by Claude Code

…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>
…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>
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 8, 2026
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

9 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
  • 3 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 231 client-bound route-ledger rows — the other 166 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 166: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 107 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 35 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json b126c13065db29c80996efc7e0527a40f651c923 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 55b0eed54cf81fe767c00921a7422a469e75a350 — the merge of head 53aea71cf3cae9820396e0642854ee88cf3694db into base b126c13065db29c80996efc7e0527a40f651c923, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# 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

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM

维护者速读

  • 改了什么: os migrate apply 开始迁移前先拿一把数据库锁,同一个库上的多个迁移进程会排队依次执行。Postgres 用 advisory lock,MySQL 用 GET_LOCK,SQLite 不需要。
  • 为什么改: 多副本各自在 init 容器里跑迁移时会并发建表。实测 86 张表的空库上,三个并发迁移分别报告建了 82、86、37 张。
  • 风险与回滚: 没有人争用锁时只多一条语句,输出逐字节不变。等锁时打印一行,最多等 10 分钟,超时就拒绝,不会在没拿到锁的情况下继续迁移。回滚即还原本 PR。
  • 先看: 新文件 packages/cli/src/utils/schema-migration-lock.ts,以及 schema-migrate.ts 里 bootSchemaStack 拿锁、shutdown() 放锁的位置。
  • 两分钟验证: 读 schema-migration-lock.integration.test.ts 的实库 Postgres 用例,三个并发迁移最终每张表只建一次。
  • 需要你做的: 无,由席位落地。
  • 席位意见: ACCEPT。服务器自身启动(含 OS_MIGRATE_AND_EXIT=1)同样会同步表结构,那条路径另开 cli/runtime: a server boot that syncs schema (OS_MIGRATE_AND_EXIT and the ordinary boot) takes the same schema-migration lock as os migrate apply (#31598 follow-up) #31715 处理。

席位核对 — ACCEPT · domain:server#2 · Head-sha 53aea71cf3cae9820396e0642854ee88cf3694db · 2026-11-08T23:29Z

  1. Shape: draft to main, Fixes #31598; Clause-②: no, Metadata-protocol: none; patch changeset for @objectstack/cli. Files: the new schema-migration-lock.ts (+150), schema-migrate.ts (+26 −4), the unit test (+206), the live-PG integration test (+266), and the changeset.
  2. Premise: held. On main, three concurrent os migrate apply runs against one fresh Postgres all exited 0 and reported creating 82, 86 and 37 tables for 86 tables. After the change: 86 / in_sync / in_sync.
  3. Read of the diff:
    • Where the lock is taken. On a boot that can apply (deferred, not a read-only probe), after the DDL-free boot and before the first read of pending work. A waiter therefore reads only what the first migrator left.
    • Release. Released first in shutdown()'s finally, and also by underLock when the boot throws after taking it.
    • Postgres. pg_try_advisory_lock first. If that fails: one line, then pg_advisory_lock bounded by lock_timeout. 55P03 means refusal.
    • MySQL. GET_LOCK(name, 0) first, then GET_LOCK(name, ⌈wait/1000⌉). Any answer other than 1 means refusal.
    • Other dialects. No statement.
    • Key. A fixed name, objectstack:schema-migrate. The PG key is SHA-256's first 8 bytes as a signed int64 and is pinned, so every CLI version takes one lock (ruling 2).
    • Bound. A constant of 10 min. No env override, because none exists for migration timeouts (ruling 3).
  4. R3 exception (card item 2):
    • Uncontended single node: one lock statement on a session of its own, and no output.
    • CONTROL: a single run's stdout is byte-identical to main (sha 8980fba0…), and stderr is empty on both.
  5. Gates:
    • Measured: live-PG pin 4/4; cli unit tier 406/406 files; 5 ablations each red, then restored.
    • Dev gates: 67/67 derived gates exit 0, 0 NOT-MEASURED, 0 UNRUN; lint clean.
    • Check-runs on this head: 35 success, 15 skipped, 0 failed.
    • MySQL: pinned in unit tests with a fake client (both result shapes, contended and uncontended, refusal). No live MySQL leg, because the CLI's live harness is PG only. Accepted.
  6. Accepted deviations and open questions, ruled:
    • (1) Own session, not the migration's connection. Accepted. My ruling 1 read "same connection", but its intent was that migrators exclude each other. A session lock does that from a dedicated session, and that session is safer than a pooled connection: no release on another session, no reaper, no deadlock at pool max 1.
    • (2) New module schema-migration-lock.ts. Forced by check:test-source-alias. Accepted.
    • (3) Error code. No new public code. The refusal is a plain error whose message names the database and the lock, and the CLI exits non-zero (no pull for a code).
    • (4) Names. SCHEMA_MIGRATION_LOCK_NAME, SCHEMA_MIGRATION_PG_LOCK_KEY, SCHEMA_MIGRATION_LOCK_WAIT_MS and acquireSchemaMigrationLock are kept as they are.
    • (5) Server boot and OS_MIGRATE_AND_EXIT=1. Not covered here. Filed as cli/runtime: a server boot that syncs schema (OS_MIGRATE_AND_EXIT and the ordinary boot) takes the same schema-migration lock as os migrate apply (#31598 follow-up) #31715 (p1), reusing this module and this lock name.
    • (6) Env override. None, per ruling 3.
  7. Landing: Clause-② is no and no governed path is touched, so there is no contract review face. Ordinary queue landing: pr_ready + automerge_enable.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 8, 2026 23:30
@objectstack-fleet
objectstack-fleet Bot enabled auto-merge November 8, 2026 23:30
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 8, 2026
Merged via the queue into main with commit d7a7193 Nov 9, 2026
51 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-mbr5cz branch November 9, 2026 00:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cli): schema migration takes a cluster-wide lock so concurrent replicas cannot migrate at once (#3814)

1 participant