Skip to content

Commit d3bea96

Browse files
fix(metadata-protocol): land the sys_metadata ACTIVE overlay index on PostgreSQL (#34032)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbNTugWasvhTMrtCZiFGrZYK)_ Fixes #33901 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:PostgreSQL 上 `sys_metadata` 的 ACTIVE 覆盖层唯一键现在真正落成与 SQLite 相同的部分 NULL 安全唯一索引;启动时不再打印 2BP01 的 DATABASE_ERROR。 - 为什么改:原先 PostgreSQL 上留下的是声明的 NULL-distinct 唯一约束,`bundle_member` 几乎全为 NULL,等于没有约束,同一 (type, name, package) 可以有两条 ACTIVE 覆盖行,读取结果不确定。 - 风险与回滚:只改运行时索引迁移的调用方式(传入表名与方言,执行通道返回结果);已有重复 ACTIVE 行时保留旧约束、不删任何行,只打印 ADR-0120 D4 报告。回滚即 revert 本 PR,下次启动索引保持现状不会被破坏。 - 先看:`packages/metadata-protocol/src/protocol-overlay-index.ts`(执行通道改为返回结果并传 client,这是本修复的另一半);`packages/metadata-protocol/src/migrations/overlay-index.ts` 的 `ensureOverlayStateIndex`;`identity-index.live-postgres.test.ts` 末尾新增的 describe。 - 两分钟验证:在空 PostgreSQL 库上 `os dev -d postgres://…` 启动、登录后请求 `GET /api/v1/meta/_drafts`,日志中 DATABASE_ERROR 为 0 行;`select indexdef from pg_indexes where indexname='idx_sys_metadata_overlay_active'` 显示 `COALESCE(package_id…), COALESCE(bundle_member…) WHERE state = 'active'`。 - 需要你做的:无,席位落地。 ## What changes - `ensureOverlayStateIndex` / `ensureMetadataOverlayIndexes` take `opts.client` and pass `table: sys_metadata` and that client to `probeThenReplaceIndex`. On PostgreSQL this selects the arm the `sys_setting` and `sys_notification_preference` identity migrations already take: it frees the constraint-held name with `ALTER TABLE … DROP CONSTRAINT IF EXISTS`, builds the partial NULL-safe index, and answers `created` only when the definition reads back equal to the probe's. - The boot call site (`protocol-overlay-index.ts`, `ensureOverlayIndex`) resolves the client name off the driver (`resolveDriverClientName`) and its raw-SQL seam now **returns** the statement's result. This half was needed as well: the seam used to discard every result, so with only table and client passed, the PostgreSQL read-back fails at `probe` on every boot. Measured below (ablation 3). The draft index, which lands today, would then stop landing too. - Duplicate ACTIVE rows: the previous constraint stays, no row is deleted, and the existing ADR-0120 D4 `[metadata-protocol] cannot rebuild 'idx_sys_metadata_overlay_active'` line is printed. It names the unenforced key, the listing query and `os migrate duplicates`. - Changeset: `@objectstack/metadata-protocol` patch, plus `@objectstack/rest` patch. `rest` lists metadata-protocol as a devDependency and its tsup build inlines it, so `rest/dist` ships its own copy of this migration. Measured: `grep -l idx_sys_metadata_overlay_active_probe` finds it in `packages/rest/dist/index.js` and `index.cjs`, and the rebuilt rest dist carries the fix. ## Tests - `overlay-index.test.ts`: a new top-level describe, `the PostgreSQL arm is taken (constraint-held name)`. It runs in Test Core with no server, using a double that answers like PostgreSQL: a constraint-held name refuses `DROP INDEX`, `IF NOT EXISTS` on a held name is a no-op, and `pg_get_indexdef` reads back. Three cases: the migration lands the partial key with no error line; the boot call site resolves the client off the driver and hands the read-back its rows; and when the drop cannot free the name, the result is `failed` with the D4 "existing index is unchanged" line, never `created`. - `identity-index.live-postgres.test.ts` (the existing live-PostgreSQL harness for this seam's callers, which the CI live step selects by its `live-postgres` substring): a new top-level describe, `sys_metadata overlay ACTIVE key on a LIVE PostgreSQL`. It drives `ensureOverlayIndex`, with a driver shaped like `SqlDriver` and the knex-compiled declared constraint as the fixture. Case 1: a fresh database ends with the partial index, `console.error`/`warn` are never called, a second ACTIVE row is refused with 23505, an ACTIVE+DRAFT pair is admitted, and a second boot is quiet and idempotent. Case 2: with duplicate ACTIVE rows the constraint stays, both rows survive, the draft index still lands, and exactly one D4 line names the key, the listing query and `os migrate duplicates`. <details><summary>Ablations (each restored with blob == HEAD, `git diff HEAD` empty, by scripts/ablation-replace.mjs)</summary> 1. Caller passes no table/client (`overlay-index.ts`, the two option lines deleted): `Tests 4 failed | 37 passed (41)`. All three Test Core PG-arm cases go red (`expected [ …(10) ] to include 'ALTER TABLE sys_metadata DROP CONSTRA…'`, `expected 'created' to be 'failed'`), and so does live case 1 (`expected true to be false`: the constraint still holds). 2. The call site passes `{}` instead of the client: `Tests 2 failed | 39 passed (41)`. The call-site case and live case 1 go red. 3. The call-site seam discards the result again (`await resolved(sql)`): `Tests 3 failed | 38 passed (41)`. The error is `the read-back of 'idx_sys_metadata_overlay_active_probe' returned no result set`, and the draft probe fails the same way. 4. Drop without a replacement in the duplicate case (`partial-index-probe.ts`, the PostgreSQL arm frees the name when the probe fails): live case 2 goes red, `expected false to be true` at the constraint-holds assertion. The first attempt was a no-op: the replacement contained the anchor, so the tool refused it ("anchor count moved 1 -> 1"). It was re-run with a different anchor. 5. Duplicates silently deleted before the probe (`DELETE … USING …` injected into `ensureOverlayStateIndex`): live case 2 goes red, `expected false to be true`. </details> ## Acceptance notes - The new pins live in the existing shared files as top-level describes, not in a new card-named file. AGENTS.md (ruling record 6583487846) requires this, and a live pin outside a `live-postgres` path would never be selected by the CI live step. - `protocol-overlay-index.ts` is outside the claim's stated surface. The client can only be resolved at the call site, and the seam's discarded result blocks the read-back, so this file had to change for the ruling to hold. - With duplicates present, the driver still prints its own `[sql-driver] DATABASE_ERROR … (23505) … could not create unique index "idx_sys_metadata_overlay_active_probe"` line ahead of the D4 line. This happens on every dialect, comes from the probe, and predates this change. - `ensureOverlayIndex` resolves its driver with `engine.driver ?? engine.getDriver()`, not `getDriverForObject('sys_metadata')` as the identity migrations do. On a kernel where platform objects sit on a non-default datasource, it could address the wrong connection. This is inferred from reading the code, not reproduced, so it is noted here and not filed. ## Verification Real boots, `examples/app-todo` through `objectstack dev -d postgres://…`, against a private PostgreSQL 16.15 cluster: <details><summary>Before (origin/main 895783a, fresh database)</summary> After sign-in and `GET /api/v1/meta/_drafts` (200), there is 1 line, `[sql-driver] DATABASE_ERROR — the backend refused a raw statement (2BP01) … cannot drop index idx_sys_metadata_overlay_active because constraint idx_sys_metadata_overlay_active on table sys_metadata requires it`. `pg_indexes` shows `UNIQUE … (type, name, package_id, bundle_member)`, `pg_constraint` shows contype `u`, and no `[metadata-protocol]` line is printed. </details> <details><summary>After (this branch, fresh database)</summary> 0 DATABASE_ERROR lines. The `_active` index reads `CREATE UNIQUE INDEX idx_sys_metadata_overlay_active ON public.sys_metadata USING btree (type, name, COALESCE(package_id, ''::character varying), COALESCE(bundle_member, ''::character varying)) WHERE ((state)::text = 'active'::text)`, and no constraint remains under the name. The `/meta` write doors keep their answers: `PUT /meta/view/todo_task.h4_probe` twice (200, active), `?mode=draft` twice beside the active row (200), `POST …/publish` (200), then `PUT` again (200). One active row results and no DATABASE_ERROR line is printed. </details> <details><summary>After, database already holding two ACTIVE rows of one key</summary> The constraint stays (`u`), both rows survive, and one `[metadata-protocol] cannot rebuild 'idx_sys_metadata_overlay_active' on "sys_metadata" — existing rows violate (type, name, COALESCE(package_id, ''), COALESCE(bundle_member, '')) among state='active'. The previous index is left in place … List them with: SELECT … — or run "os migrate duplicates" — then restart (ADR-0120 D4).` line is printed. </details> <details><summary>Local gates and tests</summary> - `@objectstack/metadata-protocol` at merged head ed3bc40, with `OS_TEST_POSTGRES_URL` set: `Test Files 347 passed | 4 skipped (351)`, `Tests 22931 passed | 19 skipped (22950)`; the 4 skipped files are the `live-mysql` ones, since no MySQL URL was set. `typecheck` (tsc --noEmit) exits 0. - `pnpm lint` (eslint . --no-inline-config) exits 0. - `dispatch-gates --commands` on this diff derived 63 commands. All 63 were run and each exit code was captured before any pipe: 62 exited 0. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, no dist) on the first pass and 0 on the re-run after a full build: 123 entry points, 72 packages. `--ran` reconciliation: 63 derived, 63 run, 0 NOT-MEASURED (a derived zero). - Direct dependents of metadata-protocol: the verify lock timed out (exit 99) on the first attempt, so these are NOT MEASURED locally and left to CI's Test Core. `@objectstack/rest` (which inlines this module) was then run: `Tests 4 failed | 8750 passed`. All 4 failures are in two test files that origin/main added in this merge (`aggregate-measure-filter-pushdown.test.ts`, `aggregation-filter-where-doors.test.ts`), each `TypeError: page.entries is not iterable`, read against an objectql dist not yet rebuilt after main's aggregate changes. They do not touch the overlay index. The re-run after rebuilding rest's closure is recorded in the report. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 529ed7d commit d3bea96

5 files changed

Lines changed: 306 additions & 7 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/rest': patch
4+
---
5+
6+
fix(metadata-protocol): on PostgreSQL the `sys_metadata` ACTIVE overlay key becomes the partial NULL-safe unique index, as on SQLite, instead of the declared NULL-distinct constraint
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
On PostgreSQL the declared `idx_sys_metadata_overlay_active` is a UNIQUE constraint over `(type, name, package_id, bundle_member)`. `bundle_member` is NULL on nearly every row, so this constraint enforced nothing. Two ACTIVE overlays for one `(type, name, package)` could both be stored, and which one a metadata read returned was undefined. The runtime migration that replaces the constraint ran `DROP INDEX` on it. PostgreSQL refuses that (2BP01), so every process printed one `[sql-driver] DATABASE_ERROR … (2BP01)` line at its first `sys_metadata` read, kept the constraint and reported nothing else.
12+
13+
The migration now gets the dialect and a seam that returns rows, so it takes the PostgreSQL path the `sys_setting` and `sys_notification_preference` identity migrations already take. That path frees the name with `ALTER TABLE … DROP CONSTRAINT`, builds `UNIQUE (type, name, COALESCE(package_id, ''), COALESCE(bundle_member, '')) WHERE state = 'active'`, and checks the result by reading the index definition back. The 2BP01 line no longer appears.
14+
15+
If the database already holds two ACTIVE rows for one key, the old constraint stays and no row is deleted. One `[metadata-protocol] cannot rebuild 'idx_sys_metadata_overlay_active'` line is printed at `error`. It names the key that is not enforced, gives the query that lists the blocking rows and points to `os migrate duplicates`. Resolve the duplicates and restart, and the next boot builds the index. If the name cannot be freed at all, the line says the existing index is unchanged. The step never reports success it did not get.

‎packages/metadata-protocol/src/migrations/identity-index.live-postgres.test.ts‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ import {
6262
NOTIFICATION_PREFERENCE_IDENTITY_INDEX_NAME,
6363
NOTIFICATION_PREFERENCE_TABLE,
6464
} from './notification-preference-identity-index.js';
65+
import {
66+
buildOverlayDuplicateProbeSql,
67+
OVERLAY_INDEX_NAMES,
68+
OVERLAY_PROBE_INDEX_NAMES,
69+
OVERLAY_TABLE,
70+
} from './overlay-index.js';
71+
import { ensureOverlayIndex } from '../protocol-overlay-index.js';
6572
import { currentLiveMysqlDatabase } from './live-mysql-database.testkit.js';
6673
import type { IndexExec } from './partial-index-probe.js';
6774

@@ -293,3 +300,146 @@ describe.skipIf(!PG_URL)('#26630 identity indexes on a LIVE PostgreSQL', () => {
293300
});
294301
});
295302
});
303+
304+
/**
305+
* The overlay ACTIVE key, landed on a live PostgreSQL by the boot call site.
306+
*
307+
* `sys-metadata.object.ts` declares `idx_sys_metadata_overlay_active` as a plain
308+
* unique over `(type, name, package_id, bundle_member)`, which the driver
309+
* materializes on PostgreSQL as a NULL-distinct UNIQUE CONSTRAINT — and with
310+
* `bundle_member` NULL on nearly every row it enforces nothing. The runtime
311+
* migration replaces it with the partial NULL-safe index SQLite carries, but on
312+
* PostgreSQL only when the call site hands the migration the dialect and a seam
313+
* that returns the read-back's rows. Before that it printed one raw 2BP01 per
314+
* process, kept the constraint, and reported nothing.
315+
*
316+
* Driven through `ensureOverlayIndex` (`protocol-overlay-index.ts`), the body
317+
* the protocol runs at its first `sys_metadata` read or write, with a driver
318+
* shaped like `SqlDriver` (`execute` plus `config.client`) over this file's
319+
* live connection. The fixture is the statement knex 3's PostgreSQL client
320+
* compiles `table.unique(['type','name','package_id','bundle_member'], {
321+
* indexName })` to, read off knex for this table.
322+
*/
323+
describe.skipIf(!PG_URL)('sys_metadata overlay ACTIVE key on a LIVE PostgreSQL', () => {
324+
let client: pg.Client;
325+
const ACTIVE = OVERLAY_INDEX_NAMES.active;
326+
const DRAFT = OVERLAY_INDEX_NAMES.draft;
327+
328+
const indexDef = async (name: string): Promise<string | undefined> => {
329+
const { rows } = await client.query<{ indexdef: string | null }>(
330+
`SELECT pg_get_indexdef(to_regclass('"${name}"')) AS indexdef`,
331+
);
332+
return rows[0]?.indexdef ?? undefined;
333+
};
334+
335+
const constraintHolds = async (): Promise<boolean> => {
336+
const { rows } = await client.query(
337+
'SELECT 1 FROM pg_constraint WHERE conname = $1 AND conrelid = to_regclass($2)',
338+
[ACTIVE, `"${OVERLAY_TABLE}"`],
339+
);
340+
return rows.length > 0;
341+
};
342+
343+
const insertOverlay = (id: string, state: string, packageId: string | null = null) =>
344+
client.query(
345+
'INSERT INTO sys_metadata (id, type, name, package_id, bundle_member, state) ' +
346+
"VALUES ($1, 'object', 'probe_dup', $2, NULL, $3)",
347+
[id, packageId, state],
348+
);
349+
350+
/** One protocol boot: a fresh host, so the run-once flag is unset. */
351+
const boot = async (): Promise<{ error: ReturnType<typeof vi.spyOn>; warn: ReturnType<typeof vi.spyOn> }> => {
352+
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
353+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
354+
const driver = { execute: (sql: string) => client.query(sql), config: { client: 'pg' } };
355+
const host = {
356+
engine: { driver },
357+
ensureOverlayMembersBackfilled: async () => undefined,
358+
overlayIndexEnsured: false,
359+
};
360+
await ensureOverlayIndex.call(host as any);
361+
return { error, warn };
362+
};
363+
364+
beforeAll(async () => {
365+
client = new pg.Client({ connectionString: PG_URL });
366+
await client.connect();
367+
await client.query(`CREATE SCHEMA IF NOT EXISTS "${SCHEMA}"`);
368+
await client.query(`SET search_path TO "${SCHEMA}"`);
369+
});
370+
371+
afterAll(async () => {
372+
if (!client) return;
373+
await client.query('SET search_path TO "$user", public');
374+
await client.query(`DROP SCHEMA IF EXISTS "${SCHEMA}" CASCADE`);
375+
await client.end();
376+
});
377+
378+
beforeEach(async () => {
379+
vi.restoreAllMocks();
380+
await client.query('DROP TABLE IF EXISTS sys_metadata');
381+
await client.query(
382+
'CREATE TABLE sys_metadata (id VARCHAR(255) PRIMARY KEY, type VARCHAR(255), name VARCHAR(255), ' +
383+
'package_id VARCHAR(255), bundle_member VARCHAR(255), state VARCHAR(255))',
384+
);
385+
// The driver's statement, as knex compiles it (block header).
386+
await client.query(
387+
`alter table "sys_metadata" add constraint "${ACTIVE}" ` +
388+
'unique ("type", "name", "package_id", "bundle_member")',
389+
);
390+
expect(await constraintHolds()).toBe(true);
391+
});
392+
393+
it('a fresh database ends with the partial NULL-safe ACTIVE index, and no line is printed', async () => {
394+
const { error, warn } = await boot();
395+
396+
expect(error).not.toHaveBeenCalled();
397+
expect(warn).not.toHaveBeenCalled();
398+
expect(await constraintHolds()).toBe(false);
399+
expect(await indexDef(ACTIVE)).toMatch(
400+
/^CREATE UNIQUE INDEX idx_sys_metadata_overlay_active ON \S+ USING btree \(type, name, COALESCE\(package_id, ''::character varying\), COALESCE\(bundle_member, ''::character varying\)\) WHERE \(\(state\)::text = 'active'::text\)$/,
401+
);
402+
expect(await indexDef(DRAFT)).toContain("WHERE ((state)::text = 'draft'::text)");
403+
expect(await indexDef(OVERLAY_PROBE_INDEX_NAMES.active)).toBeUndefined();
404+
405+
// What the key is for: a second ACTIVE row of one (type, name, package)
406+
// is refused with SQLSTATE 23505, and the ACTIVE+DRAFT pair is legal.
407+
await insertOverlay('a1', 'active');
408+
await expect(insertOverlay('a2', 'active')).rejects.toMatchObject({ code: '23505' });
409+
await insertOverlay('d1', 'draft');
410+
411+
// A second boot over the same database is quiet and leaves it as it is.
412+
const first = await indexDef(ACTIVE);
413+
const again = await boot();
414+
expect(again.error).not.toHaveBeenCalled();
415+
expect(again.warn).not.toHaveBeenCalled();
416+
expect(await indexDef(ACTIVE)).toBe(first);
417+
});
418+
419+
it('duplicate ACTIVE rows: the constraint stays, no row is deleted, and the D4 line names the key and the rows', async () => {
420+
// Admitted by the NULL-distinct constraint — the population a boot meets.
421+
await insertOverlay('dup1', 'active');
422+
await insertOverlay('dup2', 'active');
423+
424+
const { error } = await boot();
425+
426+
expect(await constraintHolds()).toBe(true);
427+
expect(await indexDef(OVERLAY_PROBE_INDEX_NAMES.active)).toBeUndefined();
428+
const { rows } = await client.query('SELECT id FROM sys_metadata ORDER BY id');
429+
expect(rows.map((r) => r.id)).toEqual(['dup1', 'dup2']);
430+
// The draft index is independent and still lands.
431+
expect(await indexDef(DRAFT)).toContain("WHERE ((state)::text = 'draft'::text)");
432+
433+
expect(error).toHaveBeenCalledTimes(1);
434+
const message = String(error.mock.calls[0]![0]);
435+
expect(message).toContain(`[metadata-protocol] cannot rebuild '${ACTIVE}'`);
436+
expect(message).toContain("COALESCE(package_id, ''), COALESCE(bundle_member, '')");
437+
expect(message).toContain('os migrate duplicates');
438+
expect(message).toContain(buildOverlayDuplicateProbeSql('active'));
439+
// …and the shipped listing names the blocking rows on this database.
440+
const listed = await client.query(buildOverlayDuplicateProbeSql('active'));
441+
expect(listed.rows).toEqual([
442+
expect.objectContaining({ type: 'object', name: 'probe_dup', duplicate_rows: '2' }),
443+
]);
444+
});
445+
});

