You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d3bea96
Browse filesBrowse the repository at this point in the historyBrowse 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>
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.
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()=>{
0 commit comments