diff --git a/.changeset/33207-seed-org-scoped-references.md b/.changeset/33207-seed-org-scoped-references.md new file mode 100644 index 00000000000..9e17eef52d7 --- /dev/null +++ b/.changeset/33207-seed-org-scoped-references.md @@ -0,0 +1,21 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol)!: a seed load for one organization resolves people through membership in that organization, says when a reference lookup was refused, and gives hooks on seeded rows the organization the rows are stamped with + +Clause-②: yes (narrowing) — narrowed: under a walled tenancy posture (`isolated` or `group`), every read and by-id write a seed write performs or triggers (a hook's `ctx.api` read, the engine's own reads on that row such as reference checks and roll-ups, and the loader's own update of an existing row and its pass-2 back-fill) is scoped to the organization the row is written as, where it reached every organization's rows. Widened: on a load for one organization (the per-organization replay, a reseed, an install into an organization), a reference to a person (`owner_id`, a `sys_user` lookup) resolves to a person who is a member of that organization, where it never resolved; a reference to `sys_organization` resolves to the load's own organization; a reference to an object no organization walls (no `organization_id` column and no tenant field at all, e.g. `tenancy: { enabled: false }`) resolves across organizations; and a hook on a seeded row now sees the organization the row is stamped with as `ctx.session.organizationId`, on those loads and on every load that stamps the install's sole organization (the boot under `single`, a publish, a hot reload). Nothing that resolved before stops resolving, and no load that succeeded is refused. +Metadata-protocol: none + + + +**BREAKING** for an app hook that reads through `ctx.api` on a seeded row under a walled tenancy posture and relied on seeing other organizations' rows. A seed load for organization A now writes as organization A: the hook, and every engine read the write triggers, reads what it reads when a person of organization A creates the row through the API. A row that supplies its own `organization_id` is written as that organization instead. The fix: a hook that genuinely needs rows of every organization says so with `ctx.api.sudo()` and filters them itself, as it must on the API path already. + +What changes, by load: + +- **A reference to a person on an organization's own load.** `sys_user` carries no organization (identity lives above it), so the loader's reference lookup no longer filters it by `organization_id`, which the database refused. It reads the people the natural key names, in id order and page by page, and keeps the first one holding a `sys_member` row in the load's organization. A person who exists but is not a member is never used: the reference stays empty, and only once every person the key names has been asked about does its error say the person is not a member of that organization. +- **Every other reference target** is judged from its registered schema: one with an `organization_id` column is looked up inside the load's organization, as before; `sys_organization` answers only for the load's own organization; an author's object that resolves no tenant field at all has no organization filter. An object walled by another tenant column (`tenancy.tenantField`) and a platform-managed table with no organization column keep the old lookup, and its refusal is now reported. +- **A refused lookup** (an unknown column, an unregistered object, a driver fault) is no longer read as "no match". The load logs it once per target, field and code, keeps going, and the reference's error names the refusal's code instead of saying no such row exists. The load's outcome is unchanged: the reference was unresolved before and stays unresolved. +- **The write context.** Every seed write of a load carries `tenantId` set to the organization the row is written as: the one it supplies itself, else the one the load stamps it with (the one the caller pinned, or the install's sole organization). The shared `SEED_WRITE_EXECUTION_CONTEXT` is unchanged. A load with no organization, pinned or derived, writes with exactly the context it used before. +- **A pass-2 back-fill that lands on no row** (a data engine answering `null` for the by-id update) is reported as a failed back-fill, never counted as resolved. +- **A load with no organization** (the single-tenant boot, a publish, a hot reload) resolves references across the whole database, as before. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 293e133d5f7..b31549d576d 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -461,6 +461,26 @@ const contactsSeed = defineSeed(Contact, { export const SeedData = [accountsSeed, contactsSeed]; ``` +### References on an organization's own load + +A load that seeds one organization (the per-organization replay, a reseed, a +package install into an organization) resolves a natural key **inside that +organization**, by what the target object carries: + +| Target | Resolves to | +|:---|:---| +| An object with an `organization_id` column (every business object) | a row of the load's organization only; another organization's row with the same key is never used | +| `sys_user` (people: `owner_id`, people lookups) | a person who is a **member** of the load's organization (a `sys_member` row there); a same-named person outside it is never used | +| `sys_organization` | the load's own organization only | +| An object no organization walls: no `organization_id` column and no tenant field (for example `tenancy: { enabled: false }`) | any row: global rows belong to every organization | +| An object walled by another tenant column (`tenancy.tenantField`) with no `organization_id` column | nothing on such a load: the lookup is refused and reported, never answered from another organization | + +A load with no organization (the single-tenant boot) resolves across the whole +database, as it always has. When the database refuses a lookup outright (for +example a column the target does not have), the load logs the refusal once, +with its code, and the reference's error says the lookup was refused instead +of claiming the row does not exist. + ### Multi-Value Lookups (`multiple: true`) A lookup declared `multiple: true` stores an **array** of related record ids, so its @@ -628,6 +648,12 @@ same way. A row someone already owns is never touched. passes `config.identity`). - `os.org.id` resolves to the current organization; during a per-tenant replay it is that tenant's id, falling back to the load's `organizationId`. +- Hooks run on seeded rows (seeds skip only flow automation), and a hook sees + the organization the row is stamped with as `ctx.session.organizationId`, + the same as for a row written through the API (a row that supplies its own + `organization_id` is written as that organization). Under a walled tenancy + posture its `ctx.api` reads, and every engine read the write triggers, are + scoped to that organization. A load with no organization gives hooks none. ### Failure is loud, not silent diff --git a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts index 6ca4b995d0d..dfc72bee430 100644 --- a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts @@ -193,6 +193,39 @@ describe('seed deferred back-fill failure is reported, not swallowed (framework# expect(result.errors.some((e: { field: string }) => e.field === 'head_id')).toBe(true); }); + /** + * #33206 — the data-engine contract lets `update` answer `null` for a by-id + * update that matched no row (the row is gone, or the organization the write + * carries cannot see it). The link was not written, so the back-fill is a + * failure like a thrown one, never counted as resolved. + */ + it('a pass-2 reference update that matched no row (null) is reported, not counted as resolved (#33206)', async () => { + const { engine, store } = createFaithfulEngine(); + const metadata = createMetadata(); + + const realUpdate = (engine.update as any).getMockImplementation(); + (engine.update as any).mockImplementation(async (obj: string, data: any, opts: any) => { + if (obj === 'audit_department') return null; + return realUpdate(obj, data, opts); + }); + + const logger = createLogger(); + const result = await new SeedLoaderService(engine, metadata, logger).load({ + seeds: SEEDS, + config: CONFIG, + }); + + expect(store.audit_department.find((r) => r.name === 'Engineering')!.head_id == null).toBe(true); + expect(result.success).toBe(false); + expect(result.errors.some((e: { field: string }) => e.field === 'head_id')).toBe(true); + const line = logger.error.mock.calls + .map((c: unknown[]) => String(c[0])) + .find((m: string) => m.includes('audit_department.head_id')); + expect(line).toContain('matched no row'); + const dept = result.results.find((r: { object: string }) => r.object === 'audit_department'); + expect(dept?.referencesResolved ?? 0).toBe(0); + }); + /** * #4729 — the LOG LEVEL has to agree with the count. * diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 38361a7603f..b36e4a1450d 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -29,11 +29,12 @@ import { RAW_FILE_VALUES_CONTEXT_KEY, } from '@objectstack/spec/data'; import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel'; +import { SystemObjectName } from '@objectstack/spec/system'; import { resolveSeedRecord } from '@objectstack/formula'; import { bulkWrite, withTransientRetry, defaultIsTransientError, type BulkWriteRowResult, runWithAdvisoryAggregation, type AdvisoryGroup, temporalComparandKind, temporalStorageForm, type TemporalComparandKind, isMissing, - blankAsNullColumns, blankStorageForm, type BlankAsNullReach, + blankAsNullColumns, blankStorageForm, type BlankAsNullReach, resolveTenantFieldName, } from '@objectstack/core'; // [#8442] The repo's ONE recogniser for "this throw is a record-validation // failure" — duck-typed on `code`/`name`, the same predicate `mapDataError` and @@ -504,6 +505,41 @@ function seedRowNeedsOrganization(definition: unknown): boolean { return resolveInjectedSystemColumns(definition).tenant; } +/** + * [#33207] Does the target's schema carry an `organization_id` column at all — + * declared, or injected by the system-column pass? Narrower than + * {@link seedRowNeedsOrganization} on purpose: an object that declares the + * column but disables tenancy still HAS it, so a reference probe may still + * filter on it, as it always did. Only a target with no such column is one + * the organization filter can never run against. + */ +function carriesOrganizationColumn(definition: unknown): boolean { + if (!definition || typeof definition !== 'object') return true; + const fields = (definition as { fields?: unknown }).fields; + if (fields && typeof fields === 'object' && Object.prototype.hasOwnProperty.call(fields, 'organization_id')) { + return true; + } + return resolveInjectedSystemColumns(definition).tenant; +} + +/** [#33207] A reference probe the engine refused: it never ran. */ +interface ProbeRefusal { + readonly object: string; + readonly field: string; + readonly code: string; +} + +/** + * [#33207] What the database probes answered for one reference value: the id + * that resolved it, or a miss — with the refusal that made the miss + * uninformative, and the organization a same-named person matched outside of. + */ +interface DatabaseProbeOutcome { + readonly id: string | null; + readonly refusal?: ProbeRefusal; + readonly nonMemberOf?: string; +} + /** * [#22301] Put every `Date` a seed row resolved to into the STORED form of its * temporal field, before the row reaches the engine. @@ -740,6 +776,14 @@ export class SeedLoaderService implements ISeedLoaderService { * the very column this answer is about. */ private declaresNameColumnCache = new Map(); + /** + * [#33207] Per-{@link load} memo of how an organization-scoped load probes a + * reference target ({@link probeScopeOf}). Cleared per load for the reason + * {@link declaresNameColumnCache} is. + */ + private probeScopeCache = new Map(); + /** [#33207] The refused probes this {@link load} has already said, one line each. */ + private refusedProbes = new Set(); /** * [#11339] Declared pointer pairs per seeded object — every `text` field * whose definition carries `referenceVia` (ADR-0052 §5 ActivityPointer: @@ -1028,6 +1072,10 @@ export class SeedLoaderService implements ISeedLoaderService { // [#9071] Same per-load lifetime, same reason: a publish between two loads // can add (or drop) the `name` column this memo answers about. this.declaresNameColumnCache.clear(); + // [#33207] Same per-load lifetime: a target's columns and the refusals said. + this.probeScopeCache.clear(); + this.refusedProbes.clear(); + this.rowWriteOptions.clear(); // [#21665] One replay's ids belong to one organization: a reused service // instance must never re-point the next load's references with them. this.replayIdByAuthoredId.clear(); @@ -1055,6 +1103,16 @@ export class SeedLoaderService implements ISeedLoaderService { if (reading.kind === 'sole') this.fallbackOrgId = reading.organizationId; else if (reading.kind === 'unowned') this.unownedOrganizationCount = reading.organizationCount; } + // [#33206] Every write of this load carries the organization its rows are + // stamped with — the pinned one, or the install's sole organization under + // `single` — as `tenantId`, the key a hook's `session.organizationId` and + // its `ctx.api` scope are built from. Composed here, at the call site: the + // shared posture is not changed. No organization ⇒ today's bag, untouched. + const writeOrganization = config.organizationId ?? this.fallbackOrgId; + this.writeOrganization = writeOrganization; + this.seedOptions = writeOrganization + ? { context: { ...SEED_WRITE_EXECUTION_CONTEXT, tenantId: writeOrganization } } + : SeedLoaderService.SEED_OPTIONS; // 1. Filter datasets by the scope axes (environment AND locale) const datasets = this.filterDatasets(request.seeds, config); @@ -1442,7 +1500,12 @@ export class SeedLoaderService implements ISeedLoaderService { // per record, with transient-error retry and per-row degradation on a // logical/validation failure. See framework#2678. const pendingInserts: Array<{ recordIndex: number; externalIdValue: string; record: Record }> = []; - const opts = SeedLoaderService.SEED_OPTIONS as any; + // [#33206] The options the buffered rows are written with. A batch holds + // rows of ONE write organization: a row whose own organization differs + // flushes the batch before it joins (see `writeOptionsFor`). + let batchOpts: any = this.seedOptions; + // [#33206] The organization each row was written as, for its pass-2 back-fill. + const rowOrganizationByRecordIndex = new Map(); // [commit 9a884c6e4] Internal ids captured at write time, keyed by record index. // Every write site below records the id it learned here — unconditionally, // unlike the `insertedRecords` registrations, which need a non-empty @@ -1501,6 +1564,7 @@ export class SeedLoaderService implements ISeedLoaderService { const flushPendingInserts = async (): Promise => { if (pendingInserts.length === 0) return; const batch = pendingInserts.splice(0, pendingInserts.length); + const opts = batchOpts; const writeResults: BulkWriteRowResult[] = await bulkWrite( batch.map(b => b.record), { @@ -1802,11 +1866,11 @@ export class SeedLoaderService implements ISeedLoaderService { // for it, miss, and DROP the column: the row lands org-less and is then // invisible to every member behind the tenant wall. // - // The probe cannot rescue it either. `resolveFromDatabase` falls back to - // an `id` probe, but under per-tenant replay it AND-scopes every probe - // with `organization_id = ` — and `sys_organization`, being - // the tenant table itself, carries no such column, so that probe matches - // nothing by construction. + // Skipping the pass is still the rule, not a fallback onto the probe: + // the stamp is an id this loader wrote, never a natural key an author + // spelled, so it is not a reference for the pass to judge at all. (Under + // per-tenant replay the probe answers `sys_organization` only for the + // load's own organization, #33207 — `probeScopeOf`.) // // Only better-auth-shaped ids (`org_msbubm8g3j35rgx0`) actually hit this: // `looksLikeInternalId` recognises UUID/ObjectId and short-circuits those. @@ -2352,6 +2416,7 @@ export class SeedLoaderService implements ISeedLoaderService { // Insert/upsert the record if (!config.dryRun) { + rowOrganizationByRecordIndex.set(i, record['organization_id']); // [#33206] if (hasSelfRef) { // Self-referencing dataset: keep the historical sequential // per-record write so a later record can resolve its self-ref @@ -2425,7 +2490,8 @@ export class SeedLoaderService implements ISeedLoaderService { insertedRecords.get(objectName)!.set(externalIdValue, decision.id); } try { - await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.update(objectName, { ...record, id: decision.id }, opts))); + const rowOpts = this.writeOptionsFor(record['organization_id']) as any; // [#33206] + await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.update(objectName, { ...record, id: decision.id }, rowOpts))); written.updated++; await settleSeedFiles(i, decision.id); // [#25779] } catch (err: any) { @@ -2446,6 +2512,10 @@ export class SeedLoaderService implements ISeedLoaderService { } } else { // Insert: buffer for the batched flush rather than writing now. + // [#33206] A row written as another organization starts its own batch. + const rowOpts = this.writeOptionsFor(record['organization_id']); + if (pendingInserts.length > 0 && rowOpts !== batchOpts) await flushPendingInserts(); + batchOpts = rowOpts; pendingInserts.push({ recordIndex: i, externalIdValue, record }); if (pendingInserts.length >= insertBatchSize) { await flushPendingInserts(); @@ -2477,6 +2547,7 @@ export class SeedLoaderService implements ISeedLoaderService { const entry = deferredUpdates[d]; const internalId = internalIdByRecordIndex.get(entry.recordIndex); if (internalId) entry.internalId = internalId; + entry.rowOrganization = rowOrganizationByRecordIndex.get(entry.recordIndex); // [#33206] } // [#31021] Record the keys of the rows this dataset landed on — inserted, @@ -2655,7 +2726,7 @@ export class SeedLoaderService implements ISeedLoaderService { | { status: 'resolved'; value: string } | { status: 'kept'; value: unknown } | { status: 'invalid'; hint: string } - | { status: 'unresolved' } + | { status: 'unresolved'; miss?: DatabaseProbeOutcome } | { status: 'withdrawn' } > { if (typeof value === 'object') { @@ -2694,12 +2765,12 @@ export class SeedLoaderService implements ISeedLoaderService { const fromDatabase = await this.resolveFromDatabase( ref.targetObject, ref.targetField, value, config.organizationId, ); - if (fromDatabase) return { status: 'resolved', value: fromDatabase }; + if (fromDatabase.id) return { status: 'resolved', value: fromDatabase.id }; // [#31021] No row answers, and the record says one landed here under this // key: a person removed it. Asked only once every probe has missed, so the // record can never stand in for a row that is there. if (await this.isWithdrawnSeedTarget(ref.targetObject, ref.targetField, value)) return { status: 'withdrawn' }; - return { status: 'unresolved' }; + return { status: 'unresolved', miss: fromDatabase }; } private async resolveFromDatabase( @@ -2707,7 +2778,7 @@ export class SeedLoaderService implements ISeedLoaderService { targetField: string, value: unknown, organizationId?: string, - ): Promise { + ): Promise { // Probe order: the target dataset's declared externalId (threaded in as // `targetField` via buildReferenceMap), then the historical 'name' // default, then the internal id. Each is exact-match, so extra probes @@ -2721,15 +2792,10 @@ export class SeedLoaderService implements ISeedLoaderService { // the filter (`INVALID_FILTER`) rather than answering "no rows" — and it // is right to: a predicate naming a column the object does not have never // ran, so "no match" would be a lie (ADR-0110 D3 — a miss and a fault are - // different facts). The refusal is caught below and the chain moves on, so - // the probe costs nothing but the ERROR line it provokes — one per - // reference value, per pass, hundreds per seeded boot and per per-org - // replay, each reading exactly like a real failure. + // different facts). // - // The remedy therefore has to be on THIS side: stop asking. Softening, - // catching-with-a-quieter-log or downgrading the driver's answer would - // keep provoking a fault and then hide it, which is strictly worse than - // the noise. + // The remedy therefore has to be on THIS side: stop asking. Softening the + // driver's answer would keep provoking a fault and then hide it. // // Dropping the leg cannot change WHICH probe answers: on an object with no // `name` column this probe could only ever throw, never match. When the @@ -2740,14 +2806,34 @@ export class SeedLoaderService implements ISeedLoaderService { probeFields.splice(probeFields.indexOf(DEFAULT_EXTERNAL_ID_FIELD), 1); } + // [#33207] How an organization-scoped load may look into this target. With + // no organization on the load (the single-tenant boot, a publish, a hot + // reload) every probe is unscoped, exactly as before. + const scope = organizationId ? await this.probeScopeOf(targetObject) : 'unscoped'; + let refusal: ProbeRefusal | undefined; + let nonMemberMatched = false; + for (const probeField of probeFields) { try { + if (scope === 'members') { + const outcome = await this.probeOrganizationMember(probeField, value, organizationId!); + if (outcome.id) return { id: outcome.id }; + nonMemberMatched ||= outcome.nonMemberMatched; + refusal ??= outcome.refusal; + continue; + } const where: Record = { [probeField]: value }; - // Per-tenant replay: when scoping is requested, only consider - // rows that belong to the target tenant so cross-tenant rows - // never get borrowed as a "resolved" reference (would silently - // create a cross-org FK). - if (organizationId) where.organization_id = organizationId; + // A tenant-carrying target (or one the registry cannot describe) is + // AND-scoped to the load's organization, so a row of another + // organization is never borrowed as the reference (that would be a + // cross-organization link). The organization table itself answers only + // for the load's own organization. A global target (its author gave it + // no organization column) has no tenant to borrow from. + if (scope === 'organization') where.organization_id = organizationId; + else if (scope === 'own-organization') { + if (probeField === 'id' && value !== organizationId) continue; + where.id = organizationId; + } const records = await this.engine.find(targetObject, { where, fields: ['id'], @@ -2759,14 +2845,138 @@ export class SeedLoaderService implements ISeedLoaderService { // UUID/ObjectId so `looksLikeInternalId` did not short-circuit); an id // either exists or it does not, so there is no false-match risk. if (records && records.length > 0) { - return String(records[0].id || records[0]._id); + return { id: String(records[0].id || records[0]._id) }; } - } catch { - // Target object (or this probe's column) may not exist — try the next - // probe rather than aborting resolution outright. + } catch (err) { + // [#33207] A refused probe never ran, so it is not "no match". The + // chain still moves on (a later leg may answer), the load is never + // refused for it, and the refusal is carried to the reference's own + // verdict and said once per target, field and code. + refusal ??= this.reportRefusedProbe(scope === 'members' ? SystemObjectName.USER : targetObject, probeField, err); + } + } + return { id: null, ...(refusal ? { refusal } : {}), ...(nonMemberMatched ? { nonMemberOf: organizationId } : {}) }; + } + + /** + * [#33207] Resolve a person for an organization-scoped load: `sys_user` + * carries no organization (identity lives above the organization), so the + * candidates the field names are kept only when they hold a `sys_member` row + * in the load's organization. ⛔ A person who is not a member is never + * resolved, however exactly the name matches: they could not even read the + * row they would be made to own. The member with the lowest id wins: the + * candidates are read in id order, so the answer does not depend on the + * driver's row order. + * + * A name is not unique above the organization (every organization may sign + * its people up under the same seeded names), so the candidates are read + * page by page until a member is found or none is left: "not a member" is + * said only after every person the key names has been asked about, never + * on a truncated read. A refused membership read is reported as a refusal + * on `sys_member`, the table that refused it. + */ + private async probeOrganizationMember( + probeField: string, + value: unknown, + organizationId: string, + ): Promise<{ id: string | null; nonMemberMatched: boolean; refusal?: ProbeRefusal }> { + const page = SeedLoaderService.MEMBER_PROBE_PAGE; + let nonMemberMatched = false; + for (let offset = 0; ; offset += page) { + const userProbe: EngineQueryOptions = { + where: { [probeField]: value }, + fields: ['id'], + orderBy: [{ field: 'id', order: 'asc' }], + limit: page, + offset, + context: { isSystem: true }, + }; + const users = (await this.engine.find(SystemObjectName.USER, userProbe)) as Array> | undefined; + const candidates = (users ?? []).map((u) => String(u.id ?? u._id)).filter((id) => id !== 'undefined'); + if (candidates.length === 0) return { id: null, nonMemberMatched }; + const memberProbe: EngineQueryOptions = { + where: { user_id: candidates.length === 1 ? candidates[0] : { $in: candidates }, organization_id: organizationId }, + fields: ['user_id'], + limit: candidates.length, + context: { isSystem: true }, + }; + let members: Array> | undefined; + try { + members = (await this.engine.find(SystemObjectName.MEMBER, memberProbe)) as Array> | undefined; + } catch (err) { + return { id: null, nonMemberMatched: false, refusal: this.reportRefusedProbe(SystemObjectName.MEMBER, 'user_id', err) }; } + const memberIds = new Set((members ?? []).map((m) => String(m.user_id))); + const member = candidates.find((id) => memberIds.has(id)); + if (member) return { id: member, nonMemberMatched: false }; + nonMemberMatched = true; + if ((users ?? []).length < page) return { id: null, nonMemberMatched }; + } + } + + /** + * [#33207] How an organization-scoped load probes `targetObject`, judged once + * per load from the same definition resolver the stamp reads: + * + * - `organization` — the target carries an `organization_id` column (declared, + * or injected by the system-column pass), or the registry cannot describe + * it: probe within the load's organization, as always. + * - `members` — `sys_user`, which carries no organization: a person resolves + * only through membership in the load's organization. + * - `own-organization` — `sys_organization`, the tenant table itself: the load + * may name its own organization and no other. + * - `global` — an author's object (no `managedBy`) with no organization + * column that resolves no tenant field at all (`resolveTenantFieldName`, + * the same reading the wall scopes by; e.g. `tenancy: { enabled: false }`): + * no organization walls its rows, so the probe is unscoped. + * - any other target with no organization column keeps the `organization` + * probe, and its refusal is reported, not swallowed: a platform-managed + * table is not a seed target, and an object that resolves another tenant + * column (`tenancy.tenantField`) is walled per organization, so an + * unscoped probe would borrow another organization's row. A scope rule + * for either is not this loader's to invent. + */ + private async probeScopeOf(targetObject: string): Promise<'organization' | 'members' | 'own-organization' | 'global'> { + const memoised = this.probeScopeCache.get(targetObject); + if (memoised !== undefined) return memoised; + let definition: unknown; + try { + definition = await this.resolveObjectDefinition(targetObject); + } catch { + // The registry could not answer: an unknown is not a tenant-less verdict, + // so the probe keeps today's organization filter. + } + let scope: 'organization' | 'members' | 'own-organization' | 'global' = 'organization'; + if (definition && typeof definition === 'object' && !carriesOrganizationColumn(definition)) { + if (targetObject === SystemObjectName.USER) scope = 'members'; + else if (targetObject === SystemObjectName.ORGANIZATION) scope = 'own-organization'; + else if (!(definition as { managedBy?: unknown }).managedBy && resolveTenantFieldName(definition) === null) scope = 'global'; + } + this.probeScopeCache.set(targetObject, scope); + return scope; + } + + /** + * [#33207] Say a refused reference probe once per load, per target, field and + * code, and hand back what the reference's own verdict carries. A refusal is + * a probe that never ran (an unknown column, an unregistered object, a driver + * fault), so the miss it leaves behind is not evidence that no row exists. + */ + private reportRefusedProbe(targetObject: string, probeField: string, err: unknown): ProbeRefusal { + const e = err as { code?: unknown; name?: unknown; message?: unknown } | undefined; + const code = typeof e?.code === 'string' && e.code ? e.code : typeof e?.name === 'string' && e.name ? e.name : 'UNKNOWN'; + const key = JSON.stringify([targetObject, probeField, code]); + if (!this.refusedProbes.has(key)) { + this.refusedProbes.add(key); + const firstSentence = typeof e?.message === 'string' ? e.message.split(/(?<=\.)\s/)[0] : ''; + this.logger.warn( + `[SeedLoader] A reference probe on ${targetObject}.${probeField} was refused (${code}), so a reference ` + + `into ${targetObject} by ${probeField} cannot resolve through it on this load: the probe never ran, ` + + `which is not the same as no row matching.${firstSentence ? ` ${firstSentence}` : ''}`, + { object: targetObject, field: probeField, code }, + ); } - return null; + return { object: targetObject, field: probeField, code }; } /** @@ -2832,6 +3042,8 @@ export class SeedLoaderService implements ISeedLoaderService { : [deferred.attemptedValue]; const resolvedItems: unknown[] = []; let missingItem: unknown; + /** [#33207] Why the database probes missed `missingItem`, when that is known. */ + let missingProbe: DatabaseProbeOutcome | undefined; let stillUnresolved = false; /** [#31021] Elements naming a seed row a person removed from this organization. */ let withdrawnItems = 0; @@ -2855,6 +3067,7 @@ export class SeedLoaderService implements ISeedLoaderService { // 'invalid' can't reach pass 2 (pass 1 drops it), but treat it as a // miss rather than writing an unresolvable value. missingItem = item; + if (outcome.status === 'unresolved') missingProbe = outcome.miss; stillUnresolved = true; break; } @@ -3043,14 +3256,26 @@ export class SeedLoaderService implements ISeedLoaderService { // row counter reads healthy while the association it declared is // permanently absent. const missedValue = this.formatAttempted(stillUnresolved ? missingItem : deferred.attemptedValue); + // [#33207] Why no row answered, said as what it is: a refused probe is + // not an absent row, and a person outside the load's organization is + // not resolved on purpose. + const why = missingProbe?.refusal + ? `because the probe into ${missingProbe.refusal.object} by ${missingProbe.refusal.field} was REFUSED ` + + `(${missingProbe.refusal.code}) and never ran, so this is not evidence that no such row exists. Fix ` + + `what the refusal names (logged above, once) and re-run the seed to complete the link.` + : missingProbe?.nonMemberOf + ? `because the ${deferred.targetObject} row that answers to it is not a member of organization ` + + `${missingProbe.nonMemberOf}, the organization this load seeds, and a person from outside it is ` + + `never borrowed. Add that person to the organization (or name a member) and re-run the seed.` + : `because no such ${deferred.targetObject} row exists — neither seeded in this load nor already in ` + + `the database. Add the missing ${deferred.targetObject} record to the seed (or fix the natural key ` + + `that names it) and re-run the seed to complete the link.`; this.logger.error( `[SeedLoader] Deferred reference UNRESOLVED after pass 2 — ${deferred.objectName}.${deferred.field} ` + `is NULL at the end of pass 2 on record '${recordName}'. The row itself was seeded, so every row ` + `counter looks healthy while the relationship is MISSING: nothing links it to ` + - `${deferred.targetObject}.${deferred.targetField} = '${missedValue}', because no such ` + - `${deferred.targetObject} row exists — neither seeded in this load nor already in the database. ` + - `No further seed pass retries this: pass 2 is the last one. Add the missing ${deferred.targetObject} ` + - `record to the seed (or fix the natural key that names it) and re-run the seed to complete the link. ` + + `${deferred.targetObject}.${deferred.targetField} = '${missedValue}', ${why} ` + + `No further seed pass retries this: pass 2 is the last one. ` + PASS_2_SCOPE_NOTE, undefined, { @@ -3061,7 +3286,12 @@ export class SeedLoaderService implements ISeedLoaderService { }, ); this.recordDeferredError(deferred, allResults, allErrors, - `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${missedValue}' → ${deferred.targetObject}.${deferred.targetField} not found`); + `Deferred reference unresolved after pass 2: ${deferred.objectName}.${deferred.field} = '${missedValue}' → ${deferred.targetObject}.${deferred.targetField} not found` + + (missingProbe?.refusal + ? `; the probe was refused (${missingProbe.refusal.code}), so this is not evidence that no such row exists` + : missingProbe?.nonMemberOf + ? `; the ${deferred.targetObject} row that answers to it is not a member of organization ${missingProbe.nonMemberOf}` + : '')); } } } @@ -3091,10 +3321,20 @@ export class SeedLoaderService implements ISeedLoaderService { recordId: string, resolvedValue: unknown, ): Promise { - await withTransientRetry(() => this.engine.update(deferred.objectName, { + const updated = await withTransientRetry(() => this.engine.update(deferred.objectName, { id: recordId, [deferred.field]: resolvedValue, - }, SeedLoaderService.SEED_OPTIONS as any)); + }, this.writeOptionsFor(deferred.rowOrganization) as any)); // [#33206] the organization the row was written as + // [#33206] A by-id update that matched no row answers `null`: the row is + // gone since pass 1, or (under a walled posture) the organization the write + // carries cannot see it. The link was NOT written, so it is never counted + // as resolved: the caller reports it like any other failed back-fill. + if (updated === null) { + throw new Error( + `The back-fill update of ${deferred.objectName} '${recordId}' matched no row: the row is gone, or the ` + + `organization the write carries cannot see it.`, + ); + } } /** @@ -3151,6 +3391,58 @@ export class SeedLoaderService implements ISeedLoaderService { */ private static readonly SEED_OPTIONS = { context: SEED_WRITE_EXECUTION_CONTEXT } as const; + /** + * [#33206] The options bag every write of the CURRENT {@link load} uses: the + * shared seed posture, with `tenantId` set to the organization the load + * stamps its rows with, so a hook on a seeded row sees that organization as + * `ctx.session.organizationId`, as it does on the same row written through + * the API. A load with no organization (neither pinned nor derived) keeps + * {@link SEED_OPTIONS} itself. Set once per load, after the organization is + * known. A row that supplies its own, different `organization_id` is + * written with that one instead: see {@link writeOptionsFor}. + */ + private seedOptions: { readonly context: Record } = SeedLoaderService.SEED_OPTIONS; + + /** [#33206] The organization {@link seedOptions} carries, or `undefined` for a load with none. */ + private writeOrganization: string | undefined; + + /** [#33206] Per-load bags for rows that supply an organization other than the load's, by organization. */ + private rowWriteOptions = new Map }>(); + + /** + * [#33206] The options bag one row is written with. A record that supplies + * its own `organization_id` keeps it (the stamp never overrides it), so its + * writes carry THAT organization: its hooks see the organization the row is + * really stamped with, and under a walled posture its by-id writes (an + * update of an existing row, the pass-2 back-fill of a deferred reference) + * are scoped to the organization the row lives in, where the load's own + * would match no row. Every other row, and every write of a load with no + * organization, uses {@link seedOptions} unchanged. + */ + private writeOptionsFor(rowOrganization: unknown): { readonly context: Record } { + if ( + !this.writeOrganization || + typeof rowOrganization !== 'string' || + rowOrganization === '' || + rowOrganization === this.writeOrganization + ) { + return this.seedOptions; + } + let bag = this.rowWriteOptions.get(rowOrganization); + if (!bag) { + bag = { context: { ...SEED_WRITE_EXECUTION_CONTEXT, tenantId: rowOrganization } }; + this.rowWriteOptions.set(rowOrganization, bag); + } + return bag; + } + + /** + * [#33207] How many same-named people one page of the membership probe + * weighs. A name is not unique above the organization, so the probe pages + * through every person the key names; the page only bounds each read. + */ + private static readonly MEMBER_PROBE_PAGE = 50; + /** * The engine write {@link writeRecoveringSummary} guards, as a NAMED callee. * @@ -3261,7 +3553,7 @@ export class SeedLoaderService implements ISeedLoaderService { comparands: ReplayComparands, ): Promise<{ action: 'inserted' | 'updated' | 'skipped'; id?: string; uncompared?: readonly string[] }> { const existing = existingRecords?.get(this.externalIdKey(record, externalId)); - const opts = SeedLoaderService.SEED_OPTIONS as any; + const opts = this.writeOptionsFor(record['organization_id']) as any; // [#33206] switch (mode) { case 'insert': { @@ -4167,7 +4459,7 @@ export class SeedLoaderService implements ISeedLoaderService { * closure no AST scan of the caller's `try` reaches. */ private async writeLandedKeys(rows: Array>): Promise { - await withTransientRetry(() => this.engine.insert(SEED_LANDED_KEY_OBJECT, rows, SeedLoaderService.SEED_OPTIONS as any)); + await withTransientRetry(() => this.engine.insert(SEED_LANDED_KEY_OBJECT, rows, this.seedOptions as any)); } /** @@ -4428,4 +4720,11 @@ interface DeferredUpdate { /** Source field stores an array of references, so pass 2 back-fills an array. */ multiple?: boolean; recordIndex: number; + /** + * [#33206] The `organization_id` the source row was written with, annotated + * once its dataset has written: pass 2 back-fills the reference as the same + * organization (`writeOptionsFor`), so a row that supplied its own + * organization is found by its by-id update under a walled posture. + */ + rowOrganization?: unknown; } diff --git a/packages/runtime/src/seed-org-scoped-references.integration.test.ts b/packages/runtime/src/seed-org-scoped-references.integration.test.ts new file mode 100644 index 00000000000..b031fec8f1e --- /dev/null +++ b/packages/runtime/src/seed-org-scoped-references.integration.test.ts @@ -0,0 +1,419 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #33207 + #33206 — an organization-scoped seed load resolves people through + * membership, and every seed write carries the organization its rows are + * stamped with. + * + * ## The two defects, as measured on `main` + * + * 1. On a per-organization replay the reference probe AND-scoped EVERY target + * with `organization_id = `, `sys_user` included. `sys_user` + * carries no organization column, so the driver refused the filter + * (`INVALID_FILTER`), a bare `catch` read the refusal as "no match", and a + * seed record naming a person who exists — and is a member — landed owned + * by nobody, reported as "no such sys_user row exists". + * 2. Every seed write ran under `SEED_WRITE_EXECUTION_CONTEXT`, which carries + * no organization, although the loader stamps each row with one. A hook on + * a seeded row saw `ctx.session` without `organizationId`, so a system hook + * that scopes its reads to the writer's organization derived nothing. + * + * ## Why this file runs real implementations + * + * The refusal is the SQL driver's (`sys_user` has no such column) and the + * hook's view is built by the engine from the write's execution context, so an + * engine double would encode the facts under test. This file boots the REAL + * `AppPlugin` (its per-organization `seed-replayer` on a walled boot, its inline + * seed on a `single` boot), the real `SeedLoaderService`, a real `ObjectQL` and + * a real `SqlDriver` over better-sqlite3, the way + * `seed-replay-per-organization-identity.integration.test.ts` does, and asserts + * on stored rows and on what a registered hook received. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +// AppPlugin loads `@objectstack/metadata` lazily; pay that load during collection, +// never inside a clocked case. +import '@objectstack/metadata'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysUser, SysMember, SysOrganization } from '@objectstack/platform-objects/identity'; +import type { PluginContext } from '@objectstack/core'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { AppPlugin } from './app-plugin'; +import { SeedLoaderService } from './seed-loader'; + +/** better-auth-shaped organization ids — the shape every real organization has. */ +const ORG_NORTH = 'org_msnorthd2a7k3x9qf'; +const ORG_SOUTH = 'org_mssouthd2p4w8m2zc'; + +/** An app object that names people and an account, the shape of a CRM deal. */ +const Deal = { + name: 'crm_deal', + label: 'Deal', + fields: { + name: { type: 'text', label: 'Name' }, + rep: { type: 'lookup', label: 'Rep', reference: 'sys_user' }, + account: { type: 'lookup', label: 'Account', reference: 'crm_account' }, + country: { type: 'lookup', label: 'Country', reference: 'crm_country' }, + home_org: { type: 'lookup', label: 'Home organization', reference: 'sys_organization' }, + ledger_kind: { type: 'lookup', label: 'Ledger kind', reference: 'crm_ledger_kind' }, + tag: { type: 'lookup', label: 'Tag', reference: 'crm_workspace_tag' }, + }, +}; +/** A tenant-carrying app object: its rows belong to one organization each. */ +const Account = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }; +/** A global catalog by its author's declaration: no organization column. */ +const Country = { + name: 'crm_country', + label: 'Country', + tenancy: { enabled: false }, + fields: { name: { type: 'text', label: 'Name' } }, +}; +/** A platform-managed table with no organization column — not a seed target. */ +const LedgerKind = { + name: 'crm_ledger_kind', + label: 'Ledger kind', + managedBy: 'engine-owned', + systemFields: { tenant: false }, + fields: { name: { type: 'text', label: 'Name' } }, +}; + +/** + * An author's object with no `organization_id` column that is STILL walled per + * organization, by another tenant column: not a global object. + */ +const WorkspaceTag = { + name: 'crm_workspace_tag', + label: 'Workspace tag', + tenancy: { enabled: true, tenantField: 'workspace_id' }, + systemFields: { tenant: false }, + fields: { name: { type: 'text', label: 'Name' }, workspace_id: { type: 'text', label: 'Workspace' } }, +}; +/** A self-referencing tenant-carrying object: a forward reference to it defers to pass 2. */ +const Task = { + name: 'crm_task', + label: 'Task', + fields: { name: { type: 'text', label: 'Name' }, parent: { type: 'lookup', label: 'Parent', reference: 'crm_task' } }, +}; + +const OBJECTS = [SysUser, SysMember, SysOrganization, Deal, Account, Country, LedgerKind, WorkspaceTag, Task] as const; + +type Row = Record & { id: string; name: string }; +type Replayer = (organizationId: string, options?: { reseed?: boolean }) => Promise<{ + inserted: number; + errors: Array<{ message: string }>; +}>; + +const openDrivers: SqlDriver[] = []; +const envBefore = { budget: process.env.OS_INLINE_SEED_BUDGET_MS, posture: process.env.OS_TENANCY_POSTURE }; + +afterEach(async () => { + while (openDrivers.length) { + try { + await openDrivers.pop()?.disconnect(); + } catch { + /* a test that already disconnected is not a failure */ + } + } + for (const [key, name] of [['budget', 'OS_INLINE_SEED_BUDGET_MS'], ['posture', 'OS_TENANCY_POSTURE']] as const) { + if (envBefore[key] === undefined) delete process.env[name]; + else process.env[name] = envBefore[key]; + } +}); + +interface BootOptions { + /** `isolated` boots walled (AppPlugin registers the replayer); `single` seeds inline. */ + readonly posture: 'isolated' | 'single'; + /** The seed the app declares. */ + readonly data: ReadonlyArray>; + /** + * Register `sys_organization` (and create the organizations). Default true. + * Without it the load has no organization at all, so the deal object is + * registered as a global one (its rows carry none either). + */ + readonly organizations?: boolean; +} + +async function boot(options: BootOptions) { + process.env.OS_INLINE_SEED_BUDGET_MS = '60000'; + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + openDrivers.push(driver); + const engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + const objects = OBJECTS.filter((o) => options.organizations !== false || o !== SysOrganization) + .map((o) => (options.organizations === false && o === Deal ? { ...Deal, tenancy: { enabled: false } } : o)); + for (const o of objects) engine.registry.registerObject(o as any, '@objectstack/platform-objects'); + const definitions = objects.map((o) => engine.registry.getObject((o as { name: string }).name) ?? o); + await driver.initObjects(definitions as any); + + const sys = { context: { isSystem: true } } as any; + if (options.organizations !== false) { + await engine.insert('sys_organization', { id: ORG_NORTH, name: 'North', slug: 'north' }, sys); + if (options.posture === 'isolated') await engine.insert('sys_organization', { id: ORG_SOUTH, name: 'South', slug: 'south' }, sys); + } + // People. Zhang Wei is a member of North only. Two people are named Wang + // Fang, one per organization; the South one exists FIRST, so a probe that + // ignored membership would hand North the South person. + await engine.insert('sys_user', { id: 'usr_wang_south', name: 'Wang Fang', email: 'wang.s@example.com' }, sys); + await engine.insert('sys_user', { id: 'usr_wang_north', name: 'Wang Fang', email: 'wang.n@example.com' }, sys); + await engine.insert('sys_user', { id: 'usr_zhang', name: 'Zhang Wei', email: 'zhang@example.com' }, sys); + if (options.organizations !== false) { + await engine.insert('sys_member', { id: 'mem_zhang_n', user_id: 'usr_zhang', organization_id: ORG_NORTH, role: 'member' }, sys); + await engine.insert('sys_member', { id: 'mem_wang_n', user_id: 'usr_wang_north', organization_id: ORG_NORTH, role: 'member' }, sys); + await engine.insert('sys_member', { id: 'mem_wang_s', user_id: 'usr_wang_south', organization_id: ORG_SOUTH, role: 'member' }, sys); + // An account that exists only in South. + await engine.insert('crm_account', { id: 'acc_globex_s', name: 'Globex', organization_id: ORG_SOUTH }, sys); + } + await engine.insert('crm_country', { id: 'cty_cn', name: 'China' }, sys); + await engine.insert('crm_ledger_kind', { id: 'lk_std', name: 'Standard' }, sys); + + /** What every hook on a deal row received: the session and the row's organization. */ + const seen: Array<{ name: unknown; session: Record | undefined; rowOrganization: unknown }> = []; + engine.registerHook('afterInsert', async (hctx: any) => { + seen.push({ name: hctx.input?.data?.name, session: hctx.session, rowOrganization: hctx.result?.organization_id }); + }, { object: 'crm_deal' }); + + const metadata = { + getObject: vi.fn(async (name: string) => definitions.find((d: any) => d.name === name)), + listObjects: vi.fn(async () => definitions), + getObjects: vi.fn(async () => definitions), + get: vi.fn(async () => undefined), + list: vi.fn(async () => []), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + register: vi.fn(async () => {}), + unregister: vi.fn(async () => {}), + }; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const services = new Map(); + if (options.posture === 'isolated') services.set('tenancy', { posture: 'isolated' }); + const ctx = { + logger, + registerService: vi.fn((name: string, svc: unknown) => { services.set(name, svc); }), + getService: vi.fn((name: string) => (name === 'objectql' ? engine : name === 'metadata' ? metadata : services.get(name))), + getServices: vi.fn(() => services), + hook: vi.fn(), + trigger: vi.fn(), + } as unknown as PluginContext; + + await new AppPlugin({ id: 'com.example.seed-org-scoped-references', data: [...options.data] as any }).start(ctx); + + const replayer = services.get('seed-replayer') as Replayer | undefined; + const dealsOf = async (organizationId?: string): Promise => + (await engine.find('crm_deal', { + where: organizationId ? { organization_id: organizationId } : {}, + context: { isSystem: true }, + } satisfies EngineQueryOptions)) as Row[]; + return { engine, metadata, logger, replayer, dealsOf, seen }; +} + +const deals = (records: Array>) => ({ object: 'crm_deal', mode: 'upsert', externalId: 'name', records }); + +describe('#33207 an organization-scoped load resolves a person through membership in that organization', () => { + it('a member of the load organization is resolved, by every probe the person reference takes', async () => { + const { replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', rep: 'Zhang Wei', owner_id: 'Zhang Wei' }])] }); + const north = await replayer!(ORG_NORTH); + expect(north.errors).toEqual([]); + const [row] = await dealsOf(ORG_NORTH); + expect(row).toMatchObject({ rep: 'usr_zhang', owner_id: 'usr_zhang' }); + }); + + it('a same-named person who is not a member of the load organization is NOT resolved — never borrowed', async () => { + const { replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', rep: 'Wang Fang' }, { name: 'Deal 2', rep: 'Zhang Wei' }])] }); + + await replayer!(ORG_NORTH); + const south = await replayer!(ORG_SOUTH); + + // Two people are named Wang Fang; each organization gets its own member, + // although the South one is the first row the name matches. + const byName = (rows: Row[]) => Object.fromEntries(rows.map((r) => [r.name, r.rep ?? null])); + expect(byName(await dealsOf(ORG_NORTH))).toEqual({ 'Deal 1': 'usr_wang_north', 'Deal 2': 'usr_zhang' }); + // Zhang Wei exists and is a member of North only: South does not get him. + expect(byName(await dealsOf(ORG_SOUTH))).toEqual({ 'Deal 1': 'usr_wang_south', 'Deal 2': null }); + expect(south.errors).toHaveLength(1); + expect(south.errors[0].message).toContain(`not a member of organization ${ORG_SOUTH}`); + }); + + it('a member among more same-named people than one read holds is found; "not a member" is said only after all were asked', async () => { + const { engine, replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', rep: 'Li Na' }])] }); + const sys = { context: { isSystem: true } } as any; + // Sixty people named Li Na; only the one with the highest id is a member of + // North, so a probe that weighed a single page of candidates misses her. + for (let n = 0; n < 60; n++) { + await engine.insert('sys_user', { id: `usr_li_${String(n).padStart(2, '0')}`, name: 'Li Na', email: `li.${n}@example.com` }, sys); + } + await engine.insert('sys_member', { id: 'mem_li_n', user_id: 'usr_li_59', organization_id: ORG_NORTH, role: 'member' }, sys); + + const north = await replayer!(ORG_NORTH); + const south = await replayer!(ORG_SOUTH); + + expect(north.errors).toEqual([]); + expect((await dealsOf(ORG_NORTH))[0].rep).toBe('usr_li_59'); + expect((await dealsOf(ORG_SOUTH))[0].rep ?? null).toBeNull(); + expect(south.errors).toHaveLength(1); + expect(south.errors[0].message).toContain(`not a member of organization ${ORG_SOUTH}`); + }); + + it('a refused probe is reported with its code, not swallowed as "not found"', async () => { + const { replayer, logger } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', ledger_kind: 'Standard' }])] }); + + const north = await replayer!(ORG_NORTH); + + // The target is platform-managed and carries no organization column: the + // organization filter is refused by the driver, and the reference says so. + expect(north.errors).toHaveLength(1); + expect(north.errors[0].message).toContain('INVALID_FILTER'); + const refusals = logger.warn.mock.calls.filter((c) => (c[1] as { code?: string } | undefined)?.code === 'INVALID_FILTER'); + expect(refusals.map((c) => (c[1] as { object: string }).object)).toContain('crm_ledger_kind'); + // Said once per target, field and code — not once per value and pass. + const keys = refusals.map((c) => JSON.stringify(c[1])); + expect(new Set(keys).size).toBe(keys.length); + }); + + it('a global catalog (no organization column, by its author) resolves on an organization-scoped load', async () => { + const { replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', country: 'China' }])] }); + expect((await replayer!(ORG_NORTH)).errors).toEqual([]); + expect((await dealsOf(ORG_NORTH))[0].country).toBe('cty_cn'); + }); + + it('an object walled by another tenant column is not taken for a global one: another organization’s row is not borrowed', async () => { + const { engine, replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', tag: 'Gold' }])] }); + await engine.insert('crm_workspace_tag', { id: 'tag_gold_s', name: 'Gold', workspace_id: ORG_SOUTH }, { context: { isSystem: true } } as any); + + const north = await replayer!(ORG_NORTH); + + expect((await dealsOf(ORG_NORTH))[0].tag ?? null).toBeNull(); + expect(north.errors).toHaveLength(1); + }); + + it('the organization table answers only for the load organization', async () => { + const { replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Mine', home_org: 'North' }, { name: 'Theirs', home_org: 'South' }])] }); + await replayer!(ORG_NORTH); + const byName = Object.fromEntries((await dealsOf(ORG_NORTH)).map((r) => [r.name, r.home_org ?? null])); + expect(byName).toEqual({ Mine: ORG_NORTH, Theirs: null }); + }); + + it('CONTROL — a tenant-carrying target still gets the organization filter: another organization’s row is not borrowed', async () => { + const { replayer, dealsOf } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1', account: 'Globex' }])] }); + const north = await replayer!(ORG_NORTH); + await replayer!(ORG_SOUTH); + expect((await dealsOf(ORG_NORTH))[0].account ?? null).toBeNull(); + expect(north.errors).toHaveLength(1); + expect((await dealsOf(ORG_SOUTH))[0].account).toBe('acc_globex_s'); + }); + + it('CONTROL — a load with no organization probes unscoped, as before: no membership is asked', async () => { + // This composition holds no organization and no membership at all, so a + // person resolves only if the probe is the unscoped one it always was. + const { dealsOf, seen } = await boot({ posture: 'single', organizations: false, data: [deals([{ name: 'Deal 1', rep: 'Zhang Wei' }])] }); + const [row] = await dealsOf(); + expect(row.rep).toBe('usr_zhang'); + expect(seen).toHaveLength(1); + }); +}); + +describe('#33206 a seed write carries the organization its rows are stamped with', () => { + it('a hook on a seeded row sees the load organization on a per-organization replay and on a reseed', async () => { + const { engine, replayer, dealsOf, seen } = await boot({ posture: 'isolated', data: [deals([{ name: 'Deal 1' }])] }); + + await replayer!(ORG_NORTH); + await replayer!(ORG_SOUTH); + // A reseed inserts a missing seed row again: remove South's, then reseed. + await engine.delete('crm_deal', { where: { id: (await dealsOf(ORG_SOUTH))[0].id }, context: { isSystem: true } } as any); + await replayer!(ORG_SOUTH, { reseed: true }); + + expect(seen.map((s) => [s.session?.organizationId, s.rowOrganization])).toEqual([ + [ORG_NORTH, ORG_NORTH], + [ORG_SOUTH, ORG_SOUTH], + [ORG_SOUTH, ORG_SOUTH], + ]); + for (const s of seen) expect(s.session).toMatchObject({ isSystem: true, skipTriggers: true }); + }); + + it('a hook on a seeded row sees the organization on a `single` boot, where the rows take the sole organization', async () => { + const { seen } = await boot({ posture: 'single', data: [deals([{ name: 'Deal 1' }])] }); + expect(seen).toHaveLength(1); + expect(seen[0].rowOrganization).toBe(ORG_NORTH); + expect(seen[0].session?.organizationId).toBe(ORG_NORTH); + }); + + it('a direct load pinned to an organization (the install path) writes with it', async () => { + const { engine, metadata, logger, seen } = await boot({ posture: 'isolated', data: [] }); + const loader = new SeedLoaderService(engine as any, metadata as any, logger as any); + await loader.load({ seeds: [deals([{ name: 'Installed' }])], config: { multiPass: true, organizationId: ORG_SOUTH } } as any); + expect(seen.map((s) => s.session?.organizationId)).toEqual([ORG_SOUTH]); + }); + + it('a row that supplies its own organization is written as that organization, its pass-2 back-fill included', async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + const { engine, metadata, logger, seen } = await boot({ posture: 'isolated', data: [] }); + // An id the loader keeps as written (UUID-shaped; an `org_` id names no + // organization but the load's own on a pinned load, so it never lands). + const ORG_EAST = '5f0c2d9e-7b1a-4c3e-9a8d-2e6f1b0c4a77'; + await engine.insert('sys_organization', { id: ORG_EAST, name: 'East', slug: 'east' }, { context: { isSystem: true } } as any); + const loader = new SeedLoaderService(engine as any, metadata as any, logger as any); + + const result = await loader.load({ + seeds: [ + deals([{ name: 'Theirs', organization_id: ORG_EAST }]), + // `Child` names `Parent` before it exists, so its link is back-filled in + // pass 2 by id; the row lives in East, the load is pinned to North. + { object: 'crm_task', mode: 'upsert', externalId: 'name', records: [{ name: 'Child', parent: 'Parent', organization_id: ORG_EAST }, { name: 'Parent' }] }, + ], + config: { multiPass: true, organizationId: ORG_NORTH }, + } as any); + + expect(result.errors).toEqual([]); + expect(seen.map((s) => [s.session?.organizationId, s.rowOrganization])).toEqual([[ORG_EAST, ORG_EAST]]); + const tasks = (await engine.find('crm_task', { where: {}, context: { isSystem: true } } satisfies EngineQueryOptions)) as Row[]; + const byName = Object.fromEntries(tasks.map((t) => [t.name, t])); + expect(byName.Child.organization_id).toBe(ORG_EAST); + expect(byName.Child.parent).toBe(byName.Parent.id); + }); + + it('a pass-2 back-fill the write organization cannot see is reported as an error, never counted as resolved', async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + const { engine, metadata, logger } = await boot({ posture: 'isolated', data: [] }); + // By the time pass 2 writes its link, the source row has moved to another + // organization: the by-id update, scoped to the organization the row was + // written as, finds no row (ObjectQL answers it with a not-found refusal). + engine.registerHook('afterInsert', async (hctx: any) => { + if (hctx.input?.data?.name !== 'Parent') return; + const [child] = (await engine.find('crm_task', { where: { name: 'Child' }, context: { isSystem: true } } satisfies EngineQueryOptions)) as Row[]; + await engine.update('crm_task', { id: child.id, organization_id: ORG_SOUTH }, { context: { isSystem: true } } as any); + }, { object: 'crm_task' }); + const loader = new SeedLoaderService(engine as any, metadata as any, logger as any); + + const result = await loader.load({ + seeds: [{ object: 'crm_task', mode: 'upsert', externalId: 'name', records: [{ name: 'Child', parent: 'Parent' }, { name: 'Parent' }] }], + config: { multiPass: true, organizationId: ORG_NORTH }, + } as any); + + expect(result.errors).toHaveLength(1); + expect(result.errors[0]).toMatchObject({ sourceObject: 'crm_task', field: 'parent' }); + expect(result.errors[0].message).toContain('not found in crm_task'); + }); + + it('CONTROL — a load with no organization, pinned or derived, writes with the seed posture unchanged', async () => { + const { seen } = await boot({ posture: 'single', organizations: false, data: [deals([{ name: 'Deal 1' }])] }); + expect(seen).toHaveLength(1); + expect(seen[0].session).toEqual({ isSystem: true, skipTriggers: true }); + }); + + it.each(['isolated', 'group'] as const)('under the walled posture %s a hook reads through ctx.api within the load organization (the declared narrowing)', async (posture) => { + process.env.OS_TENANCY_POSTURE = posture; + const { engine, replayer } = await boot({ posture: 'isolated', data: [deals([{ name: 'Seeded' }])] }); + await engine.insert('crm_deal', { name: 'South deal', organization_id: ORG_SOUTH }, { context: { isSystem: true } } as any); + const reads: string[][] = []; + engine.registerHook('afterInsert', async (hctx: any) => { + if (hctx.input?.data?.name !== 'Seeded') return; + const rows = (await hctx.api.object('crm_deal').find({ where: {} })) as Row[]; + reads.push(rows.map((r) => r.name).sort()); + }, { object: 'crm_deal' }); + + await replayer!(ORG_NORTH); + + expect(reads).toEqual([['Seeded']]); + }); +});