Skip to content

Commit 31c75dd

Browse files
committed
fix(metadata-protocol): the sys_setting duplicate query lists only rows the plain organization key refuses; re-pin turso, memory and sys_setting suites
Claude-Session: https://claude.ai/code/session_01NnXVu3vF2TKFLMi5Me4CUd Co-authored-by: Claude <noreply@anthropic.com>
1 parent e4c6ffe commit 31c75dd

7 files changed

Lines changed: 306 additions & 96 deletions

‎packages/drivers/driver-memory/src/memory-declared-index-unique.test.ts‎

Lines changed: 39 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,18 @@
4545
* ('acme', NULL, 'X') then ('acme', NULL, 'X') -> BOTH ACCEPTED (NULL-DISTINCT)
4646
* ('acme', 'A2', NULL) then ('acme', 'A2', NULL) -> BOTH ACCEPTED (NULL-DISTINCT)
4747
*
48-
* UNIQUE (COALESCE(organization_id,'__global__'), account_id, code) -- 'organization'
49-
* (NULL, 'A1', 'X') then (NULL, 'A1', 'X') -> second REFUSED (the org part FOLDS)
50-
* (NULL, 'A2', NULL) then (NULL, 'A2', NULL) -> BOTH ACCEPTED (NULL-DISTINCT wins)
48+
* UNIQUE (organization_id, account_id, code) -- 'organization'
49+
* (NULL, 'A1', 'X') then (NULL, 'A1', 'X') -> BOTH ACCEPTED (NULL-DISTINCT)
50+
* (NULL, 'A2', NULL) then (NULL, 'A2', NULL) -> BOTH ACCEPTED (NULL-DISTINCT)
5151
* ```
5252
*
5353
* So the composite rule is the field-level rule with a wider key, and NOT a new
54-
* invention: a NULL in any LISTED key column exempts the row, while a NULL
55-
* ORGANIZATION folds onto one bucket because its key part is an expression that
56-
* is never NULL. Both halves are pinned below.
54+
* invention: a NULL in ANY key part exempts the row — the organization's
55+
* included. Since ADR-0131 D1 the tenant column is NOT NULL and `driver-sql`
56+
* keys it plain; until then ADR-0120 D3 keyed it as
57+
* `COALESCE(organization_id,'__global__')`, which folded NULL organizations onto
58+
* one bucket (the second `(NULL, 'A1', 'X')` above was REFUSED). That fold is
59+
* retired on both surfaces, and the exemption is pinned below.
5760
*/
5861

5962
import { describe, it, expect, beforeEach } from 'vitest';
@@ -177,9 +180,11 @@ describe('[#13239] the two `unique` surfaces disagree about bare `true`, and thi
177180
);
178181
});
179182

180-
it("only the explicit `'organization'` prepends the NULL-safe organization key part", async () => {
183+
it("only the explicit `'organization'` prepends the organization key part — plain, ADR-0131 D1", async () => {
184+
// `scopeColumns` names it for the refusal's wording; `nullSafeColumns` is
185+
// empty — the organization key part no longer folds NULLs (ADR-0131 D1).
181186
expect(uniqueConstraintsFromDeclaredIndexes(ledger('organization'))).toEqual([
182-
{ columns: ['organization_id', 'account_id', 'code'], nullSafeColumns: ['organization_id'] },
187+
{ columns: ['organization_id', 'account_id', 'code'], nullSafeColumns: [], scopeColumns: ['organization_id'] },
183188
]);
184189

185190
const driver = new InMemoryDriver();
@@ -232,16 +237,17 @@ describe('[#13239] the two `unique` surfaces disagree about bare `true`, and thi
232237
* ==================================================================== */
233238

234239
describe("[#13239] the arms are `normalizeDeclaredIndex`'s, reproduced without importing driver-sql", () => {
235-
it('a listed column that IS the tenant column is not prepended again — its own key part becomes NULL-safe', () => {
240+
it('a listed column that IS the tenant column is not prepended again — it stays a plain key part, named as the scope', () => {
236241
// The hand-written S6 spelling, opted in. Order is preserved: the author's
237-
// column stays where they put it.
242+
// column stays where they put it. Since ADR-0131 D1 its key part is plain,
243+
// like the prepended one.
238244
const schema = {
239245
name: 'ledger',
240246
fields: { id: {}, organization_id: {}, code: {} },
241247
indexes: [{ fields: ['code', 'organization_id'], unique: 'organization' }],
242248
};
243249
expect(uniqueConstraintsFromDeclaredIndexes(schema)).toEqual([
244-
{ columns: ['code', 'organization_id'], nullSafeColumns: ['organization_id'] },
250+
{ columns: ['code', 'organization_id'], nullSafeColumns: [], scopeColumns: ['organization_id'] },
245251
]);
246252
});
247253

@@ -276,7 +282,7 @@ describe("[#13239] the arms are `normalizeDeclaredIndex`'s, reproduced without i
276282
indexes: [{ fields: ['a'], unique: 'organization' }],
277283
};
278284
expect(uniqueConstraintsFromDeclaredIndexes(schema)).toEqual([
279-
{ columns: ['org', 'a'], nullSafeColumns: ['org'] },
285+
{ columns: ['org', 'a'], nullSafeColumns: [], scopeColumns: ['org'] },
280286
]);
281287
});
282288

@@ -337,7 +343,7 @@ describe("[#13239] the arms are `normalizeDeclaredIndex`'s, reproduced without i
337343
};
338344
expect(uniqueConstraintsFromDeclaredIndexes(schema)).toEqual([
339345
{ columns: ['a'], nullSafeColumns: [] },
340-
{ columns: ['organization_id', 'b', 'c'], nullSafeColumns: ['organization_id'] },
346+
{ columns: ['organization_id', 'b', 'c'], nullSafeColumns: [], scopeColumns: ['organization_id'] },
341347
]);
342348
});
343349
});
@@ -357,43 +363,46 @@ describe('[#13239] NULL handling matches the composite index SQL actually builds
357363
expect(await driver.count('ledger')).toBe(4);
358364
});
359365

360-
it('a NULL ORGANIZATION does NOT exempt — the D3 fold, reached without the `__global__` token', async () => {
361-
// SQL folds NULL organizations with COALESCE onto a reserved literal because
362-
// an index EXPRESSION needs a non-NULL one. A JS key holds `null` directly,
363-
// so the same bucket is reached with no token at all.
366+
it('a NULL ORGANIZATION exempts the row, like any NULL key part — the D3 fold is retired (ADR-0131 D1)', async () => {
367+
// The plain `(organization_id, …)` index SQL builds now is NULL-distinct in
368+
// its organization part too, so rows without an organization (which only a
369+
// pre-18 store can still hold) are not constrained among themselves.
364370
const driver = new InMemoryDriver();
365371
await driver.syncSchema('ledger', ledger('organization'));
366372
await driver.create('ledger', { id: '1', account_id: 'A1', code: 'X' });
367-
const err = await refusalOf(() => driver.create('ledger', { id: '2', account_id: 'A1', code: 'X' }));
373+
await driver.create('ledger', { id: '2', account_id: 'A1', code: 'X' });
374+
await driver.create('ledger', { id: '3', organization_id: null, account_id: 'A1', code: 'X' });
375+
// …while a row that DOES carry an organization is still constrained in it.
376+
await driver.create('ledger', { id: '4', organization_id: 'acme', account_id: 'A1', code: 'X' });
377+
const err = await refusalOf(() =>
378+
driver.create('ledger', { id: '5', organization_id: 'acme', account_id: 'A1', code: 'X' }),
379+
);
368380
expectUniqueViolationEnvelope(err, 'account_id', 'code', 'organization_id');
369-
// …and a row that DOES carry an organization is untouched by that bucket.
370-
await driver.create('ledger', { id: '3', organization_id: 'acme', account_id: 'A1', code: 'X' });
371-
expect(await driver.count('ledger')).toBe(2);
381+
expect(await driver.count('ledger')).toBe(4);
372382
});
373383

374-
it('an index whose ONLY key part is the NULL-safe organization is "one row per organization"', async () => {
384+
it('an index whose ONLY key part is the organization is "one row per organization" — NULL-org rows exempt', async () => {
375385
// `normalizeDeclaredIndex` has no "a unique ON the tenant column stays
376386
// single-column" guard — that guard is the FIELD surface's. Here the listed
377-
// organization column simply becomes the NULL-safe key part, so NULL-org
378-
// rows share one bucket and are unique among themselves.
387+
// organization column is the whole key, and plain since ADR-0131 D1: one
388+
// row per organization, while rows without one are not constrained.
379389
const schema = {
380390
name: 'settings',
381391
fields: { id: {}, organization_id: {} },
382392
indexes: [{ fields: ['organization_id'], unique: 'organization' }],
383393
};
384394
expect(uniqueConstraintsFromDeclaredIndexes(schema)).toEqual([
385-
{ columns: ['organization_id'], nullSafeColumns: ['organization_id'] },
395+
{ columns: ['organization_id'], nullSafeColumns: [], scopeColumns: ['organization_id'] },
386396
]);
387397

388398
const driver = new InMemoryDriver();
389399
await driver.syncSchema('settings', schema);
390400
await driver.create('settings', { id: '1', organization_id: 'acme' });
391-
await driver.create('settings', { id: '2' }); // NULL organization: its own bucket
401+
await driver.create('settings', { id: '2' }); // NULL organization: exempt
392402
const dupOrg = await refusalOf(() => driver.create('settings', { id: '3', organization_id: 'acme' }));
393403
expectUniqueViolationEnvelope(dupOrg, 'organization_id');
394-
const dupNull = await refusalOf(() => driver.create('settings', { id: '4' }));
395-
expectUniqueViolationEnvelope(dupNull, 'organization_id');
396-
expect(await driver.count('settings')).toBe(2);
404+
await driver.create('settings', { id: '4' }); // a second NULL-org row lands too
405+
expect(await driver.count('settings')).toBe(3);
397406
});
398407
});
399408

@@ -411,7 +420,7 @@ describe('[#13239] the refusal names no single column, because a composite has n
411420
);
412421
// Matches what SQLite answers for the same index — measured: the plain
413422
// composite prints `UNIQUE constraint failed: t.account_id, t.code` (two
414-
// targets -> undefined) and the NULL-safe form prints
423+
// targets -> undefined) and the 18.0 NULL-safe form printed
415424
// `UNIQUE constraint failed: index '…'` (an index name -> undefined).
416425
expect(isUniqueViolationError(err)).toBe(true);
417426
expect(uniqueViolationColumn(err)).toBeUndefined();

‎packages/drivers/driver-memory/src/memory-unique-constraint.test.ts‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@
2828
* platform-wide, bare `true` and `'organization'` are per-organization (bare
2929
* `true` is the POSITIONAL spelling of `'organization'` at FIELD level, not of
3030
* `'global'` — the #4986 trap), and both degrade to a single-column constraint
31-
* when the object has no tenant column. This package cannot import `driver-sql`
31+
* when the object has no tenant column. Since ADR-0131 D1 the organization key
32+
* part is the PLAIN column there, so a row with no organization is exempt like a
33+
* NULL in any key part. This package cannot import `driver-sql`
3234
* (dependency direction), so the arms are reproduced and pinned here against
3335
* that rule rather than shared.
3436
*/
@@ -285,20 +287,36 @@ describe("[#13197] scoping matches driver-sql's ADR-0120 D1/D3 rule", () => {
285287
expect(err.message).not.toContain('organization_id');
286288
});
287289

288-
it('the NULL-organization rows form ONE bucket — the D3 fold, without needing the `__global__` token', async () => {
289-
// SQL UNIQUE is NULL-distinct, so a raw `(organization_id, email)` composite
290-
// enforced NOTHING on NULL-org rows — every row on a single-organization
291-
// stack (#5030). ADR-0120 D3 folds them with COALESCE onto a reserved
292-
// literal because an index EXPRESSION needs one; a JS key holds `null`
293-
// directly, so the same bucket is reached with no token at all.
290+
it('a row with NO organization is exempt — the plain organization key part (ADR-0131 D1), the D3 bucket retired', async () => {
291+
// ADR-0120 D3 once folded NULL-org rows onto one bucket (COALESCE onto
292+
// `__global__` in SQL). The tenant column is NOT NULL since ADR-0131 D1, so
293+
// driver-sql keys `(organization_id, email)` plain and SQL's NULL-distinct
294+
// UNIQUE exempts such rows (which only a pre-18 store can still hold) —
295+
// this driver answers the same.
294296
const driver = new InMemoryDriver();
295297
await driver.syncSchema('contact', withOrg(true));
296298
await driver.create('contact', { id: '1', email: 'a@b.com' });
299+
await driver.create('contact', { id: '2', email: 'a@b.com' });
300+
await driver.create('contact', { id: '3', organization_id: null, email: 'a@b.com' });
301+
// …while a row that DOES carry an organization is still constrained in it.
302+
await driver.create('contact', { id: '4', organization_id: 'acme', email: 'a@b.com' });
303+
const err = await refusalOf(() =>
304+
driver.create('contact', { id: '5', organization_id: 'acme', email: 'a@b.com' }),
305+
);
306+
expectUniqueViolationEnvelope(err, 'email');
307+
expect(await driver.count('contact')).toBe(4);
308+
});
309+
310+
it("a platform-wide constraint's constant scope still constrains rows with no organization", async () => {
311+
// The one NULL-safe part left: `scopeField: null` is a constant, not a column,
312+
// so `'global'` keeps refusing a second NULL-org row (ADR-0131 D1 changes
313+
// only the organization key part).
314+
const driver = new InMemoryDriver();
315+
await driver.syncSchema('contact', withOrg('global'));
316+
await driver.create('contact', { id: '1', email: 'a@b.com' });
297317
const err = await refusalOf(() => driver.create('contact', { id: '2', email: 'a@b.com' }));
298318
expectUniqueViolationEnvelope(err, 'email');
299-
// …and a row that DOES carry an organization is untouched by that bucket.
300-
await driver.create('contact', { id: '3', organization_id: 'acme', email: 'a@b.com' });
301-
expect(await driver.count('contact')).toBe(2);
319+
expect(await driver.count('contact')).toBe(1);
302320
});
303321

304322
it('with NO tenant column both per-organization spellings degrade to a single-column constraint', () => {

‎packages/drivers/driver-turso/src/turso-local-remote-declared-index-parity.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@
2323
* per-face suite cannot fail on the DIFFERENCE between faces, and the
2424
* difference is the defect. So each pin here drives one object set through
2525
* BOTH faces and compares what physically landed — index names, uniqueness,
26-
* origin and key parts (NULL-safe organization expressions included) — rather
27-
* than asserting either face against a literal. Each parity pin is ANCHORED
26+
* origin and key parts (the organization key part included — PLAIN since
27+
* ADR-0131 D1, so a face that still emitted a COALESCE expression would show
28+
* here) — rather than asserting either face against a literal. Each parity pin is ANCHORED
2829
* by names computed through the shared `buildIndexName`, because two faces
2930
* that both lost every index would agree perfectly.
3031
*
@@ -39,7 +40,8 @@
3940
* `indexes` verbatim — because this package does not (and should not) depend
4041
* on `service-messaging` or `platform-objects`. `os17609_scoped` covers what
4142
* those two do not: a tenant column, a field-level `unique` scoped by it, a
42-
* declared `unique: 'organization'` (NULL-safe key part), an explicit
43+
* declared `unique: 'organization'` (plain organization key part, ADR-0131
44+
* D1), an explicit
4345
* `unique: 'global'`, two author-named indexes — one of them no SQL
4446
* identifier at all (a space and a double quote), which both faces must
4547
* accept — and an index over a virtual `formula` field that neither face may
@@ -374,10 +376,15 @@ describe('[#17609] declared object-level indexes land identically on both TursoD
374376
expect(localShapes.map((i) => i.name), name).toEqual(EXPECTED_NAMES[name]);
375377
}
376378

377-
// The tenant key part is the NULL-safe expression on both faces, not the bare column.
379+
// ADR-0131 D1: the tenant key part is the PLAIN column on both faces — no
380+
// COALESCE expression — for the declared `unique: 'organization'` and the
381+
// field-level `unique` alike (the remote face's agreement is pinned above).
378382
const scoped = await indexShapes(remote.query, SCOPED.name);
379383
expect(scoped.find((i) => i.name === buildIndexName(SCOPED.name, ['organization_id', 'slug'], true))).toEqual(
380-
expect.objectContaining({ unique: true, keys: ["COALESCE(organization_id, '__global__')", 'slug'] }),
384+
expect.objectContaining({ unique: true, keys: ['organization_id', 'slug'] }),
385+
);
386+
expect(scoped.find((i) => i.name === buildIndexName(SCOPED.name, ['organization_id', 'code'], true))).toEqual(
387+
expect.objectContaining({ unique: true, keys: ['organization_id', 'code'] }),
381388
);
382389
});
383390

0 commit comments

Comments
 (0)