Skip to content

Commit e36e855

Browse files
committed
wip(dogfood): fixtures name their organization, hold a Default Organization, or model a pre-18 store
Claude-Session: https://claude.ai/code/session_018EszgtA3V2KXBX5tf59Hi4 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e5e11c commit e36e855

12 files changed

Lines changed: 148 additions & 1 deletion

‎packages/qa/dogfood/test/attachments-permission-matrix.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,11 +569,15 @@ describe('attachments permission matrix (#2755)', () => {
569569
// Hook-bypass re-reference: a DIRECT DRIVER insert (no engine hooks
570570
// fire, so afterInsert cannot un-tombstone) + a backdated tombstone.
571571
const driver = ql.getDriverForObject('sys_attachment');
572+
// The row carries its parent's organization, as the engine would stamp
573+
// it: a fresh tenant column is NOT NULL (ADR-0131 D1).
574+
const parent = await ql.findOne('att_case', { where: { id: caseAId }, context: SYS });
572575
await driver.create('sys_attachment', {
573576
id: `bypass-${fileId}`,
574577
parent_object: 'att_case',
575578
parent_id: caseAId,
576579
file_id: fileId,
580+
organization_id: parent.organization_id,
577581
created_at: new Date(),
578582
});
579583
await ql.update(
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Give a lean test engine what every real `single` install has: an
5+
* organization object holding its Default Organization.
6+
*
7+
* ADR-0131 D1: a table the SQL driver creates carries its tenant column NOT
8+
* NULL. The engine stamps an organization-less system write with the derived
9+
* organization under `single` (D9) — but only where the composition registers
10+
* the organization object; a bare `ObjectQL` + `SqlDriver` registers none, so
11+
* the write reaches the database with no organization and is refused there.
12+
* A suite whose subject is not tenancy (claims, acks, idle cost, at-rest
13+
* shapes) calls this once its own objects are registered, so its system
14+
* writes land the way they do on a real install.
15+
*
16+
* The object mirrors the platform's: managed by better-auth, so it carries no
17+
* tenant column of its own.
18+
*/
19+
export const DEFAULT_ORGANIZATION_ID = 'org_default';
20+
21+
export async function installDefaultOrganization(engine: {
22+
registry: { registerObject(def: unknown, owner: string): unknown };
23+
getSchema(object: string): unknown;
24+
syncSchemas(): Promise<unknown>;
25+
getDriverForObject(object: string):
26+
| {
27+
create(object: string, data: Record<string, unknown>): Promise<unknown>;
28+
findOne(object: string, query: unknown): Promise<unknown>;
29+
}
30+
| undefined;
31+
}): Promise<void> {
32+
// Idempotent: a suite that syncs one engine more than once may call it each time.
33+
if (!engine.getSchema('sys_organization')) {
34+
engine.registry.registerObject(
35+
{ name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } },
36+
'@objectstack/dogfood',
37+
);
38+
}
39+
await engine.syncSchemas();
40+
// Seeded through the driver: the organization is data at rest, not a write
41+
// the suite under test should observe (an audit or activity mirror would).
42+
const driver = engine.getDriverForObject('sys_organization')!;
43+
if (await driver.findOne('sys_organization', { where: { id: DEFAULT_ORGANIZATION_ID } })) return;
44+
await driver.create('sys_organization', { id: DEFAULT_ORGANIZATION_ID, name: 'Default' });
45+
}

‎packages/qa/dogfood/test/email-template-boot-sweep.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { describe, it, expect, afterEach } from 'vitest';
3232
import { ObjectQL } from '@objectstack/objectql';
3333
import { SqlDriver } from '@objectstack/driver-sql';
3434
import { EmailServicePlugin } from '@objectstack/plugin-email';
35+
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
3536

3637
const SYS = { isSystem: true, positions: [], permissions: [] };
3738
const TABLE = 'sys_email_template';
@@ -100,6 +101,10 @@ const onTable = (statements: string[]) => statements.filter((s) => s.includes(`\
100101
* every row carrying stale wording a send must never render.
101102
*/
102103
async function seedSharedSlot(engine: ObjectQL): Promise<void> {
104+
// `etpl_z` belongs to no organization, which only a store built before 18.x
105+
// can hold (ADR-0131 D1 makes a fresh tenant column NOT NULL): the table is
106+
// that store's.
107+
await relaxTenantColumns(engine as any, [TABLE]);
103108
const rows: Array<[string, string | null, string]> = [
104109
['etpl_m', 'org_b', 'en-US'],
105110
['etpl_z', null, 'en-US'],

‎packages/qa/dogfood/test/engine-where-shape-refusal.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2323
import { ObjectQL } from '@objectstack/objectql';
2424
import { SqlDriver } from '@objectstack/driver-sql';
25+
import { installDefaultOrganization } from './default-organization.testkit.js';
2526

2627
const SYS = { context: { isSystem: true, userId: 'usr_system' } };
2728

@@ -67,6 +68,9 @@ beforeEach(async () => {
6768
objects: [PROBE_ORDER],
6869
} as never);
6970
await engine.syncSchemas();
71+
// A real `single` install's Default Organization: the system writes below
72+
// derive it (ADR-0131 D9), as a fresh NOT NULL tenant column requires (D1).
73+
await installDefaultOrganization(engine);
7074
for (const [id, name, amount] of [['o1', 'a', 50], ['o2', 'b', 150], ['o3', 'c', 50], ['o4', 'd', 150]] as const) {
7175
await engine.insert('probe_order', { id, name, amount }, SYS as never);
7276
}

‎packages/qa/dogfood/test/parent-derived-write-refusal-not-visible.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import { buildAttSecret, buildAttReadonly, attFixtureBaselineSet, attachmentMana
5959
import { buildCmtPrivate, buildCmtReadonly, commentManagerSet } from './fixtures/comments-fixture.js';
6060
import { armedWhen, assertArmed, leaveOrganization, principalArmed, resolveAuthzFor } from './armed.js';
6161
import { catalogPermissionSet } from './catalog-permission-set.js';
62+
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
6263

6364
const SYS = { isSystem: true } as const;
6465

@@ -139,6 +140,9 @@ async function boot(inside: boolean, email: string): Promise<Booted> {
139140
// organization-less system insert with the Default Organization (ADR-0131 D9),
140141
// so the global row is landed beneath the engine, as the residue an older
141142
// release left. The readers still apply it until C8's NULL-reader stages.
143+
// That residue lives only on a store built before 18.x, whose tenant column is
144+
// nullable (ADR-0131 D1 makes a fresh one NOT NULL): the table is that store's.
145+
await relaxTenantColumns(ql as any, ['sys_user_permission_set']);
142146
await ql.getDriver('sys_user_permission_set').create('sys_user_permission_set', {
143147
id: `ups_${userId}_${set.name}`, user_id: userId, permission_set: set.name, organization_id: null,
144148
});
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Return engine-synced tables to the shape a store built BEFORE 18.x has: the
5+
* tenant column nullable.
6+
*
7+
* ADR-0131 D1: since 18.x the SQL driver creates a table's tenant column NOT
8+
* NULL. A store an earlier release built still holds the nullable column and
9+
* its organization-less rows — the holdings, grants and seeds this package's
10+
* NULL readers still answer for until the organization-ownership ceremony has
11+
* attributed them. A suite whose subject is those rows calls this after
12+
* `syncSchemas()` and before seeding them. Done through each table's driver
13+
* and its own drift apply door (`relax_not_null`), never a hand `ALTER`.
14+
*/
15+
export async function relaxTenantColumns(
16+
engine: { getDriverForObject(object: string): unknown },
17+
tables: readonly string[],
18+
column = 'organization_id',
19+
): Promise<void> {
20+
for (const table of tables) {
21+
const driver = engine.getDriverForObject(table) as {
22+
applyMigrationEntries(entries: never[]): Promise<{ applied: unknown[] }>;
23+
};
24+
const op = { type: 'relax_not_null', table, column };
25+
const { applied } = await driver.applyMigrationEntries([
26+
{ kind: 'nullability_mismatch', remoteName: table, table, column, category: 'needs_confirm', op } as never,
27+
]);
28+
if (applied.length !== 1) throw new Error(`relaxTenantColumns: ${table}.${column} was not relaxed`);
29+
}
30+
}
31+
32+
/**
33+
* {@link relaxTenantColumns} over every object of an app that carries a tenant
34+
* column as the engine registered it — the shape a whole pre-18 store has.
35+
*/
36+
export async function relaxEveryTenantColumn(
37+
engine: { getDriverForObject(object: string): unknown; getSchema(object: string): unknown },
38+
objects: readonly { name: string }[],
39+
): Promise<void> {
40+
const tenant = objects
41+
.map((o) => o.name)
42+
.filter((name) => {
43+
const schema = engine.getSchema(name) as { fields?: Record<string, unknown>; tenancy?: { enabled?: boolean } } | undefined;
44+
return !!schema?.fields?.organization_id && schema.tenancy?.enabled !== false;
45+
});
46+
await relaxTenantColumns(engine, tenant);
47+
}
48+
49+
/** {@link relaxEveryTenantColumn} over every object the engine's registry holds. */
50+
export async function relaxEveryRegisteredTenantColumn(engine: {
51+
getDriverForObject(object: string): unknown;
52+
getSchema(object: string): unknown;
53+
registry: { getAllObjects(): readonly { name: string }[] };
54+
}): Promise<void> {
55+
await relaxEveryTenantColumn(engine, engine.registry.getAllObjects());
56+
}

‎packages/qa/dogfood/test/predicate-write-unreadable-not-matched.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import {
5858
import { buildCmtOpen, buildCmtPrivate, buildCmtReadonly, commentManagerSet } from './fixtures/comments-fixture.js';
5959
import { armedWhen, assertArmed, leaveOrganization, principalArmed, resolveAuthzFor } from './armed.js';
6060
import { catalogPermissionSet } from './catalog-permission-set.js';
61+
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
6162

6263
const SYS = { isSystem: true } as const;
6364

@@ -162,6 +163,9 @@ async function boot(inside: boolean, email: string): Promise<Booted> {
162163
// organization-less system insert with the Default Organization (ADR-0131 D9),
163164
// so the global row is landed beneath the engine, as the residue an older
164165
// release left. The readers still apply it until C8's NULL-reader stages.
166+
// That residue lives only on a store built before 18.x, whose tenant column is
167+
// nullable (ADR-0131 D1 makes a fresh one NOT NULL): the table is that store's.
168+
await relaxTenantColumns(ql as any, ['sys_user_permission_set']);
165169
await ql.getDriver('sys_user_permission_set').create('sys_user_permission_set', {
166170
id: `ups_${userId}_${set.name}`, user_id: userId, permission_set: set.name, organization_id: null,
167171
});

‎packages/qa/dogfood/test/sharing-rule-criteria-required.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
2626
import { type VerifyStack } from '@objectstack/verify';
2727
import { bootShowcase } from './showcase-boot.js';
28+
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
2829

2930
// Sharing-rule routes are anchored on the API base, not under `/data/:object`
3031
// (they administer rules tenant-wide) — `/api/v1/sharing/rules`.
@@ -137,6 +138,9 @@ describe('#3896 — a sharing rule POSTed without criteria is rejected, never ma
137138
const id = 'srule_3896_legacy';
138139
const driver = (ql as any).getDriverForObject('sys_sharing_rule');
139140
expect(driver, 'sys_sharing_rule driver must be resolvable').toBeTruthy();
141+
// That residue lives only on a store built before 18.x, whose tenant column is
142+
// nullable (ADR-0131 D1 makes a fresh one NOT NULL): the table is that store's.
143+
await relaxTenantColumns(ql as any, ['sys_sharing_rule']);
140144
await driver.create('sys_sharing_rule', {
141145
id,
142146
name: 'legacy_match_all_3896',

‎packages/qa/dogfood/test/sharing-rule-org-less-caller.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import { type VerifyStack } from '@objectstack/verify';
6565
import { bootShowcase } from './showcase-boot.js';
6666
import { leaveOrganization } from './armed.js';
6767
import { catalogPermissionSet } from './catalog-permission-set.js';
68+
import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js';
6869

6970
const RULES = '/sharing/rules';
7071
const SYS = { isSystem: true } as const;
@@ -167,6 +168,9 @@ describe('#8158 — a manage_sharing holder with NO active organization cannot r
167168
// NULL-reader stages.
168169
const globalGrant = (row: Record<string, unknown>) =>
169170
ql.getDriver('sys_user_permission_set').create('sys_user_permission_set', { ...row, organization_id: null });
171+
// That residue lives only on a store built before 18.x, whose tenant column is
172+
// nullable (ADR-0131 D1 makes a fresh one NOT NULL): the table is that store's.
173+
await relaxTenantColumns(ql as any, ['sys_user_permission_set']);
170174
await globalGrant({ id: 'ups_8158_org_less', user_id: orgLessUserId, permission_set: 'sharing_admin_8158' });
171175
// The #8158 grant as filed — scoped to tenant A — for the control (which
172176
// has tenant A active) and for the org-scoped persona (which has none).

‎packages/qa/dogfood/test/storage-growth.dogfood.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ describe('objectstack verify LIFECYCLE (ADR-0057): declared policies bound growt
6565
let engine: EngineLike;
6666
let lifecycle: LifecycleLike;
6767
let driver: DriverLike;
68+
let organizationId: string;
6869

6970
// Platform storage convention: `created_at` is registry-injected as a
7071
// `datetime` field, stored as epoch-ms INTEGER on SQLite (a JS Date through
@@ -76,6 +77,11 @@ describe('objectstack verify LIFECYCLE (ADR-0057): declared policies bound growt
7677
beforeAll(async () => {
7778
stack = await bootShowcase();
7879
engine = stack.kernel.getService('objectql') as unknown as EngineLike;
80+
// The runaway writer's rows belong to the install's organization, as the
81+
// engine would stamp them: a fresh tenant column is NOT NULL (ADR-0131 D1).
82+
organizationId = String(
83+
((await (engine as any).find('sys_organization', { context: { isSystem: true } })) as Array<{ id: string }>)[0].id,
84+
);
7985
lifecycle = stack.kernel.getService('lifecycle') as unknown as LifecycleLike;
8086
expect(lifecycle?.sweep, 'the ObjectQLPlugin must register the ADR-0057 lifecycle service').toBeTruthy();
8187

@@ -148,12 +154,14 @@ describe('objectstack verify LIFECYCLE (ADR-0057): declared policies bound growt
148154
// any window (must never be touched).
149155
for (let i = 0; i < 40; i++) {
150156
await driver.create('growth_probe_event', {
157+
organization_id: organizationId,
151158
payload: `tick-${i}`,
152159
created_at: backdated(5 + i * 5), // 5d … 200d
153160
});
154161
}
155162
for (let i = 0; i < 5; i++) {
156163
await driver.create('growth_probe_record', {
164+
organization_id: organizationId,
157165
payload: `business-${i}`,
158166
created_at: backdated(400),
159167
});
@@ -215,7 +223,7 @@ describe('objectstack verify LIFECYCLE (ADR-0057): declared policies bound growt
215223
// Round-trip: write through the driver, read through the view, and a
216224
// sweep applies the 'rotation' policy without touching the rows inside
217225
// the window.
218-
await streamDriver.create('growth_probe_stream', { payload: 'tick' });
226+
await streamDriver.create('growth_probe_stream', { organization_id: organizationId, payload: 'tick' });
219227
expect(await streamDriver.count('growth_probe_stream', {})).toBe(1);
220228

221229
const report = await lifecycle.sweep();
@@ -227,6 +235,7 @@ describe('objectstack verify LIFECYCLE (ADR-0057): declared policies bound growt
227235
it('ARCHIVE SAFETY: an audit ledger with a declared archive is never hot-deleted unarchived', async () => {
228236
for (let i = 0; i < 3; i++) {
229237
await driver.create('growth_probe_ledger', {
238+
organization_id: organizationId,
230239
payload: `ledger-${i}`,
231240
created_at: backdated(365), // far past the 90d hot window
232241
});

0 commit comments

Comments
 (0)