‎packages/metadata-protocol/src/migrations/overlay-index.test.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
type OverlayMemberBackfillEngine,
2727
} from './overlay-index.js';
2828
import type { IndexExec } from './partial-index-probe.js';
29+
import { ensureOverlayIndex } from '../protocol-overlay-index.js';
2930

3031
/**
3132
* `sys_metadata` — overlay uniqueness survives a failed tightening (#6418).
@@ -847,3 +848,120 @@ describe('sys_metadata overlay key — an action\'s bound object in `bundle_memb
847848
expect(updates, 'the backfill leaves an action row\'s member to its writer').toEqual([]);
848849
});
849850
});
851+
852+
/**
853+
* The PostgreSQL arm reaches the overlay index too.
854+
*
855+
* On PostgreSQL the declared `idx_sys_metadata_overlay_active` is a UNIQUE
856+
* CONSTRAINT (knex's `table.unique()`), so `DROP INDEX` on it is refused with
857+
* 2BP01 and `CREATE UNIQUE INDEX IF NOT EXISTS` under the held name is a no-op.
858+
* `probeThenReplaceIndex` frees such a name and confirms the rebuild by reading
859+
* the definition back — but only when the caller passes the table and the
860+
* client name. The other two callers did; this one did not, so the NULL-distinct
861+
* constraint stayed and the step answered `created`.
862+
*
863+
* The double below answers the way PostgreSQL does for exactly the statements
864+
* the migration issues: a constraint-held name refuses `DROP INDEX` and is
865+
* freed only by `ALTER TABLE … DROP CONSTRAINT`, a held name makes `CREATE …
866+
* IF NOT EXISTS` a no-op, and `pg_get_indexdef` reads back whatever the name
867+
* holds. The live cell is `identity-index.live-postgres.test.ts`.
868+
*/
869+
describe('sys_metadata overlay index — the PostgreSQL arm is taken (constraint-held name)', () => {
870+
const ACTIVE = OVERLAY_INDEX_NAMES.active;
871+
const DECLARED_DEF = 'CREATE UNIQUE INDEX idx_sys_metadata_overlay_active ON public.sys_metadata USING btree (type, name, package_id, bundle_member)';
872+
873+
function pgDouble() {
874+
const statements: string[] = [];
875+
/** name → definition; a `constraint` entry can only be dropped as one. */
876+
const held = new Map<string, { def: string; constraint: boolean }>();
877+
held.set(ACTIVE, { def: DECLARED_DEF, constraint: true });
878+
const exec: IndexExec = async (sql: string) => {
879+
statements.push(sql);
880+
let m = /^ALTER TABLE sys_metadata DROP CONSTRAINT IF EXISTS (\S+)$/.exec(sql);
881+
if (m) {
882+
if (held.get(m[1]!)?.constraint) held.delete(m[1]!);
883+
return { rows: [] };
884+
}
885+
m = /^DROP INDEX IF EXISTS (\S+)$/.exec(sql);
886+
if (m) {
887+
if (held.get(m[1]!)?.constraint) {
888+
throw Object.assign(
889+
new Error(`cannot drop index ${m[1]} because constraint ${m[1]} on table sys_metadata requires it`),
890+
{ code: '2BP01' },
891+
);
892+
}
893+
held.delete(m[1]!);
894+
return { rows: [] };
895+
}
896+
m = /^CREATE UNIQUE INDEX IF NOT EXISTS (\S+) ON (.*)$/.exec(sql);
897+
if (m) {
898+
if (!held.has(m[1]!)) held.set(m[1]!, { def: `CREATE UNIQUE INDEX ${m[1]} ON public.${m[2]}`, constraint: false });
899+
return { rows: [] };
900+
}
901+
m = /^SELECT pg_get_indexdef\(to_regclass\('"(\S+)"'\)\) AS indexdef$/.exec(sql);
902+
if (m) return { rows: [{ indexdef: held.get(m[1]!)?.def ?? null }] };
903+
throw new Error(`statement the double does not model: ${sql}`);
904+
};
905+
return { exec, statements, held };
906+
}
907+
908+
it('frees the constraint-held name and lands the partial NULL-safe key, quietly', async () => {
909+
const { exec, statements, held } = pgDouble();
910+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
911+
912+
const result = await ensureMetadataOverlayIndexes(exec, logger, { client: 'pg' });
913+
914+
expect(result.active).toEqual({ status: 'created', fallback: 'not-attempted' });
915+
expect(result.draft).toEqual({ status: 'created', fallback: 'not-attempted' });
916+
expect(statements).toContain(`ALTER TABLE sys_metadata DROP CONSTRAINT IF EXISTS ${ACTIVE}`);
917+
expect(held.get(ACTIVE)).toEqual({ def: `CREATE UNIQUE INDEX ${ACTIVE} ON public.sys_metadata (${overlayIndexKeyParts().join(', ')}) WHERE state = 'active'`, constraint: false });
918+
expect(logger.error).not.toHaveBeenCalled();
919+
expect(logger.warn).not.toHaveBeenCalled();
920+
});
921+
922+
it('the boot call site resolves the client off the driver and hands the read-back its result', async () => {
923+
const { exec, statements, held } = pgDouble();
924+
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
925+
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
926+
try {
927+
const host = {
928+
engine: { driver: { execute: (sql: string) => exec(sql), config: { client: 'pg' } } },
929+
ensureOverlayMembersBackfilled: async () => undefined,
930+
overlayIndexEnsured: false,
931+
};
932+
await ensureOverlayIndex.call(host as any);
933+
934+
expect(statements).toContain(`ALTER TABLE sys_metadata DROP CONSTRAINT IF EXISTS ${ACTIVE}`);
935+
expect(held.get(ACTIVE)?.constraint).toBe(false);
936+
expect(held.get(ACTIVE)?.def).toContain("WHERE state = 'active'");
937+
expect(errorSpy).not.toHaveBeenCalled();
938+
expect(warnSpy).not.toHaveBeenCalled();
939+
} finally {
940+
errorSpy.mockRestore();
941+
warnSpy.mockRestore();
942+
}
943+
});
944+
945+
it('a name the drop cannot free is reported as NOT enforced (ADR-0120 D4), never as created', async () => {
946+
const { exec, held } = pgDouble();
947+
// Something depends on the constraint, so the constraint drop is refused
948+
// too; the `IF NOT EXISTS` create is then a no-op under the held name.
949+
const refusing: IndexExec = async (sql: string) => {
950+
if (sql.startsWith('ALTER TABLE sys_metadata DROP CONSTRAINT')) {
951+
throw Object.assign(new Error(`cannot drop constraint ${ACTIVE} on table sys_metadata because other objects depend on it`), { code: '2BP01' });
952+
}
953+
return exec(sql);
954+
};
955+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
956+
957+
const result = await ensureOverlayStateIndex(refusing, 'active', logger, { client: 'pg' });
958+
959+
expect(result.status).toBe('failed');
960+
expect(result.detail).toContain('cannot drop constraint');
961+
expect(held.get(ACTIVE)).toEqual({ def: DECLARED_DEF, constraint: true });
962+
expect(logger.error).toHaveBeenCalledTimes(1);
963+
const msg = String(logger.error.mock.calls[0]![0]);
964+
expect(msg).toContain(`[metadata-protocol] could not rebuild '${ACTIVE}'`);
965+
expect(msg).toContain('the existing index is unchanged');
966+
});
967+
});

