Skip to content

Commit 1ac2dab

Browse files
committed
Merge origin/main into the ADR-0067 amendment branch
Claude-Session: https://claude.ai/code/session_01ADHkmSFzVdDvrh768eFPoV Co-authored-by: Claude <noreply@anthropic.com>
2 parents 3648782 + d3bea96 commit 1ac2dab

13 files changed

Lines changed: 769 additions & 77 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
fix(scenarios): a card that keeps to working days stays on working days on every run date
6+
7+
Clause-②: yes (widening) — new optional key `ScenarioCardSchema.workingDays` (`.`)
8+
Metadata-protocol: none
9+
10+
A scenario card can declare `workingDays: true`. The run-date rebase then moves its `asOf` onto the run
11+
date and every other date by whole working days instead of whole days, so a Monday-to-Friday leave day,
12+
and the weekday an ask names, stays on a working day however far from `asOf` the card runs (a weekend run
13+
date moves them as for the Friday before it). The loader refuses such a card when its `asOf` or any other date
14+
it holds falls on a weekend, or it has no `asOf`. The `leave_balances` card declares it, so its request days,
15+
balances and truths keep their meaning on every run date.
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.

‎docs/qa/scenarios/README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ Chinese and an English title, and every reader picks one of the two explicitly.
4848
unique across the library. The app lives in the namespace `demo` + code (`democrm`) wherever
4949
it is built, scored or exported, and every item it declares carries that prefix.
5050

51+
**The run moves the card's dates.** `asOf` is the card's today as written, not the day it runs on.
52+
Before a card runs, the runner moves its dates onto the run date: `asOf` becomes the run date, and
53+
every ISO date under `run` and `iterate`, and every date an `ask` writes in its text, moves with it
54+
(one whole-day delta, so every interval between two dates is kept; truths over a calendar window
55+
are computed again over the moved seed). An author therefore must not rely on a fixed calendar
56+
date or on the day of the week: a date written as a Wednesday may run as a Sunday, an ask's weekday
57+
name is written again for the moved date, and a `this_month` window holds whatever the moved seed
58+
puts in it. A card whose dates keep to working days (leave taken Monday to Friday, a day count that
59+
skips weekends) declares `"workingDays": true`: `asOf` and every other date it holds must then fall
60+
on a Monday to Friday, or the card is refused, and the run moves those dates by whole working days
61+
instead, so a working day stays a working day on every run date and N working days between two
62+
dates stay N (a weekend run date moves them as for the Friday before it). Public holidays are out
63+
of scope either way.
64+
5165
**Counts.** The default band is 8–10 questions and 4–6 operations. A card below 8 questions
5266
or 4 operations states why in `run.countsReason`, or it is refused; a `starter` or `delivery`
5367
card has no such excuse ([Tiers](#tiers)).

‎docs/qa/scenarios/leave_balances.json‎

Lines changed: 33 additions & 32 deletions
Large diffs are not rendered by default.

‎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+
});

0 commit comments

Comments
 (0)