diff --git a/.changeset/31823-job-pull-organization.md b/.changeset/31823-job-pull-organization.md new file mode 100644 index 00000000000..766c21bc685 --- /dev/null +++ b/.changeset/31823-job-pull-organization.md @@ -0,0 +1,13 @@ +--- +'@objectstack/runtime': patch +'@objectstack/objectql': patch +--- + +fix(runtime): a job with no `organization` pulls as the organization its writes are stamped with, so its upsert match uses the organization index + +Clause-②: yes (widening) — @objectstack/objectql gains `ObjectQL#systemWriteOrganization()`, the engine's own answer to which organization an organization-less system write resolves to +Metadata-protocol: none + +A `job` whose `pull` syncs a mapping and that declares no `organization` ran its pull with no organization in its context (`{ isSystem: true }`). Every write of that pull was still stamped with the install's organization: on the `single` posture with exactly one organization, the engine derives it for an organization-less system write (ADR-0131 D9). But the import's match lookup had no organization to scope by, so on `single`, where a read gets no tenant scope, it read the target table once per row instead of probing the `(organization_id, )` unique index. A large sync on the most common setup stayed table-scan slow. + +Each run of such a pull now asks the engine, once, before it reads or writes, the same decision the engine's system insert makes, and runs as that organization when the engine derives one. The lookup then carries it on the tenant column, and the rows land exactly where they did before. When the engine does not derive one (a `group` or `isolated` posture, zero or several organizations, a composition with no organization object), the pull runs as before, and its writes are refused or stamped exactly as before. A job that declares an `organization` is unchanged, and so are the `body` and `handler` run forms. If the organization probe fails, the run says so once at `warn`, naming the job, and goes on as before. diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index 5be9249ef74..4229f070195 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -40,7 +40,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isWriteEpochOperation } from './write-epoch.js'; import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; -import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName } from './tenancy/system-write-organization.js'; +import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName, type SystemWriteOrganizationDecision } from './tenancy/system-write-organization.js'; import { isFederatedObject } from './federated-object.js'; import type { EngineMiddleware, OperationContext } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; @@ -359,24 +359,34 @@ export class MiddlewareAndContextFacet { if (rows.every((row) => carriesOrganization(row?.[tenantField]))) return undefined; const posture = this.resolveEnginePosture(); + const decision = await MiddlewareAndContextFacet.systemWriteOrganization.call(this, posture); + if (decision.kind === 'derived') return decision.organizationId; + if (decision.kind === 'no-organization-object') return undefined; + throw new SystemWriteOrganizationRequiredError( + object, + posture, + decision.reason, + decision.organizationCount, + ); + } + + /** + * The body of `ObjectQL#systemWriteOrganization`; the method's docblock there + * is its contract. Also the decision half of + * {@link resolveSystemInsertOrganization}, which hands in the posture it has + * already read, so the insert and the public answer are one assembly. + */ + static async systemWriteOrganization(this: Pick, posture = this.resolveEnginePosture()): Promise { // [ADR-0131 D9] Zero organizations is refused under `single` only where // the composition registers the organization object; the composition that // registers none keeps today's branch (`no-organization-object`). The // probe itself is unchanged and answers `[]` for both — this is the one // fact that tells them apart, read from the same registry the probe reads. - const decision = await resolveSystemWriteOrganization({ + return resolveSystemWriteOrganization({ posture, probeOrganizations: () => this.probeInstallOrganizations(), organizationObjectRegistered: !!this._registry.getObject(ORGANIZATION_OBJECT), }); - if (decision.kind === 'derived') return decision.organizationId; - if (decision.kind === 'no-organization-object') return undefined; - throw new SystemWriteOrganizationRequiredError( - object, - posture, - decision.reason, - decision.organizationCount, - ); } /** diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 4bce8bf6cea..d44515ba92b 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -200,6 +200,7 @@ import { redactBoundStatement } from '@objectstack/types'; // supplies the facts and turns a `refuse` into the throw. import { ORGANIZATION_OBJECT, + type SystemWriteOrganizationDecision, } from './tenancy/system-write-organization.js'; import { type TenancyPosture, @@ -3054,6 +3055,32 @@ export class ObjectQL implements IObjectQLEngine { return SecretsAndRoutingFacet.setTenancyPostureProvider.call(secretsAndRoutingHost.of(this), provider); } + /** + * [ADR-0131 D9] The organization a SYSTEM-context write that carries none + * resolves to on this engine — the decision its own system insert makes + * (`resolveSystemInsertOrganization`), from the same three inputs: the + * posture in force (the injected tenancy-posture accessor, else the + * deployment's), the install's organizations (the memoised probe, capped at + * two), and whether this composition registers `sys_organization` at all. + * The predicate is `@objectstack/core`'s `resolveSystemWriteOrganization`, + * never a second spelling of it. + * + * For a caller that runs system work with no organization of its own and + * wants to carry, ahead of its writes, the organization those writes would + * be stamped with — a job that declares no `organization` resolves its pull's + * context here, so the pull's reads scope by the organization its writes + * land in. Not a write and not a gate: it refuses nothing itself. A `refuse` + * decision is the answer the write would turn into its refusal, and the + * write stays the one that refuses. + * + * A probe that could not run (an outage, not an empty table) propagates, as + * it does on the insert. + */ + systemWriteOrganization(): Promise { + // [#31823] The body lives in `engine-middleware-and-context.ts` (see `MiddlewareAndContextHost`). + return MiddlewareAndContextFacet.systemWriteOrganization.call(middlewareAndContextHost.of(this)); + } + private async encryptSecretFields( object: string, row: Record, diff --git a/packages/objectql/src/system-write-organization.test.ts b/packages/objectql/src/system-write-organization.test.ts index c05cb315da9..8486cd5e876 100644 --- a/packages/objectql/src/system-write-organization.test.ts +++ b/packages/objectql/src/system-write-organization.test.ts @@ -229,6 +229,55 @@ describe('#8844 the decision — the ruling as one pure function', () => { }); }); +describe('ObjectQL#systemWriteOrganization — the engine answers the decision its system insert makes', () => { + // A caller with no organization of its own (a job pull) asks this up front, + // so the organization its reads scope by is the one its writes are stamped + // with. It must be the insert's own assembly: same posture, same probe (and + // memo), same registry fact — and it writes nothing. + const probes = (observed: ObservedCall[]) => observed.filter((c) => c.object === 'sys_organization' && c.method === 'find').length; + + it('single, one organization: derived — the organization a system insert is then stamped with', async () => { + const { engine, observed } = await makeEngine({ posture: 'single' }); + expect(await engine.systemWriteOrganization()).toEqual({ kind: 'derived', organizationId: ORG_ID }); + expect(observed.filter((c) => c.method !== 'find')).toEqual([]); + + await engine.insert('dispatch_order', { subject: 'stamped' }, { context: SYSTEM_CTX } as any); + expect(lastWrite(observed, 'dispatch_order')?.options?.tenantId).toBe(ORG_ID); + // One probe for both: the answer and the insert share the engine's memo. + expect(probes(observed)).toBe(1); + }); + + it('single, several organizations: refuse (ambiguous), as the insert refuses', async () => { + const { engine } = await makeEngine({ posture: 'single', organizations: [ORG_ID, SECOND_ORG_ID] }); + expect(await engine.systemWriteOrganization()) + .toEqual({ kind: 'refuse', reason: 'ambiguous-organization', organizationCount: 2 }); + }); + + it.each(['group', 'isolated'] as const)('the injected %s posture: refuse (walled), and nothing is probed', async (posture) => { + const { engine, observed } = await makeEngine({ posture }); + expect(await engine.systemWriteOrganization()).toEqual({ kind: 'refuse', reason: 'walled-posture' }); + expect(probes(observed)).toBe(0); + }); + + it('no provider injected: the posture is the deployment\'s, as on the insert', async () => { + vi.stubEnv('OS_TENANCY_POSTURE', 'isolated'); + const { engine } = await makeEngine(); + expect(await engine.systemWriteOrganization()).toEqual({ kind: 'refuse', reason: 'walled-posture' }); + }); + + it('a composition with no organization object: no-organization-object', async () => { + const { engine } = await makeEngine({ posture: 'single', lean: true }); + expect(await engine.systemWriteOrganization()).toEqual({ kind: 'no-organization-object' }); + }); + + it('a probe that cannot run propagates — it is not answered as "no organization"', async () => { + const { engine } = await makeEngine({ posture: 'single' }); + const driver = engine.getDriverForObject('dispatch_order') as any; + driver.find = async () => { throw new Error('connection reset'); }; + await expect(engine.systemWriteOrganization()).rejects.toThrow('connection reset'); + }); +}); + describe('#8844 single-tenant — the system write is stamped like a session write', () => { it('derives the install organization for a system-context insert, and a session write is unchanged', async () => { const { engine, observed } = await makeEngine(); diff --git a/packages/runtime/src/app-artifact-handlers.job-pull.test.ts b/packages/runtime/src/app-artifact-handlers.job-pull.test.ts index 534eeb84576..8a6ed1775f1 100644 --- a/packages/runtime/src/app-artifact-handlers.job-pull.test.ts +++ b/packages/runtime/src/app-artifact-handlers.job-pull.test.ts @@ -38,7 +38,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { PluginContext } from '@objectstack/core'; import { SCHEDULED_WORK_ENV } from '@objectstack/types'; +import { runImport, type ExportFieldMeta, type ImportProtocolLike, type ImportRunSummary } from '@objectstack/core'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; import { collectJobsWithoutBody, scheduleAppArtifactJobs } from './app-artifact-handlers.js'; +// The source under test reaches `@objectstack/metadata` by dynamic import +// (`app-plugin.ts`); paid here, at collection, not inside a case's clock. +import '@objectstack/metadata'; import { withScheduledWorkOn } from './scheduled-work.test-support.js'; withScheduledWorkOn(); @@ -79,9 +87,10 @@ const result = (summary: Partial } = {}) { const writes: Array<{ object: string; data: unknown; context: unknown }> = []; const ql = { + ...opts.engine, createContext: (context: unknown) => ({ object: (object: string) => ({ insert: async (data: Record) => { @@ -416,3 +425,225 @@ describe('#20281 stage ③: an unreadable tenancy posture fails closed — and i } }); }); + +/** + * A job that declares no `organization` pulls as the organization its writes + * are stamped with: the engine's own system-write decision + * (`ObjectQL#systemWriteOrganization`, ADR-0131 D9), asked once per run before + * the pull reads or writes. Only `derived` changes the context; every other + * decision, an engine that does not answer, and a probe that throws keep + * `{ isSystem: true }`. The `body` and `handler` forms are unchanged. + */ +describe('a pull of a job with no organization runs as the organization its writes are stamped with', () => { + withPosture('single'); + + const decide = (decision: unknown) => vi.fn(async () => decision); + + it('derived: the pull context carries it, asked once per run', async () => { + const systemWriteOrganization = decide({ kind: 'derived', organizationId: 'org_one' }); + const h = harness({ engine: { systemWriteOrganization } }); + await h.schedule([PULL_JOB]); + expect(systemWriteOrganization).not.toHaveBeenCalled(); + + await h.run('orders_pull_hourly'); + await h.run('orders_pull_hourly'); + expect(h.pulls).toEqual([ + { mapping: 'orders_pull', context: { isSystem: true, tenantId: 'org_one' } }, + { mapping: 'orders_pull', context: { isSystem: true, tenantId: 'org_one' } }, + ]); + expect(systemWriteOrganization).toHaveBeenCalledTimes(2); + }); + + it('CONTROL: a job that declares an organization runs as it, and the engine is not asked', async () => { + const systemWriteOrganization = decide({ kind: 'derived', organizationId: 'org_one' }); + const h = harness({ engine: { systemWriteOrganization } }); + await h.schedule([{ ...PULL_JOB, organization: 'org_a' }]); + + await h.run('orders_pull_hourly'); + expect(h.pulls).toEqual([{ mapping: 'orders_pull', context: { isSystem: true, tenantId: 'org_a' } }]); + expect(systemWriteOrganization).not.toHaveBeenCalled(); + }); + + for (const [label, decision] of [ + ['refuse (several organizations)', { kind: 'refuse', reason: 'ambiguous-organization', organizationCount: 2 }], + ['refuse (no organization)', { kind: 'refuse', reason: 'no-organization', organizationCount: 0 }], + ['refuse (a walled posture)', { kind: 'refuse', reason: 'walled-posture' }], + ['no-organization-object', { kind: 'no-organization-object' }], + ] as const) { + it(`CONTROL: ${label} keeps today's context, and nothing is said`, async () => { + const h = harness({ engine: { systemWriteOrganization: decide(decision) } }); + await h.schedule([PULL_JOB]); + + expect(await h.run('orders_pull_hourly')).toEqual({ outcome: 'completed' }); + expect(h.pulls).toEqual([{ mapping: 'orders_pull', context: { isSystem: true } }]); + expect(h.said('warn')).toEqual([]); + }); + } + + it('CONTROL: an engine that does not answer the question keeps today\'s context', async () => { + const h = harness(); + await h.schedule([PULL_JOB]); + + await h.run('orders_pull_hourly'); + expect(h.pulls).toEqual([{ mapping: 'orders_pull', context: { isSystem: true } }]); + }); + + it('a probe that throws is said once at warn, naming the job, and the run goes on with today\'s context', async () => { + const systemWriteOrganization = vi.fn(async () => { throw new Error('connection reset'); }); + const h = harness({ engine: { systemWriteOrganization } }); + await h.schedule([PULL_JOB]); + + expect(await h.run('orders_pull_hourly')).toEqual({ outcome: 'completed' }); + expect(h.pulls).toEqual([{ mapping: 'orders_pull', context: { isSystem: true } }]); + const warns = h.logger.warn.mock.calls.filter((c) => String(c[0]).includes("'orders_pull_hourly'")); + expect(warns).toHaveLength(1); + expect(warns[0][1]).toMatchObject({ job: 'orders_pull_hourly', mapping: 'orders_pull', error: 'connection reset' }); + }); + + it('CONTROL: a body job and a handler job with no organization keep { isSystem: true }, and the engine is not asked', async () => { + const systemWriteOrganization = decide({ kind: 'derived', organizationId: 'org_one' }); + const h = harness({ engine: { systemWriteOrganization } }); + const seen: unknown[] = []; + const body = { language: 'js', capabilities: ['api.write'], source: "await ctx.api.object('tick').insert({ name: 'tick' });" }; + await h.schedule( + [{ name: 'plain_body', schedule: INTERVAL, body }, { name: 'plain_fn', schedule: INTERVAL, handler: 'sweep' }], + { functions: { sweep: async (jobCtx: { executionContext?: unknown }) => { seen.push(jobCtx.executionContext); } } }, + ); + + await h.run('plain_body'); + await h.run('plain_fn'); + expect(h.writes.map((w) => w.context)).toEqual([{ isSystem: true }]); + expect(seen).toEqual([{ isSystem: true }]); + expect(systemWriteOrganization).not.toHaveBeenCalled(); + }); +}); + +/** + * The same, against the REAL engine: `ObjectQL` over a `SqlDriver` + * (better-sqlite3 `:memory:`), the real protocol and the real `runImport`. The + * `automation` service here runs the import step a connector pull runs + * (`connector-pull.ts`: `runImport` over the protocol, under the pull's + * `context`), with the pulled records in hand, so the pin reads the query the + * match lookup actually sends. Before this, a no-organization job's lookup was + * `where external_id = ?` (a scan per row under `single`, where the engine adds + * no tenant scope to a read, ADR-0131 D11), while its writes were stamped with + * the one organization anyway. + */ +describe('a no-organization job pull on a real engine: the match lookup carries the organization its writes carry', () => { + withPosture('single'); + + const ITEM = { + name: 'po_item_31823', label: 'Item', + fields: { + external_id: { name: 'external_id', type: 'text' as const, label: 'External id', unique: true }, + title: { name: 'title', type: 'text' as const, label: 'Title' }, + }, + }; + const ORG_OBJECT = { name: 'sys_organization', label: 'Organization', fields: { name: { name: 'name', type: 'text' as const, label: 'Name' } } }; + const metaMap = new Map([ + ['external_id', { name: 'external_id', type: 'text' }], + ['title', { name: 'title', type: 'text' }], + ]); + const live: ObjectQL[] = []; + afterEach(async () => { + while (live.length) { + try { await live.pop()?.destroy(); } catch { /* noop */ } + } + }); + + interface Statement { sql: string; bindings: unknown[] } + + async function boot(organizations: string[]) { + const engine = new ObjectQL(); + live.push(engine); + engine.setTenancyPostureProvider(() => 'single'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [ITEM, ORG_OBJECT, SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + if (!engine.registry.getObject(o.name)) engine.registry.registerObject(o as any); + } + await engine.syncSchemas(); + // The install's organizations, planted through the driver (each its own + // owner, as the Default Organization row is): the engine only reads + // them, through its organization probe. + for (const id of organizations) await driver.create('sys_organization', { id, name: id, organization_id: id }); + const knex = (driver as unknown as { knex: any }).knex; + const protocol = new ObjectStackProtocolImplementation(engine as any) as unknown as ImportProtocolLike; + + const lookups: Statement[] = []; + knex.on('query', (q: Statement) => { + if (/^select \*/i.test(q.sql) && q.sql.includes(`\`${ITEM.name}\``) && q.sql.includes('`external_id` = ?')) { + lookups.push({ sql: q.sql, bindings: q.bindings }); + } + }); + const contexts: unknown[] = []; + const summaries: ImportRunSummary[] = []; + const automation = { + pullConnectorSource: vi.fn(async ({ context }: { mapping: string; context: Record }) => { + contexts.push(context); + const summary = await runImport({ + p: protocol, objectName: ITEM.name, context, metaMap, + rows: [{ external_id: 'E1', title: 'pulled' }, { external_id: 'E2', title: 'pulled' }], + writeMode: 'upsert', matchFields: ['external_id'], dryRun: false, runAutomations: true, + treatAsHistorical: false, trimWhitespace: true, createMissingOptions: false, skipBlankMatchKey: true, + }); + summaries.push(summary); + return { ...result(), summary }; + }), + }; + const h = harness({ automation }); + const schedule = (jobs: unknown[]) => scheduleAppArtifactJobs( + { logger: h.logger, getService: (n: string) => h.services[n] ?? (() => { throw new Error(`no ${n}`); })() } as unknown as PluginContext, + { id: APP_ID, version: '0.1.0', type: 'app', jobs, mappings: [MAPPING] }, + { appId: APP_ID, ql: engine as any, source: 'Test' }, + ); + const stored = async () => (await knex(ITEM.name).select('external_id', 'organization_id').orderBy('external_id')) as Array>; + return { h, schedule, lookups, contexts, summaries, stored, engine }; + } + + it('one organization: the pull runs as it, its lookup carries it on the tenant column, and its writes are stamped with it', async () => { + const b = await boot(['org_one']); + await b.schedule([PULL_JOB]); + + await b.h.run('orders_pull_hourly'); + expect(b.contexts).toEqual([{ isSystem: true, tenantId: 'org_one' }]); + expect(b.lookups).toHaveLength(2); + for (const [i, key] of (['E1', 'E2'] as const).entries()) { + expect(b.lookups[i].sql).toMatch(/where `organization_id` = \? and `external_id` = \?/); + expect(b.lookups[i].bindings.slice(0, 2)).toEqual(['org_one', key]); + } + expect(b.summaries[0]).toMatchObject({ errors: 0, created: 2 }); + expect(await b.stored()).toEqual([ + { external_id: 'E1', organization_id: 'org_one' }, + { external_id: 'E2', organization_id: 'org_one' }, + ]); + + // A second run matches the rows the first created: the same organization. + await b.h.run('orders_pull_hourly'); + expect(b.summaries[1]).toMatchObject({ errors: 0, created: 0, updated: 2 }); + }); + + it('CONTROL: a job that declares the organization reads and writes the same way, and the engine is not asked', async () => { + const b = await boot(['org_one']); + const asked = vi.spyOn(b.engine, 'systemWriteOrganization'); + await b.schedule([{ ...PULL_JOB, organization: 'org_one' }]); + + await b.h.run('orders_pull_hourly'); + expect(b.contexts).toEqual([{ isSystem: true, tenantId: 'org_one' }]); + expect(b.lookups[0].bindings.slice(0, 2)).toEqual(['org_one', 'E1']); + expect(asked).not.toHaveBeenCalled(); + }); + + it('CONTROL: two organizations: the pull runs with none, its lookup is the key alone, and its writes refuse as today', async () => { + const b = await boot(['org_one', 'org_two']); + await b.schedule([PULL_JOB]); + + await b.h.run('orders_pull_hourly'); + expect(b.contexts).toEqual([{ isSystem: true }]); + expect(b.lookups[0].sql).not.toContain('organization_id'); + expect(b.summaries[0]).toMatchObject({ errors: 2, created: 0 }); + expect(JSON.stringify(b.summaries[0].results)).toContain('ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED'); + expect(await b.stored()).toEqual([]); + }); +}); diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 1fb1fd13059..0175ea791a8 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -96,7 +96,9 @@ * under `group` (an undeclared job runs with no organization, said once at * `warn`), not required under `single`. Each run's execution context is * `{ isSystem: true, tenantId: }`, or `{ isSystem: true }` for a - * job that declares none ({@link jobExecutionContext}). + * job that declares none ({@link jobExecutionContext}) — except a `pull`, which + * runs as the organization its writes would be stamped with where the engine + * can derive one ({@link resolveJobPullOrganization}). * * A job's identity is its package coordinate — the package's id and the job's * name together, as the metadata registry keys it (`:`; @@ -128,7 +130,7 @@ * runtime module and passes no such option: its handler hooks bind unchanged. */ -import type { PluginContext } from '@objectstack/core'; +import type { PluginContext, SystemWriteOrganizationDecision } from '@objectstack/core'; import type { ConnectorSourcePullResult, IAutomationService, @@ -537,6 +539,58 @@ export function jobExecutionContext(organization: string | undefined): { isSyste return organization !== undefined ? { isSystem: true, tenantId: organization } : { isSystem: true }; } +/** + * The engine face {@link resolveJobPullOrganization} asks: + * `ObjectQL#systemWriteOrganization`, the decision the engine's own + * system-context insert makes (ADR-0131 D9). + */ +interface SystemWriteOrganizationSource { + systemWriteOrganization(): Promise; +} + +/** + * The organization a job's `pull` runs as, resolved ONCE per run, before the + * pull reads or writes anything. + * + * A job that declares an `organization` runs as it, unchanged. A job that + * declares none runs its pull as the organization its writes would be stamped + * with anyway: every write of that pull is a system-context insert or update + * the engine resolves through `resolveSystemWriteOrganization` (ADR-0131 D9), + * so the engine is asked that same decision up front + * ({@link SystemWriteOrganizationSource}) — never a second derivation, never a + * "first organization", never an env default. Only `derived` (the `single` + * posture, exactly one organization) changes anything: the pull then carries + * that organization, and the import runner's match lookup scopes by it — one + * index probe per row instead of a scan of the target table. + * + * Every other decision keeps today's context, `{ isSystem: true }`: under a + * wall, or with zero or several organizations, the WRITE stays the one that + * refuses, with its own located message; `no-organization-object` has nothing + * to carry. An engine that does not answer the question (an embedding's own + * engine) keeps today's context too. + * + * Not a write and not a gate: a probe that throws is said once, at `warn`, + * naming the job, and the run goes on with today's context — the writes then + * meet the same probe and answer for it. + */ +async function resolveJobPullOrganization( + ql: unknown, + declared: string | undefined, + onProbeFailure: (err: unknown) => void, +): Promise { + if (declared !== undefined) return declared; + const source = ql as Partial | null | undefined; + if (typeof source?.systemWriteOrganization !== 'function') return undefined; + let decision: SystemWriteOrganizationDecision; + try { + decision = await source.systemWriteOrganization(); + } catch (err) { + onProbeFailure(err); + return undefined; + } + return decision?.kind === 'derived' ? decision.organizationId : undefined; +} + /** * The run outcome of a pull that RESOLVED, mapped once here rather than left to * each author: rows the import runner refused make the run `degraded` — it ran @@ -721,8 +775,11 @@ export interface AppArtifactJobScheduling { * * Every form runs as {@link jobExecutionContext} of the job's organization — * the body's `ctx.api`, the handler's `executionContext`, the pull's - * `context`. Under `group`, the jobs that declare none are named once at - * `warn`: they are armed, and a tenant-scoped write they make is refused. + * `context`. A pull of a job that declares none runs as the organization its + * writes would be stamped with, where the engine derives one + * ({@link resolveJobPullOrganization}); otherwise as none. Under `group`, the + * jobs that declare none are named once at `warn`: they are armed, and a + * tenant-scoped write they make is refused. * * The schedule is lowered to the boundary tier (`toBoundaryJobSchedule`), and * the job's `retryPolicy` / `timeoutMs` are threaded to the adapter. For a body @@ -932,7 +989,15 @@ export async function scheduleAppArtifactJobs( + '`pullConnectorSource` — nothing was pulled', ); } - const result = await service.pullConnectorSource({ mapping, context: jobExecutionContext(organization) }); + // [#31823] Resolved once per run, before the pull reads or writes: + // a job with no organization pulls as the one its writes are + // stamped with, where the engine derives one. + const runAs = await resolveJobPullOrganization(ql, organization, (err) => logger.warn( + `${tag} job '${jobName}' declares no organization, and the organization its pull's writes would be ` + + 'stamped with could not be resolved — the pull runs with none, and its match lookup reads by the key alone', + { appId, job: jobName, mapping, error: err instanceof Error ? err.message : String(err) }, + )); + const result = await service.pullConnectorSource({ mapping, context: jobExecutionContext(runAs) }); return pullRunOutcomeOf(result); }; form = 'pull';