‎packages/metadata-protocol/src/migrations/overlay-index.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,7 @@ export async function ensureOverlayStateIndex(
344344
exec: IndexExec | undefined,
345345
state: OverlayIndexState,
346346
logger?: IndexMigrationLogger,
347+
opts: { client?: string } = {},
347348
): Promise<EnsureOverlayIndexResult> {
348349
if (!exec) return { status: 'no-driver', fallback: 'not-attempted' };
349350

@@ -352,6 +353,15 @@ export async function ensureOverlayStateIndex(
352353
indexName,
353354
probeIndexName: OVERLAY_PROBE_INDEX_NAMES[state],
354355
buildSql: (name) => buildOverlayIndexSql(name, state),
356+
// The table and the dialect select PostgreSQL's drop and read-back.
357+
// There the declared `…_active` name is held by a UNIQUE CONSTRAINT
358+
// (knex's `table.unique()`), which `DROP INDEX` cannot remove (2BP01);
359+
// without them the NULL-distinct constraint stayed and 'created' was
360+
// reported for a no-op `CREATE … IF NOT EXISTS`. A verdict the read-back
361+
// cannot confirm comes back 'failed' at 'verify' and is reported below.
362+
// `exec` must hand back the statement's result for that read-back.
363+
table: OVERLAY_TABLE,
364+
client: opts.client,
355365
});
356366

357367
if (outcome.status === 'created') return { status: 'created', fallback: 'not-attempted' };
@@ -401,10 +411,11 @@ export async function ensureOverlayStateIndex(
401411
export async function ensureMetadataOverlayIndexes(
402412
exec: IndexExec | undefined,
403413
logger?: IndexMigrationLogger,
414+
opts: { client?: string } = {},
404415
): Promise<Record<OverlayIndexState, EnsureOverlayIndexResult>> {
405416
return {
406-
active: await ensureOverlayStateIndex(exec, 'active', logger),
407-
draft: await ensureOverlayStateIndex(exec, 'draft', logger),
417+
active: await ensureOverlayStateIndex(exec, 'active', logger, opts),
418+
draft: await ensureOverlayStateIndex(exec, 'draft', logger, opts),
408419
};
409420
}
410421

0 commit comments

Comments
 (0)