Skip to content

Commit 5b7269f

Browse files
feat(core): key the activation ledger by (metadata_type, package_id, name) and bind package-less rows to their one holder (#31727)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9LUbkDNjMEbah13Un7M4WTK)_ Fixes #31682 Clause-②: yes (widening) — `@objectstack/core` exports `backfillActivationLedgerPackages` and the `ActivationLedgerHolder`, `ActivationLedgerUnboundRow`, `ActivationLedgerBackfillReport` and `ActivationLedgerBackfillOptions` types from its root, and `@objectstack/metadata-protocol` exports `ensureActivationLedgerPackagelessIndex`, `buildActivationLedgerPackagelessIndexSql`, `buildActivationLedgerPackagelessDuplicateProbeSql`, `ACTIVATION_LEDGER_PACKAGELESS_INDEX_NAME` and the `EnsureActivationLedgerPackagelessIndexResult` / `EnsureActivationLedgerPackagelessIndexStatus` types; nothing is removed or renamed, and every door and name-keyed reader answers as before. Metadata-protocol: none ## 维护者速读 - 改了什么:激活台账 `sys_metadata_activation` 的唯一键从 `(metadata_type, name)` 改为 `(metadata_type, package_id, name)`;启动时把没有包的台账行回填为唯一持有它的软件包,两个包都持有的名字不猜、记一条 warn 列出全部候选。没有包的行(环境自己写的项)不受新键约束(NULL 互不相同),所以另建一条索引让它们仍然每个(类型,名字)只有一行:SQLite/PostgreSQL 为部分唯一索引,MySQL 为函数键,Mongo 为部分过滤唯一索引。driver-sql 的差异比对只在这条保护索引已存在时,才把旧的两列索引报成安全替换。 - 为什么改:专题 #31527 子卡 S1(ADR-0150 D4、D8 R4):行为类元数据按(包,名)寻址,台账要能让两个包各有一行同名项,同时不丢掉没有包的行原有的“一项一行”保证(专题红线复核 6729398713)。 - 风险与回滚:没有读者或写者改用包列,激活门的回答不变;回填只写 `package_id`,第二次启动零写入。新索引只增不替换,已有重复行时拒绝建索引、不删数据并报 error。MariaDB 两种形式都建不了,旧两列索引被保留(见 #31732)。回滚即 revert。 - 先看:`packages/metadata-protocol/src/migrations/activation-ledger-packageless-index.ts`、`packages/objectql/src/activation-ledger-backfill.ts`、`packages/drivers/driver-sql/src/schema-drift.ts` 的 `widenedUniqueReplacements`。 - 两分钟验证:`pnpm --filter @objectstack/dogfood exec vitest run test/activation-ledger-package-key.dogfood.test.ts`,预期 8 条通过、1 条跳过(memory 驱动不建该索引)。 - 需要你做的:无,席位落地(专题线程复核该项后由席位落地)。 ## What changes - **The key** (`platform-objects`). `sys_metadata_activation`'s one declared unique index is `(metadata_type, package_id, name)`, `unique: 'global'` (ADR-0150 D4 table row "activation ledger"; D8 row R4). `package_id` stays its own nullable column (ADR-0126 §4: two facts, two columns, never a re-encoded literal). - **The backfill** (`core` + its boot entry in `objectql`). `backfillActivationLedgerPackages(engine, holderOf, { dryRun? })` reads every ledger row with no package and asks `holderOf(type, name)`; it writes only `package_id`, and only for a row whose item has exactly one holder. The answer comes from the R resolver, read through its exports (`resolvePackageScopedName` with no caller package, ADR-0150 D3), in `activationLedgerHolderOf`: resolved to a package binds; resolved to the environment's own item, not-found, or a type the resolver does not address (`position`, D7) leaves the row null; refused is the ambiguous set, left null with every candidate. The engine plugin runs it once per cold boot at `kernel:bootstrapped`, right after `sealBareNameHoldersAtColdBoot`, only on a sealed registry that registers the ledger object. Bound rows are named in one `info` line; ambiguous rows in one `warn` line naming each holder. Never fatal: a ledger that cannot be read leaves every row as it was and the next boot tries again. The function returns the report, so S4's upgrade report and bind command can reuse it. - **Rows naming no package keep one row per `(metadata_type, name)`** (`metadata-protocol`, `driver-mongodb`; epic review 6729398713). The new key is NULL-distinct on `package_id`, which is NULL on every row for an item the environment authored, so on its own it would no longer refuse a second such row. A runtime index ADDED beside the declared key, `uniq_sys_metadata_activation_packageless`, restores the guarantee. `ensureActivationLedgerPackagelessIndex` builds it at `kernel:ready`, as the four precedents in `metadata-protocol/src/migrations/` do (same seam, presence probe and ADR-0120 D4 refuse-never-keep-one wording), and `os migrate duplicates` lists what would block it (`runtime-index-preflight.ts`). It replaces nothing, so there is no probe name and nothing is dropped. `driver-mongodb` builds the same index at collection sync, because it has no raw-SQL seam. The per-dialect forms are in the table under Acceptance notes. - **No reader or writer moves.** `ObjectStoreMetadataActivationStore.setActive` still addresses the row by `(metadata_type, name)` (the bare path, red line 3): it inserts only where that read finds nothing, so it keeps one row per name and no name-keyed reader can see two. Each type's E child moves its reads and writes onto the package together. - **The upgrade path** (`driver-sql`, claim amendment 6728608547). On an existing database the old `uniq_sys_metadata_activation_metadata_type_name` read as an orphan `drop_index`, category destructive, and three upgrade-harness pins went red. `legacyUniqueReplacements` gains one narrow arm, `widenedUniqueReplacements`: a physical generated-name plain UNIQUE whose columns are an in-order proper subsequence of an unnamed `unique: true`/`'global'` declared index on the same table, whose name no current index (field-level included) carries, is superseded through the existing `replace_unique_index` op: category `safe`, create-before-drop. **Widening a unique key is a pure relaxation**: two rows that collide on the wider key already collided on the narrower one, so the wider index cannot fail to build and dropping the narrower one loses no row. The arm runs on a tenant-less table (the tenant arms keep their own early return, moved into `tenantScopedLegacyReplacements` unchanged) and reads the physical index list, so it names only an index that exists. `diffManagedIndexes` gives the arm its own message (the tenant one would have said "scopes it per metadata_type"), and when a gained column is nullable the message says that rows whose column is NULL are constrained by the new key no longer (epic review wording item). `detectTableIndexDrift` passes `physical` through. **One more condition, for the same reason:** when a gained column is nullable, the arm offers the replace only once a partial UNIQUE on exactly the narrower columns stands beside it (`hasPartialUniqueGuard`). Until then the narrower index is still the only rule over the NULL rows, so it is KEPT: accounted for, offered neither as the replace nor as the orphan arm's destructive drop. On SQLite and PostgreSQL the guard exists after the first boot of this release, and the next `os migrate plan` offers the safe replace. On MariaDB it never exists, so the old index keeps guarding (route b, ruled by the seat). ## Step 0 — measured on `main` b126c13 | What | Reading | |:--|:--| | Unique key | `{ fields: ['metadata_type', 'name'], unique: 'global' }`, materialized `uniq_sys_metadata_activation_metadata_type_name` (also in the 18.0 / 18.0.0 / 18.0.0-next.5 upgrade fixtures) | | Package column | `package_id` text, nullable, already present; the store writes null for an environment-authored item and refuses `''` | | Writer | `ObjectStoreMetadataActivationStore.setActive` only (flow toggle, action toggle, catalog activation door): read by `(metadata_type, name)`, update the first match or insert | | Readers | per-type `list()` keyed by name (flows, actions, authz resolver, sharing, queues); `listPackageMetadataActivations` by `package_id` (customizations read) | | Migration entry | none existed for the ledger; the resolver's holders are final only after the boot seal at `kernel:bootstrapped` | | sql / sqlite | declared index through knex `unique(columns)`, SQL NULL-distinct; schema sync is additive by name, an undeclared generated index is an orphan `drop_index` (destructive) | | memory | `memory-unique-constraint.ts` reproduces the declared index, NULL-distinct like SQL | | mongo | NULL-distinct partial unique index (#29278), so the same NULL exemption (measured in round 2 on mongod 8.0.34) | | mssql | federation-only: `SqlDriver` refuses DDL, so no ledger table | ## ADR-0150's four readings - **(a) Phase-1 one-holder tests stay green.** `bare-name-one-holder` and `package-scoped-resolver` suites are inside the objectql run below; nothing in phase 1 changed. - **(b) Bare-name behaviour unchanged.** No door, URL, MCP or SDK path reads the package; the ledger writer and every reader still key by type and name. The existing ledger dogfood files (catalog activation door, action door, actor stamps, operator gate, flow provenance) are in the dogfood battery below. - **(c) The migration is re-runnable and never guesses.** Pinned in core (second run binds nothing, writes nothing; ambiguous row left with every candidate; dry run writes nothing; a bound row is never re-asked) and on a real SQLite file across three boots (dogfood: bound after boot 2, `updated_at` unchanged after boot 3). - **(d) `Clause-②: yes (widening)`.** The published face only grows: the new root exports of `@objectstack/core` and `@objectstack/metadata-protocol` named on the Clause-② line. Every package bumps patch: under ruling A on #25105 the changeset level follows `Metadata-protocol` alone, and `none` takes patch. No spec, door or response shape changes, and nothing is removed or renamed. A second package-less activation row is refused `409 DUPLICATE_RECORD` as on `main`. No ADR-0087 entry: no declared-breaking change, and the change is to a platform object's indexes and its data, not to authorable metadata. ## Tests - `core` `metadata-activation-store.test.ts`: new top-level `describe` for the backfill (7 cases), with a stateful ledger double routed through `assertEngineUpdateDispatch`. - `objectql` `activation-ledger-backfill.test.ts` (new, 9 cases): the resolver adapter on a real `SchemaRegistry` (one holder, two holders named, environment item, unheld, position never asked) and the boot run (bind + ambiguous warning naming both holders, second boot writes nothing, unsealed registry and missing ledger object do not run, unreadable ledger warns and continues). - `platform-objects` `sys-metadata-activation.object.test.ts`: **forced edit** — the index pin now asserts `['metadata_type', 'package_id', 'name']` by equality (it asserted the old key); one new case pins the package column as nullable beside required type and name. - `driver-sql` `sql-driver-widened-declared-unique.test.ts` (new, 9 cases): the ledger case is one safe replace with no `drop_index`; a UNIQUE on other columns still reads `drop_index`/destructive; a declared UNIQUE that is not a superset leaves the old index orphaned; the arm runs tenant-less while the tenant arms still claim nothing there; a live field-level unique is never read as superseded; no physical list, a named or an organization declaration claim nothing; and on a real SQLite database built with the old key, plan → apply (no `allowDestructive`) → only the new index, no drift, and the wider key admits a second package and refuses a duplicate. - `dogfood` `activation-ledger-package-key.dogfood.test.ts` (new, 9 cases): on `sqlite-wasm` and on `memory`, two packages may hold rows of one name and the same package's second row is refused `DUPLICATE_RECORD` 409; on one SQLite file across restarts, a showcase flow row written with no package names `com.example.showcase` after the next boot and keeps its switch, a position row stays null, and a third boot does not touch the bound row. - `metadata-protocol` `activation-ledger-packageless-index.test.ts` (new, 9 cases, real `node:sqlite`): without the index the declared key admits two package-less rows (the hole); with it the second is refused, packaged rows are left to the declared key, a second boot is a no-op, existing duplicates give `conflict` with nothing deleted and the listing query in the `error` line, an absent table or no SQL driver is silent. It also pins the MySQL statement, ER_DUP_KEYNAME read as already-built, and the MariaDB `unsupported` report naming what still guards. - `metadata-protocol` `activation-ledger-packageless-index.live-dialects.test.ts` (new): live PostgreSQL (`OS_TEST_POSTGRES_URL`) and MySQL/MariaDB (`OS_TEST_MYSQL_URL`), named skips without them. Run here against all three containers, green. - `driver-mongodb` `mongodb-activation-ledger-packageless.test.ts` (new): the DDL against the recording fake `Db` (every lane), plus a real-mongod leg (opt-in, #5517), run here against mongod 8.0.34 (`MONGOMS_SYSTEM_BINARY`): missing field twice, then explicit null, both refused `E11000`; two packages admitted; one package twice refused. - `driver-sql` widening suite: the ledger case now stands beside the guard; new pins cover a nullable gained column with no guard (KEPT: no entry at all, and a plain non-partial unique is not the guard), a required gained column (no NULL warning) and the NULL wording; the real-SQLite apply also proves the guard still refuses a second package-less row afterwards. - `dogfood` ledger file: new red-first pin on `sqlite-wasm`: a second package-less row written straight to the engine is refused `DUPLICATE_RECORD` 409 (skipped on `memory`, the stated gap). - **Forced edits**: - `platform-objects` index pin (above). - `metadata-protocol` `runtime-index-preflight.test.ts`: the probe list and the blocked/clear listing each gain the fifth index (`table-absent` in that fixture). - `cli` `duplicates.contract.test.ts`: the list of `kernel:ready` indexes gains the fifth, and the title says five. - No other existing test was edited. The three upgrade-harness pins are **not** rebaselined; they are green because of the driver-sql arm. ## Acceptance notes - **The package-less guarantee, per driver** (measured on live servers stood up in Docker in the card container: PostgreSQL 16, MySQL 8.4, MariaDB 11, MongoDB 8.0.34, SQL Server 2022): | Driver | Package-less index | Second package-less row | Two packages, one name | |:--|:--|:--|:--| | SQLite (`better-sqlite3`, `sqlite-wasm`) | partial `(metadata_type, name) WHERE package_id IS NULL` | refused (`409 DUPLICATE_RECORD` through the engine) | admitted | | PostgreSQL 16 | same partial form | refused | admitted | | MySQL 8.4 | functional key part `((CASE WHEN package_id IS NULL THEN unhex(sha2(concat(metadata_type, 0x1f, name), 256)) END))`: a hidden generated column over the driver's own TEXT-key digest. The plain partial and CASE-over-columns forms are refused because the columns are TEXT | refused | admitted | | MariaDB 11 | none: no partial indexes and no functional key parts (`unsupported`, one `error` line). A visible VIRTUAL column would work, but the differ then reports it as a destructive `drop_column` + `drop_index` and it leaks into reads, so the route was not taken | upgraded database: refused by the KEPT old index. Fresh database: **admitted, a gap recorded in #31732** | upgraded: refused until the old index goes (#31732); fresh: admitted | | SQL Server | n/a: `SqlDriver` refuses all DDL there (federation-only, ADR-0015 §4.6), so no ledger lives there | — | — | | MongoDB 8.0 | partial unique with filter `{ package_id: null }`, which covers a missing field and an explicit `null` (`$exists: false` is refused in a partial filter) | refused `E11000` | admitted | | memory | none: it enforces declared indexes only. **A stated gap, ruled by the seat:** single-process, never multi-replica (#3814 R3), and `setActive`'s read-then-write is the one writer | admitted (measured) | admitted | - **The upgrade on SQL.** On SQLite and PostgreSQL, once this release has booted (which builds the guard), `os migrate plan` reports one `replace_unique_index` (safe) per upgraded database. Before that boot it reports nothing for the old index, which keeps guarding; the 18.x upgrade-harness pin plans the fixture before any boot and stays green unedited. Until the replace is applied, the old two-part index keeps refusing a second package's row of one name, which nothing writes yet. On MySQL the old index is a #11627 hash-shadow carrier, which the replace arms never claim (`isHashShadowCarrier`, unchanged here), so it reads as a destructive orphan, as on `main`. A default `os migrate apply` keeps it; `--allow-destructive` may drop it safely because the functional guard stands (measured). On MariaDB it is kept, as above. - **MongoDB, upgraded database.** That driver has no orphan arm, so an upgraded Mongo database keeps the old two-part unique beside the new one. That is harmless while nothing writes a second package's row, but it would refuse one once a type's E child does. The seat filed it as its own card; this PR does not touch it. - **Bound rows show in the customizations read.** `GET /packages/:id/customizations` lists ledger rows by `package_id`; a row the backfill binds now appears under its holder. That is the D8 binding itself, and on the stock showcase there are no such rows. - **File surface.** Claim amendments 6728608547 (driver-sql), 6729482694 (metadata-protocol migration, plugin, index, preflight; driver-mongodb) and 6729595741 (the cli duplicates contract test). The driver-sql amendment named `legacyUniqueReplacements` only, and the arm also needed its message and its `kept` branch in `diffManagedIndexes`, plus the `physical` argument at its caller. ## Verification Head `38d2d30c` (origin/main merged in `4bc107e5`, no rebase). The suites below ran on `4bc107e5`. The one commit after it renames the live test file (`.live.` is a nightly-tier marker) and adds module-top preloads to the cli contract test that `check:test-source-alias` asked for; that file was re-run (5/5) and the three gates re-run green. <details><summary>Package suites (under <code>os-verify-lock</code>, after the closure build)</summary> | Package | test | typecheck | |:--|:--|:--| | `@objectstack/core` | 3158 / 3158 (137 files) | exit 0 | | `@objectstack/platform-objects` | 1932 / 1932 (120 files) | exit 0 | | `@objectstack/objectql` | 11714 / 11714 (575 files) | exit 0 | | `@objectstack/driver-sql` | 4179 passed, 223 skipped (260 files; the skips are live-database cells) | exit 0 | | `@objectstack/metadata-protocol` | 22604 passed, 29 skipped (334 files) | exit 0 | | `@objectstack/driver-mongodb` | 731 passed, 196 skipped (42 files; the skips are the opt-in real-mongod suites) | exit 0 | | `@objectstack/cli` | `duplicates.contract.test.ts` 5 / 5 | exit 0 | | `@objectstack/dogfood` (full) | 3660 passed, 42 skipped (444 files) | — | Live cells, run here against Docker containers and skipped on CI lanes without the URLs: `activation-ledger-packageless-index.live-dialects.test.ts` on PostgreSQL 16 + MySQL 8.4, and again on PostgreSQL 16 + MariaDB 11, 3 / 3 each time. `mongodb-activation-ledger-packageless.test.ts` + `mongodb-unique-null-distinct.test.ts` + `mongodb-schema-declared-indexes.test.ts` against mongod 8.0.34, 26 / 26. The upgraded-database plan was also measured through `SqlDriver` on PostgreSQL (safe replace, then apply, then no drift, then a second package-less row refused and two packages admitted), MariaDB (old index kept, a second package refused) and MySQL (hash-carrier orphan, destructive, kept by a default apply). Upgrade harness + ledger dogfood together (`upgrade-18x-harness`, `upgrade-18x-index-equivalence`, `activation-ledger-package-key`): 34 passed, 1 skipped (the memory leg of the new pin). The harness pins are not edited. `pnpm lint` (root eslint, `--no-inline-config`) over `packages/core`, `packages/objectql`, `packages/platform-objects`, `packages/drivers/driver-sql`, `packages/drivers/driver-mongodb`, `packages/metadata-protocol`, the cli contract test and the dogfood file: exit 0. </details> <details><summary>Ablations — each negative pin read red, then restored (<code>git diff HEAD</code> empty after each)</summary> | # | Mutation | Red | |:--|:--|:--| | A1 | core: bind an ambiguous row to its first candidate | 5 core cases, incl. "leaves an ambiguous row as it is and reports EVERY candidate — never a guess" | | A2 | core: drop the "already names a package" filter | 5 core cases, incl. "never asks about, or moves, a row that already names a package" and the rerun pin | | A3 | objectql: map `refused` to its first candidate | 2 objectql cases (adapter "names EVERY holder…", boot "…naming both holders in its warning") | | A4 | objectql: drop the seal gate | 1 ("does not run before the holders are sealed") | | A5 | objectql: drop the unaddressed-type guard | 1 ("never asks the resolver about a type it does not address by package") | | A6 | driver-sql: the widening arm's call removed (marker in `dist/` proven present, then absent) | 3 driver-sql pins (ledger safe replace, tenant-less run, real SQLite apply) and the 3 upgrade-harness pins | | A7 | platform-objects: the ledger index made non-unique (marker in `dist/` proven present, then absent) | 2 dogfood refusal pins (sqlite-wasm and memory) | | B1 | driver-sql: the guard rule off (`kept` always false) | 1 ("a nullable gained column with NO partial guard … is KEPT") | | B2 | driver-mongodb: the runtime-owned unique not pushed | 2 (the DDL pin, and the live "second row naming no package … refused") | | B3 | metadata-protocol: the package-less index built without its `WHERE` | 3 (second package-less row refused, packaged rows left to the declared key, the dialect statement pin) | | B4 | metadata-protocol: the boot migration unwired (seam forced undefined; marker in `dist/` proven present, then absent) | 1 dogfood pin ("a second row naming no package … is refused — written past the store") | The positive pins (two packages accepted; the different-column and non-superset cases staying orphans) are controls for the same files and stayed green under every ablation that did not target them. </details> <details><summary>Dispatch gates</summary> `node scripts/pm/dispatch-gates.mjs --ran … --repo objectstack-ai/objectstack`: **85 derived, 85 run, 0 NOT-MEASURED, 0 UNRUN**, every exit 0 (derivation identical at `4bc107e5` and `38d2d30c`). Re-run after a first red: `check:tier-file-adoption` (the live file's `.live.` name, renamed), `check:test-source-alias` (the edited cli test, preloads added), and `check:type-check-debt` (lock queue-timeout while the dogfood battery held the lock, exit 3, NOT MEASURED until re-run). </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmQYLwhv2dRdWVF3aU1 <!-- signed: domain:server#4 · os-steve · session_01ADHkmQYLwhv2dRdWVF3aU1 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 01cbbba commit 5b7269f

25 files changed

Lines changed: 2223 additions & 50 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/core': patch
3+
'@objectstack/platform-objects': patch
4+
'@objectstack/objectql': patch
5+
'@objectstack/driver-sql': patch
6+
'@objectstack/metadata-protocol': patch
7+
'@objectstack/driver-mongodb': patch
8+
---
9+
10+
feat(core): the activation ledger is keyed by `(metadata_type, package_id, name)`, and rows that name no package take their one holder
11+
12+
Clause-②: yes (widening) — `@objectstack/core` exports `backfillActivationLedgerPackages` and the `ActivationLedgerHolder`, `ActivationLedgerUnboundRow`, `ActivationLedgerBackfillReport` and `ActivationLedgerBackfillOptions` types from its root, and `@objectstack/metadata-protocol` exports `ensureActivationLedgerPackagelessIndex`, `buildActivationLedgerPackagelessIndexSql`, `buildActivationLedgerPackagelessDuplicateProbeSql`, `ACTIVATION_LEDGER_PACKAGELESS_INDEX_NAME` and the `EnsureActivationLedgerPackagelessIndexResult` / `EnsureActivationLedgerPackagelessIndexStatus` types; nothing is removed or renamed, and every door and name-keyed reader answers as before.
13+
Metadata-protocol: none
14+
15+
`sys_metadata_activation` (the switch an administrator throws to turn a packaged flow, action, permission set, sharing rule, webhook, queue or assignment rule off) is now unique on `(metadata_type, package_id, name)` instead of `(metadata_type, name)` (ADR-0150 D4, D8 row R4). Two packages may each hold a row for an item of the same name; one package may not hold two.
16+
17+
At every boot, once the package holders are sealed, a ledger row that names no package is given the package that holds its item, as the package-scoped resolver answers it. Who sees it: an operator whose deployment carries such rows reads one `info` line naming each row bound. A row whose name two packages hold is left as it is and reported in one `warn` line naming every holder; nothing is picked. A row for an item the environment authored, or for a position, keeps naming no package. The backfill writes only `package_id`, never the switch itself, so the next boot finds nothing to change.
18+
19+
Nothing reads the package yet: every flow, action and catalog switch still applies by type and name exactly as before, and the activation doors answer as before.
20+
21+
Rows for an item the environment authored name no package, and SQL `UNIQUE` (like the memory and MongoDB drivers) exempts a row whose key part is NULL, so the new key does not constrain them. They keep one row per `(metadata_type, name)` through an index of their own, `uniq_sys_metadata_activation_packageless`: built at boot by `metadata-protocol` (SQLite and PostgreSQL: a partial index `WHERE package_id IS NULL`; MySQL 8.0.13+: a functional key part) and by `driver-mongodb` at collection sync (a `{ package_id: null }` partial filter). Who sees it: a second activation row naming no package for one item is refused `409 DUPLICATE_RECORD`, as it was before. A database that already holds such duplicates keeps them and gets one `error` line with the query that lists them, also reported by `os migrate duplicates`; nothing is deleted. MariaDB can build neither form and says so at `error`. The memory driver enforces declared indexes only.
22+
23+
On an existing SQL database the boot's schema sync creates the new key's index beside the old one, and once the package-less index stands, `os migrate plan` reports the old `(metadata_type, name)` index as superseded: one `replace_unique_index`, category safe, applied by `os migrate apply` with no `--allow-destructive`. The SQL driver reads a generated plain UNIQUE whose columns are an in-order proper subsequence of a declared global UNIQUE on the same table this way, because widening a unique key only admits rows the old key refused; when a column the key gained is nullable, it does so only beside a partial UNIQUE on the old columns, and until then keeps the old index without offering to drop it (MariaDB stays there). A UNIQUE on other columns still reads as an orphan, as before. Until the replace is applied the old index keeps refusing a second package's row of the same name, which nothing writes yet.

‎packages/cli/src/commands/migrate/duplicates.contract.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ import {
3030
type SeedTenancyExec,
3131
} from '@objectstack/metadata-protocol';
3232
import { collectDuplicateIdentifierReport } from './duplicates.js';
33+
// Paid at collection, not inside a clocked case: the command's schema-migration
34+
// boot reaches these through dynamic imports (check:test-source-alias).
35+
import '@objectstack/driver-turso';
36+
import '@objectstack/platform-objects/plugin';
37+
import '@objectstack/plugin-security';
38+
import '@objectstack/rest';
39+
import '@objectstack/runtime';
40+
import '@objectstack/service-datasource';
3341

3442
/**
3543
* The registry view the booted stack hands the command — the same objects
@@ -253,7 +261,7 @@ describe('#8928 os migrate duplicates — the report document', () => {
253261
});
254262
});
255263

256-
it('names the four kernel:ready indexes, and the migration behind each — none for the retired sys_view_definition (ADR-0131 D13)', async () => {
264+
it('names the five kernel:ready indexes, and the migration behind each — none for the retired sys_view_definition (ADR-0131 D13)', async () => {
257265
const report = await collect();
258266
expect(
259267
report.runtimeIndexPreflight.map((p) => `${p.migration}:${p.table}:${p.index}`),
@@ -264,6 +272,9 @@ describe('#8928 os migrate duplicates — the report document', () => {
264272
// One admin-global default (an empty User) per (organization, topic,
265273
// channel): service-messaging's preference table, ADR-0118 D1.
266274
'ensureNotificationPreferenceIdentityIndex:sys_notification_preference:uniq_sys_notification_preference_a22d7d27',
275+
// One package-less activation row per (metadata_type, name), ADR-0150 D4:
276+
// an index added beside the ledger's declared key, under its own name.
277+
'ensureActivationLedgerPackagelessIndex:sys_metadata_activation:uniq_sys_metadata_activation_packageless',
267278
]);
268279
});
269280

‎packages/cli/src/commands/migrate/duplicates.integration.test.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ import {
6363
import { bootSchemaStack } from '../../utils/schema-migrate.js';
6464
import { isExitSignal } from '../../utils/format.js';
6565
import MigrateDuplicates, { collectDuplicateIdentifierReport } from './duplicates.js';
66+
// Paid at collection, not inside a clocked case: the command's schema-migration
67+
// boot reaches these through dynamic imports (check:test-source-alias).
68+
import '@objectstack/driver-turso';
69+
import '@objectstack/platform-objects/plugin';
70+
import '@objectstack/plugin-security';
71+
import '@objectstack/rest';
72+
import '@objectstack/runtime';
73+
import '@objectstack/service-datasource';
6674

6775
const HERE = dirname(fileURLToPath(import.meta.url));
6876
/** This package's root, where oclif reads its own manifest from. */
@@ -311,9 +319,10 @@ describe('#8928 os migrate duplicates — against a really booted stack', () =>
311319
// sees that something is blocked without reading every entry.
312320
expect(produced.summary.runtimeIndexesBlocked).toBe(1);
313321
expect(produced.summary.runtimeIndexBlockingRows).toBe(2);
314-
// `sys_setting` is absent on this fixture; whatever each status, the four
315-
// indexes are all accounted for.
316-
expect(produced.runtimeIndexPreflight).toHaveLength(4);
322+
// `sys_setting` is absent on this fixture; whatever each status, the five
323+
// indexes (the fifth is the activation ledger's package-less index,
324+
// ADR-0150 D4) are all accounted for.
325+
expect(produced.runtimeIndexPreflight).toHaveLength(5);
317326
expect(produced.reportVersion).toBe(2);
318327

319328
// The whole run — boot included — wrote nothing. If a future change arms a

‎packages/core/src/utils/metadata-activation-store.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,10 @@ import { describe, it, expect, vi } from 'vitest';
3838
import { assertEngineUpdateDispatch } from '@objectstack/metadata-core';
3939

4040
import {
41+
backfillActivationLedgerPackages,
4142
InMemoryMetadataActivationStore,
4243
listPackageMetadataActivations,
44+
type ActivationLedgerHolder,
4345
METADATA_ACTIVATION_TABLE,
4446
ObjectStoreMetadataActivationStore,
4547
} from './metadata-activation-store.js';
@@ -470,3 +472,132 @@ describe('listPackageMetadataActivations — one package\'s rows across types (#
470472
expect(engine.find).not.toHaveBeenCalled();
471473
});
472474
});
475+
476+
/**
477+
* A STATEFUL ledger for the backfill: `update` patches the row it addresses, so
478+
* a second run reads what the first one wrote. The backfill's one read is
479+
* unscoped (`where: {}`), so the double answers every row and refuses any other
480+
* WHERE rather than filtering it.
481+
*/
482+
function makeLedger(rows: any[]) {
483+
const table = rows.map((r) => ({ ...r }));
484+
const updates: Array<{ data: any; options: any }> = [];
485+
const engine = {
486+
find: vi.fn(async (_object: string, options?: any) => {
487+
if (Object.keys(options?.where ?? {}).length > 0) {
488+
throw new Error('makeLedger: the backfill reads the whole ledger; a scoped read is not modelled');
489+
}
490+
return table.map((r) => ({ ...r }));
491+
}),
492+
update: vi.fn(async (_object: string, data: any, options?: any) => {
493+
assertEngineUpdateDispatch(data, options);
494+
updates.push({ data, options });
495+
const row = table.find((r) => r.id === data.id);
496+
if (row) Object.assign(row, data);
497+
return data;
498+
}),
499+
};
500+
return { engine, table, updates };
501+
}
502+
503+
describe('backfillActivationLedgerPackages — rows with no package take their one holder (ADR-0150 D8 row R4)', () => {
504+
const holders: Record<string, ActivationLedgerHolder> = {
505+
'flow:nightly_sync': { kind: 'package', packageId: 'crm' },
506+
'sharing_rule:share_open': { kind: 'ambiguous', candidates: ['crm', 'support'] },
507+
'permission:env_set': { kind: 'environment' },
508+
'action:gone': { kind: 'unheld' },
509+
'position:crm_manager': { kind: 'unaddressed' },
510+
'action:mark_done': { kind: 'package', packageId: 'other' },
511+
};
512+
const holderOf = vi.fn((type: string, name: string): ActivationLedgerHolder =>
513+
holders[`${type}:${name}`] ?? { kind: 'unheld' });
514+
const rows = () => [
515+
{ id: 'r1', metadata_type: 'flow', name: 'nightly_sync', package_id: null, active: false },
516+
{ id: 'r2', metadata_type: 'sharing_rule', name: 'share_open', active: false },
517+
{ id: 'r3', metadata_type: 'permission', name: 'env_set', package_id: null, active: false },
518+
{ id: 'r4', metadata_type: 'action', name: 'gone', package_id: null, active: true },
519+
{ id: 'r5', metadata_type: 'position', name: 'crm_manager', package_id: null, active: false },
520+
// Already bound: never read as a candidate, even where the resolver
521+
// would now answer a different package.
522+
{ id: 'r6', metadata_type: 'action', name: 'mark_done', package_id: 'crm', active: 0 },
523+
];
524+
525+
it('binds a single-holder row to its package, writing package_id alone, under the system context', async () => {
526+
const { engine, table, updates } = makeLedger(rows());
527+
const report = await backfillActivationLedgerPackages(engine, holderOf);
528+
529+
expect(report.bound).toEqual([{ metadataType: 'flow', name: 'nightly_sync', packageId: 'crm' }]);
530+
expect(updates).toHaveLength(1);
531+
// `active` is the administrator's choice: the backfill never writes it.
532+
expect(updates[0].data).toEqual({ id: 'r1', package_id: 'crm' });
533+
expect(updates[0].options?.context?.isSystem).toBe(true);
534+
expect(table.find((r) => r.id === 'r1')).toMatchObject({ package_id: 'crm', active: false });
535+
});
536+
537+
it('leaves an ambiguous row as it is and reports EVERY candidate — never a guess', async () => {
538+
const { engine, table, updates } = makeLedger(rows());
539+
const report = await backfillActivationLedgerPackages(engine, holderOf);
540+
541+
expect(report.ambiguous).toEqual([
542+
{ metadataType: 'sharing_rule', name: 'share_open', candidates: ['crm', 'support'] },
543+
]);
544+
expect(updates.some((u) => u.data.id === 'r2')).toBe(false);
545+
expect(table.find((r) => r.id === 'r2')?.package_id).toBeUndefined();
546+
});
547+
548+
it('leaves the environment\'s own item, an unheld name and an unaddressed type null, saying why', async () => {
549+
const { engine, updates } = makeLedger(rows());
550+
const report = await backfillActivationLedgerPackages(engine, holderOf);
551+
552+
expect(report.unchanged).toEqual([
553+
{ metadataType: 'permission', name: 'env_set', reason: 'environment' },
554+
{ metadataType: 'action', name: 'gone', reason: 'unheld' },
555+
{ metadataType: 'position', name: 'crm_manager', reason: 'unaddressed' },
556+
]);
557+
expect(updates.map((u) => u.data.id)).toEqual(['r1']);
558+
});
559+
560+
it('never asks about, or moves, a row that already names a package', async () => {
561+
holderOf.mockClear();
562+
const { engine, updates } = makeLedger(rows());
563+
await backfillActivationLedgerPackages(engine, holderOf);
564+
565+
expect(holderOf).not.toHaveBeenCalledWith('action', 'mark_done');
566+
expect(updates.some((u) => u.data.id === 'r6')).toBe(false);
567+
});
568+
569+
it('is re-runnable: the second run over the same ledger binds nothing and writes nothing', async () => {
570+
const { engine, updates } = makeLedger(rows());
571+
await backfillActivationLedgerPackages(engine, holderOf);
572+
const writesAfterFirst = updates.length;
573+
574+
const second = await backfillActivationLedgerPackages(engine, holderOf);
575+
576+
expect(writesAfterFirst).toBe(1);
577+
expect(updates).toHaveLength(writesAfterFirst);
578+
expect(second.bound).toEqual([]);
579+
// The ambiguous row is still reported, still with every candidate.
580+
expect(second.ambiguous).toEqual([
581+
{ metadataType: 'sharing_rule', name: 'share_open', candidates: ['crm', 'support'] },
582+
]);
583+
});
584+
585+
it('a dry run reports the same binding and writes nothing', async () => {
586+
const { engine, table, updates } = makeLedger(rows());
587+
const report = await backfillActivationLedgerPackages(engine, holderOf, { dryRun: true });
588+
589+
expect(report.bound).toEqual([{ metadataType: 'flow', name: 'nightly_sync', packageId: 'crm' }]);
590+
expect(updates).toHaveLength(0);
591+
expect(table.find((r) => r.id === 'r1')?.package_id).toBeNull();
592+
});
593+
594+
it('reads the whole ledger once, unscoped, under the system context', async () => {
595+
const { engine } = makeLedger(rows());
596+
await backfillActivationLedgerPackages(engine, holderOf);
597+
expect(engine.find).toHaveBeenCalledTimes(1);
598+
expect(engine.find).toHaveBeenCalledWith(METADATA_ACTIVATION_TABLE, expect.objectContaining({
599+
where: {},
600+
context: expect.objectContaining({ isSystem: true }),
601+
}));
602+
});
603+
});

0 commit comments

Comments
 (0)