diff --git a/.changeset/33626-relation-semi-join.md b/.changeset/33626-relation-semi-join.md new file mode 100644 index 00000000000..2573be6c768 --- /dev/null +++ b/.changeset/33626-relation-semi-join.md @@ -0,0 +1,10 @@ +--- +'@objectstack/objectql': patch +'@objectstack/service-analytics': minor +--- + +feat(objectql): a nested-relation condition on a read verb is an in-database subquery per relationship, up to three relationships, where that is provably the same read as the id read; analytics serves the dataset's own `filter` the same way + +Clause-②: yes (widening) — `{ account: { status: { $ne: 'cancelled' } } }` on `find`, `findOne`, `count` and `aggregate` (and so every analytics face that hands the engine the nested form) is served whatever the number of matching related records on a driver that compiles the subquery (the SQL drivers; the in-memory driver evaluates it in process), where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller and its final `where` becomes the subquery's scope; related-object read restrictions the planned read observes are carried into the subquery, or the hop falls back to the id read (the related object read as the caller, then `$in`, under the 1,000 cap). A relation key inside the condition may now carry a condition of its own, down to ADR-0071's three relationships (`{ contact: { account: { region: { name: 'NA' } } } }`), where a second level answered `INVALID_FILTER` / 400; each hop is that object's own read, and a fourth relationship is refused by name. On the analytics engine-aggregate path a dotted `where` leaf through up to three relationships (`order.customer.tier`), and a cross-object leaf in a compiled dataset's own definition-level `filter`, reach the engine as that nested condition, where both answered `INVALID_FIELD` / 400. Still the id read, under the 1,000 cap: a related object on another datasource, a federated related object, a driver that compiles no subquery (MongoDB, OData), a related object an object-scoped middleware or an `afterFind` hook shapes, a related object read under different driver options than the outer object (decided before planning where the registry answers it: the two objects' tenancy class under a walled posture), a related read that a middleware answers itself, a multi-valued relation and the `update` / `delete` verbs. A hop that falls back after planning dispatches the related read twice: its middleware chain and `beforeFind` hooks run for the planned read and again for the id read. A per-measure `filter` carrying a cross-object leaf stays refused. The SQL echo of a dataset `filter` carrying a served cross-object leaf refuses `INVALID_FILTER` / 400 where it refused `INVALID_FIELD` / 400; neither printed a statement. +Metadata-protocol: added — a compiled dataset's definition-level `filter` (`@objectstack/service-analytics`) now accepts a cross-object leaf on the engine-aggregate path, where it answered `INVALID_FIELD` / 400: a new accepted value for a dataset author. +Skills-docs: `content/docs/protocol/objectql/query-syntax.mdx` and `content/docs/kernel/contracts/data-engine.mdx` describe the subquery, the three-relationship limit, where the id read and its cap still apply and which drivers compile the subquery. `skills/objectstack-query` still says "up to 1000 related ids" and one level for every relation; that is now stricter than the engine for a single-valued relation on a read verb (a follow-up skills-only change, governed). diff --git a/content/docs/kernel/contracts/data-engine.mdx b/content/docs/kernel/contracts/data-engine.mdx index 2ae51b1765d..fdfd6b1389c 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -193,15 +193,43 @@ multiple). The engine serves it in `where`, the same on every driver: it reads t related object with the condition **as the caller** — that object's row scope and field permissions apply, so a condition on a field the caller cannot read is refused (`PERMISSION_DENIED` / 403), never answered with an empty list — and then matches the -relation field against the ids that read returns: `$in` on a single-valued relation, any -member on a multi-valued one (`multiple: true`). No related record matching selects no +relation field against what that read selects: on a read verb, a single-valued relation is +one subquery inside the read's own statement where that is provably the same read (the +related read is planned, not run: its read scope and the condition become the subquery's +`WHERE`, so no id list is read and none is capped — the related object's read restrictions +the planned read observes are carried into the subquery, or the hop falls back to the id +read); otherwise `$in` on the +ids that read returns, any member on a multi-valued one (`multiple: true`). No related record matching selects no rows; under `$not`, a record whose relation is empty satisfies the negation. -It reaches **one level**: every key must be a field the related object declares -(`{ account: { owner: { region: 'NA' } } }` and the dotted `{ account: { 'owner.region': 'NA' } }` -are refused), and a condition matching more than 1,000 related records is refused with -`INVALID_FILTER` / 400 rather than run over a cut-off list. For either, run the two steps -yourself — filter the related object, then match its ids: +It reaches **up to three relationships** (ADR-0071's hop limit): every key must be a field +the related object declares, and a relation key may carry a condition of its own +(`{ account: { owner: { region: 'NA' } } }`), each hop read as the caller with its own read +scope; a fourth relationship and the dotted `{ account: { 'owner.region': 'NA' } }` are +refused. Where ids are read (a multi-valued relation, `update`, `delete`) a +condition matching more than 1,000 related records is refused with `INVALID_FILTER` / 400 +rather than run over a cut-off list. The id read, with that cap, is also what serves a +single-valued relation on a read verb in each of these cases: + +- a related object on another datasource; +- a federated related object; +- a driver that compiles no subquery (MongoDB, OData — the SQL drivers compile it, the + in-memory driver evaluates it in process); +- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes; +- a related object read under different driver options than the outer object (its tenant + scope, most commonly) — decided before the related read is planned where the registry + answers it (the two objects' tenancy class under a walled posture), at the executor + boundary otherwise; +- a related read that a middleware answers itself (or adds rows to after the driver call). + +A read rule that narrows a related object's rows after its driver call bounds a relation +condition on that object only when it is registered for that object — as an object-keyed +middleware or an `afterFind` hook; registered that way, the hop keeps the id read. + +A hop that falls back after planning (a middleware answering the related read, or driver +options only the request decides) dispatches the related read twice: its middleware chain and `beforeFind` hooks run for the +planned read and again for the id read. Past the cap, run the two steps yourself — filter +the related object, then match its ids: ```typescript const tech = await engine.find('account', { where: { industry: 'tech' }, fields: ['id'] }); diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index c83238522e3..795d7297bbf 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -687,25 +687,68 @@ const opportunities = await engine.find('opportunity', { A condition on a related record's fields beneath a relation field (`lookup`, `master_detail`, `user`, `tree`) is served in `where`: the engine reads the -related object with it **as the caller**, then matches the field against the -ids it returns (`$in`; any member when `multiple: true`). - -Limits — one level: every key a field the related object declares, no relation -or dotted key inside; forward only: never a parent by its children; `where` +related object with it **as the caller**. On a read verb (`find`, `findOne`, +`count`, `aggregate`) a single-valued relation is matched in the database +where that is provably the same read: the related read is planned, not run, +and the driver receives one statement with a subquery, +`account IN (SELECT id FROM account WHERE AND )` — +no id list, no cap. The related object's read restrictions the planned read +observes are carried into the subquery, or the hop falls back to reading the +related ids as the caller and matching them with `$in`, under the cap below. +Otherwise (a multi-valued +relation, or `update` / `delete`) the field is matched against the ids the +related read returns (`$in`; any member when `multiple: true`). + +Limits — up to three relationships (ADR-0071's hop limit): every key a field the +related object declares, and a relation key may hold a condition of its own on +its related object (`{ account: { owner: { region: 'NA' } } }`), each hop read as +the caller and nested as a subquery; no dotted key; forward only: never a parent by its children; `where` only: an aggregation's `filter` and `having` refuse it, `INVALID_FILTER` / 400; -at most 1000 related ids, refused past that, `INVALID_FILTER` / 400, never -truncated; as the caller: the related object's row scope and field permissions +where ids are read, at most 1000 of them, refused past that, +`INVALID_FILTER` / 400, never truncated; the subquery form is taken only on +the related object's own datasource and on a driver that compiles it — the SQL +drivers (every `driver-sql` dialect, Turso) compile it and the in-memory driver +evaluates it in process; as the caller: the related object's row scope and field permissions apply, so a field the caller cannot read is refused, `PERMISSION_DENIED` / 403, never an empty result. +A single-valued relation on a read verb keeps the id read, and its 1000-id cap, in each +of these cases: + +- a related object on another datasource; +- a federated related object; +- a driver that compiles no subquery (MongoDB, OData); +- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes; +- a related object read under different driver options than the outer object (its tenant + scope, most commonly) — decided before the related read is planned where the registry + answers it (the two objects' tenancy class under a walled posture), at the executor + boundary otherwise; +- a related read that a middleware answers itself (or adds rows to after the driver call). + +A hop that falls back after planning (a middleware answering the related read, or driver +options only the request decides) dispatches the related read twice: its middleware chain +and `beforeFind` hooks run for the planned read and again for the id read. + +A read rule that narrows a related object's rows after its driver call bounds a relation +condition on that object only when it is registered for that object — as an object-keyed +middleware or an `afterFind` hook; registered that way, the hop keeps the id read. + - **Every verb that takes a `where`** serves it — `find`, `findOne`, `count`, `aggregate`, `update` and `delete` — and so do the REST `GET /data/:object` and `POST /data/:object/query` doors, which read through the same engine calls. A - single-valued relation matches with `$in` on the related ids; a multi-valued one + single-valued relation matches with a subquery on a read verb (or with `$in` on the + related ids in the cases listed above) and with `$in` on the related ids on + `update` / `delete`; a multi-valued one (`multiple: true`) matches a record when **any** member qualifies, written as one `$contains` per id under an `$or`. -- **A second level is refused.** `{ account: { owner: { region: 'NA' } } }` and - `{ account: { 'owner.region': 'NA' } }` answer `INVALID_FILTER` / 400. +- **A related record the caller cannot read never matches**, whatever the operator: + `{ account: { status: { $ne: 'cancelled' } } }` leaves out a row whose account is + absent or hidden from the caller, as well as one whose account is cancelled. +- **Up to three relationships.** `{ account: { owner: { region: 'NA' } } }` reads + `user` as the caller, then `account` as the caller with the owner subquery inside, + and every hop carries its own object's row scope and field check; a related record + the caller cannot read at any hop excludes the row. A fourth relationship, and the + dotted `{ account: { 'owner.region': 'NA' } }`, answer `INVALID_FILTER` / 400. - **The reverse direction is not served.** A parent filtered by its children is not written as `{ opportunities: { stage: 'won' } }`: the parent has no such field, so the REST doors answer `INVALID_FIELD` / 400. diff --git a/packages/objectql/src/engine-count-aggregate.ts b/packages/objectql/src/engine-count-aggregate.ts index f004a8c16a1..d877680e163 100644 --- a/packages/objectql/src/engine-count-aggregate.ts +++ b/packages/objectql/src/engine-count-aggregate.ts @@ -154,7 +154,7 @@ export async function count( // `find()` fallback below composes at its own boundary. return driver.count( object, - await this.composeReadableIdsAtBoundary(object, 'count', opCtx.ast as QueryAST, opCtx.context), + await this.composeReadableIdsAtBoundary(object, 'count', opCtx.ast as QueryAST, opCtx.context, countOpts), countOpts, ); } diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 1a3d92ebd1a..2acaaae8813 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -1289,7 +1289,11 @@ export class DeleteAndAggregateFacet { // [ADR-0139 D2] The executor boundary, once for BOTH driver paths below // (they are exclusive, and the rows path keeps this `where` by // reference): the AST is final once the chain has run. - const ast = await this.composeReadableIdsAtBoundary(object, 'aggregate', opCtx.ast as QueryAST, opCtx.context); + // One driver-options bag for the boundary and whichever driver call + // below runs: a planned relation leaf is composed only when these + // are the related read's own (`relation-semi-join.ts`). + const aggregateOptions = this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const ast = await this.composeReadableIdsAtBoundary(object, 'aggregate', opCtx.ast as QueryAST, opCtx.context, aggregateOptions); // Prefer driver.aggregate() when available — driver.find() in many // drivers (e.g. driver-sql) does not honor `groupBy` / `aggregations` @@ -1353,7 +1357,7 @@ export class DeleteAndAggregateFacet { // natively today; one that grows native support must advertise a // capability flag, at which point this post-filter becomes the // fallback tier — the dateGranularity two-tier pattern. - const aggregated = await drv.aggregate(object, ast, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict })); + const aggregated = await drv.aggregate(object, ast, aggregateOptions); return applyHaving(aggregated, ast.having, havingColumnClasses); } // In-memory fallback path: ask the driver for raw rows, then bucket + @@ -1396,7 +1400,7 @@ export class DeleteAndAggregateFacet { delete rowsAst.groupBy; delete rowsAst.aggregations; delete rowsAst.having; - const raw = await driver.find(object, rowsAst, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict })); + const raw = await driver.find(object, rowsAst, aggregateOptions); return applyHaving(applyInMemoryAggregation(raw, ast, tz, declaredFields), ast.having, havingColumnClasses); }); diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index 4f69ddf53d5..df621b5e34f 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -318,7 +318,7 @@ export function buildDriverOptions( // federated object by — one spelling of "this schema is the remote's", // not a second reading of it. const isFederated = isFederatedObject(objectSchema); - const tenantObject = !isTenancyDisabled(objectSchema) && !isFederated; + const tenantObject = isDriverTenantScopedSchema(objectSchema); const tenantScope = tenantObject ? scope.writeTarget ? this.driverWriteTarget(execCtx) @@ -411,6 +411,17 @@ export function buildDriverOptions( return opts; } +/** + * Whether a read of an object with this schema can hand its driver a tenant + * scope at all — the object's tenancy class: neither tenancy-disabled + * (ADR-0066 platform-global posture) nor federated (ADR-0015 `external`). + * The one spelling {@link buildDriverOptions} and the relation semi-join + * (`relation-semi-join.ts`) both ask. + */ +export function isDriverTenantScopedSchema(objectSchema: unknown): boolean { + return !isTenancyDisabled(objectSchema) && !isFederatedObject(objectSchema); +} + /** * [ADR-0131 D8] The driver's native read scope for one operation — the Layer * 0 verdict projected onto `DriverOptions` (see {@link buildDriverOptions}). diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 3ff00370cb8..75d7a3483d3 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -30,8 +30,9 @@ */ import { SortNodeSchema, lowerFilterCondition, resolveSearchFieldResolution } from '@objectstack/spec/data'; -import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data'; +import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data'; import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js'; +import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; @@ -545,7 +546,18 @@ export class FindFacet { // [ADR-0139 D2] The executor boundary: the AST is final here — after the // doors, the middleware chain and `beforeFind` — so every `ReadableIds` // leaf is composed (or refused) on it, immediately before the driver. - const driverAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context); + const driverAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context, driverOptions); + // [relation semi-join] A PLANNED read (`relation-semi-join.ts`): the + // final `where` and the driver options are handed to the planner in + // place of the driver call, and the read answers the plan's own empty + // rows. Only the engine's own nested-relation lowering sets this + // symbol-keyed option. + const plan = (options as Record | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined; + if (plan !== undefined) { + plan.capture(driverAst.where as FilterCondition | undefined, driverOptions); + opCtx.result = plan.rows; + return opCtx.result; + } try { let result = await driver.find(object, driverAst, driverOptions); @@ -837,7 +849,7 @@ export class FindFacet { const driverOptions = this.buildDriverOptions(objectName, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); // [ADR-0139 D2] The executor boundary, as in `find`. - const driverAst = await this.composeReadableIdsAtBoundary(objectName, 'findOne', hookContext.input.ast as QueryAST, opCtx.context); + const driverAst = await this.composeReadableIdsAtBoundary(objectName, 'findOne', hookContext.input.ast as QueryAST, opCtx.context, driverOptions); let result = await driver.findOne(objectName, driverAst, driverOptions); diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index ea6bb834d14..c0faff56c92 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -21,6 +21,7 @@ */ import { describe, it, expect, beforeEach } from 'vitest'; +import { isComposedReadableIds, ReadableIds } from '@objectstack/spec/data'; import type { EngineAggregateOptions, EngineQueryOptions, FilterCondition } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; import { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js'; @@ -71,15 +72,17 @@ interface SeenRead { object: string; ast: any } /** * A recording driver. A read of the object named in `answers` returns those * rows (the related read's matches); every other read returns none. Writes - * are recorded, never applied. + * are recorded, never applied. It answers to `name` — by default the SQL + * driver's, one of the drivers the engine plans a semi-join for + * (`SEMI_JOIN_COMPILING_DRIVERS`); any other name keeps the id read. */ -function makeRecordingDriver() { +function makeRecordingDriver(name = 'com.objectstack.driver.sql') { const reads: SeenRead[] = []; const writes: SeenRead[] = []; const answers = new Map>>(); const rowsOf = (o: string) => answers.get(o) ?? []; const driver: any = { - name: 'recording', version: '0.0.0', supports: {}, + name, version: '0.0.0', supports: {}, async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, async find(o: string, ast: any) { reads.push({ object: o, ast }); return rowsOf(o); }, async findOne(o: string, ast: any) { reads.push({ object: o, ast }); return rowsOf(o)[0] ?? null; }, @@ -103,6 +106,18 @@ const INVALID_FILTER = { code: 'INVALID_FILTER', status: 400 }; const idRows = (...ids: string[]) => ids.map((id) => ({ id })); +/** + * `where` with every composed semi-join leaf respelled `{ SEMI_JOIN: object, + * scope }`, so a driver input can be compared with a literal (the composed + * leaf itself is branded and cannot be written by hand). + */ +const normalized = (v: any): any => { + if (isComposedReadableIds(v)) return { SEMI_JOIN: v.object, scope: normalized(v.scope) }; + if (Array.isArray(v)) return v.map(normalized); + if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, normalized(x)])); + return v; +}; + describe('[#20802] the nested-relation form is lowered at the engine\'s where seam', () => { let engine: ObjectQL; let rec: ReturnType; @@ -136,22 +151,66 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se return outer[outer.length - 1]?.ast?.where; }; - it('every single-valued relation type: the related object is read as the condition says, then $in on its ids', async () => { + it('every single-valued relation type on a read verb: the related read is PLANNED, never run, and the outer read carries one semi-join leaf scoped by it', async () => { for (const [field, , target, condition] of SINGLE) { rec.answers.clear(); rec.answers.set(target, idRows('r1', 'r3')); rec.reads.length = 0; await engine.find(OBJECT, { where: { [field]: condition } as FilterCondition }); - const related = rec.reads.filter((r) => r.object === target && r.ast?.limit === RELATION_FILTER_ID_CAP + 1); - expect(related, field).toHaveLength(1); - expect(related[0].ast.where, field).toEqual(condition); - expect(related[0].ast.fields, field).toEqual(['id']); - const outer = rec.reads[rec.reads.length - 1]; + // One driver call: the outer read. The related read reached its driver + // call and was planned, so no id list was read. + expect(rec.reads, field).toHaveLength(1); + const outer = rec.reads[0]; expect(outer.object, field).toBe(OBJECT); - expect(outer.ast.where, field).toEqual({ [field]: { $in: ['r1', 'r3'] } }); + const leaf = outer.ast.where?.[field]?.$in; + expect(isComposedReadableIds(leaf), field).toBe(true); + expect(normalized(outer.ast.where), field).toEqual({ [field]: { $in: { SEMI_JOIN: target, scope: condition } } }); } }); + it('[#33626] two and three hops: each hop is the related object\'s own planned read, so each is a semi-join leaf nested in the scope of the one above — one driver call', async () => { + const owner = (scope: unknown) => ({ SEMI_JOIN: OWNER, scope }); + const ledger = (scope: unknown) => ({ SEMI_JOIN: OBJECT, scope }); + const cases: ReadonlyArray = [ + // 2 hops: ledger.owner → owner.account → ledger.title + [{ owner: { account: { title: 'a' } } }, { owner: { $in: owner({ account: { $in: ledger({ title: 'a' }) } }) } }], + // 3 hops, a sibling key beside the inner relation at the middle hop + [ + { owner: { region: 'NA', account: { owner: { region: { $ne: 'EU' } } } } }, + // The innermost `$ne` is the shared lowering's NULL-inclusive form, as on a direct read of the owner. + { owner: { $in: owner({ region: 'NA', account: { $in: ledger({ owner: { $in: owner({ $and: [{ $or: [{ region: { $null: true } }, { region: { $ne: 'EU' } }] }] }) } }) } }) } }, + ], + // 3 hops through a tree and a master_detail field + [ + { parent: { boss: { account: { title: 'z' } } } }, + { parent: { $in: ledger({ boss: { $in: owner({ account: { $in: ledger({ title: 'z' }) } }) } }) } }, + ], + ]; + for (const [where, expected] of cases) { + rec.reads.length = 0; + await engine.find(OBJECT, { where }); + expect(rec.reads, JSON.stringify(where)).toHaveLength(1); + expect(normalized(rec.reads[0].ast.where), JSON.stringify(where)).toEqual(expected); + expect(engine.judgeFilter(OBJECT, where), JSON.stringify(where)).toEqual({ ok: true }); + } + }); + + it('[#33626] a multi-valued relation at an inner hop keeps its capped id read there; the hops above stay semi-joins', async () => { + const OWNER_WITH_MULTI = { + ...OWNER_OBJECT, + fields: { ...OWNER_OBJECT.fields, accounts: { name: 'accounts', type: 'lookup', reference: OBJECT, multiple: true } }, + }; + engine.registry.registerObject(OWNER_WITH_MULTI as any, 'test'); + rec.answers.set(OBJECT, idRows('l1')); + rec.reads.length = 0; + await engine.find(OBJECT, { where: { owner: { accounts: { title: 'a' } } } }); + // The inner id read (ledger, by title), then the outer read. + expect(rec.reads.map((r) => r.object)).toEqual([OBJECT, OBJECT]); + expect(normalized(rec.reads[1].ast.where)).toEqual({ + owner: { $in: { SEMI_JOIN: OWNER, scope: { $and: [{ $or: [{ accounts: { $contains: 'l1' } }] }] } } }, + }); + }); + it('a multi-valued relation matches on ANY member: an $or of $contains per id, the spec\'s any-of spelling', async () => { rec.answers.set(OWNER, idRows('u1', 'u3')); expect(await outerWhereOf({ owners: { region: 'NA' } })).toEqual({ @@ -163,33 +222,44 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se }); }); - it('no related record matches: $in [] / $or [] — FALSE, never an absent predicate', async () => { + it('no related record matches: an empty subquery / $or [] — FALSE, never an absent predicate', async () => { rec.answers.set(OWNER, []); - expect(await outerWhereOf({ owner: { region: 'APAC' } })).toEqual({ owner: { $in: [] } }); + // Single-valued: the subquery decides in the database — an empty one is FALSE there. + expect(normalized(await outerWhereOf({ owner: { region: 'APAC' } }))).toEqual({ + owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'APAC' } } }, + }); expect(await outerWhereOf({ owners: { region: 'APAC' } })).toEqual({ $and: [{ $or: [] }] }); }); - it('composes as written inside $and / $or / $not, and the FilterArray sugar alike — exactly the two-step route\'s driver input', async () => { + it('composes as written inside $and / $or / $not, and the FilterArray sugar alike', async () => { rec.answers.set(OWNER, idRows('u1')); - const cases: ReadonlyArray = [ - [{ $or: [{ owner: { region: 'NA' } }, { title: 'a' }] }, { $or: [{ owner: { $in: ['u1'] } }, { title: 'a' }] }], - [{ $and: [{ title: 'c' }, { boss: { region: 'NA' } }] }, { $and: [{ title: 'c' }, { boss: { $in: ['u1'] } }] }], - [{ title: 'c', owner: { region: 'NA' } }, { title: 'c', owner: { $in: ['u1'] } }], - // `$not`: the lowered leaf takes the shared lowering's NULL-safe negation, - // so a row whose relation is empty satisfies it — the two-step route's reading. - [{ $not: { owner: { region: 'NA' } } }, { $not: { owner: { $in: ['u1'] } } }], - [{ $not: { owners: { region: 'NA' } } }, { $not: { $and: [{ $or: [{ owners: { $contains: 'u1' } }] }] } }], - [[['owner', '=', { region: 'NA' }]], { owner: { $in: ['u1'] } }], + const NA = { SEMI_JOIN: OWNER, scope: { region: 'NA' } }; + const cases: ReadonlyArray = [ + [{ $or: [{ owner: { region: 'NA' } }, { title: 'a' }] }, { $or: [{ owner: { $in: NA } }, { title: 'a' }] }], + [{ $and: [{ title: 'c' }, { boss: { region: 'NA' } }] }, { $and: [{ title: 'c' }, { boss: { $in: NA } }] }], + [{ title: 'c', owner: { region: 'NA' } }, { title: 'c', owner: { $in: NA } }], + [[['owner', '=', { region: 'NA' }]], { owner: { $in: NA } }], ]; - for (const [nested, twoStep] of cases) { - const reference = await twoStepWhereOf(twoStep); - expect(await outerWhereOf(nested), JSON.stringify(nested)).toEqual(reference); + for (const [nested, expected] of cases) { + expect(normalized(await outerWhereOf(nested)), JSON.stringify(nested)).toEqual(expected); } + // `$not` over a single-valued relation: the shared lowering's NULL-safe + // negation applies to the semi-join leaf exactly as it does to a list — + // the same driver input as the hand-written `$not` over a ReadableIds leaf. + const negated = normalized(await outerWhereOf({ $not: { owner: { region: 'NA' } } })); + expect(JSON.stringify(negated)).toContain('"SEMI_JOIN":"nested_rel_owner"'); + // A multi-valued relation keeps the id route. + const reference = await twoStepWhereOf({ $not: { $and: [{ $or: [{ owners: { $contains: 'u1' } }] }] } }); + expect(await outerWhereOf({ $not: { owners: { region: 'NA' } } })).toEqual(reference); }); it('covers every verb that takes a where — the driver never receives the nested form — and the judge admits it', async () => { rec.answers.set(OWNER, idRows('u1')); const where = { owner: { region: 'NA' } } as FilterCondition; + // Read verbs: the semi-join leaf. Write verbs (`update`, `delete`) keep + // the id read — their `where` never reaches the executor boundary that + // composes the leaf. + const semiJoin = { owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } } }; const lowered = { owner: { $in: ['u1'] } }; for (const [verb, call] of [ ['find', () => engine.find(OBJECT, { where })], @@ -201,7 +271,7 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se await call(); const outer = rec.reads.filter((r) => r.object === OBJECT); expect(outer.length, verb).toBeGreaterThan(0); - for (const read of outer) expect(read.ast.where, verb).toEqual(lowered); + for (const read of outer) expect(normalized(read.ast.where), verb).toEqual(semiJoin); } rec.writes.length = 0; await engine.update(OBJECT, { title: 'x' }, { where, multi: true }); @@ -222,12 +292,12 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se expect(engine.judgeFilter(OBJECT, { owners: { region: 'NA' } })).toEqual({ ok: true }); }); - it('placeholders in the condition resolve against the caller before the related read', async () => { + it('placeholders in the condition resolve against the caller before the related read is planned', async () => { rec.answers.set(OWNER, idRows('u9')); rec.reads.length = 0; await engine.find(OBJECT, { where: { owner: { id: '{current_user_id}' } }, context: { userId: 'u9' } } as EngineQueryOptions); - const related = rec.reads.find((r) => r.object === OWNER); - expect(related?.ast.where).toEqual({ id: 'u9' }); + expect(rec.reads.find((r) => r.object === OWNER), 'no related read ran').toBeUndefined(); + expect(normalized(rec.reads[0]?.ast.where)).toEqual({ owner: { $in: { SEMI_JOIN: OWNER, scope: { id: 'u9' } } } }); }); it('the related read runs AS THE CALLER, through the middleware chain, and its refusal is the answer — loudly, no outer read', async () => { @@ -264,34 +334,34 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se // ── the cap ────────────────────────────────────────────────────────────── - it('the cap: past it the filter is REFUSED with the two-step route, never run over a cut-off list; at it, served whole', async () => { + it('the cap: a single-valued relation on a read verb has none (the semi-join reads no id list); a multi-valued one and a write verb are REFUSED past it, never run over a cut-off list', async () => { const many = (n: number) => Array.from({ length: n }, (_, i) => ({ id: `u${i}` })); rec.answers.set(OWNER, many(RELATION_FILTER_ID_CAP + 1)); - rec.reads.length = 0; - const err = await refusalOf(engine.find(OBJECT, { where: { owner: { region: 'NA' } } })); - expect(envelopeOf(err)).toEqual(INVALID_FILTER); - expect(err!.message).toMatch(/^find\('nested_rel_ledger'\): /); - expect(err!.message).toContain(`matched more than ${RELATION_FILTER_ID_CAP} records of the related object '${OWNER}'`); - expect(err!.message).toContain('the filter was NOT applied: a cut-off id list would silently drop matching rows'); - expect(err!.message).toContain('{ "owner": { "$in": [ID, …] } }'); - expect(rec.reads.filter((r) => r.object === OBJECT), 'no outer read').toHaveLength(0); + expect(normalized(await outerWhereOf({ owner: { region: 'NA' } }))).toEqual({ + owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } }, + }); + rec.reads.length = 0; const multi = await refusalOf(engine.find(OBJECT, { where: { owners: { region: 'NA' } } })); expect(envelopeOf(multi)).toEqual(INVALID_FILTER); + expect(multi!.message).toMatch(/^find\('nested_rel_ledger'\): /); + expect(multi!.message).toContain(`matched more than ${RELATION_FILTER_ID_CAP} records of the related object '${OWNER}'`); expect(multi!.message).toContain('{ "owners": { "$contains": ID } }'); + expect(rec.reads.filter((r) => r.object === OBJECT), 'no outer read').toHaveLength(0); - rec.answers.set(OWNER, many(RELATION_FILTER_ID_CAP)); - const where = await outerWhereOf({ owner: { region: 'NA' } }); - expect((where as any).owner.$in).toHaveLength(RELATION_FILTER_ID_CAP); + const write = await refusalOf(engine.update(OBJECT, { title: 'x' }, { where: { owner: { region: 'NA' } }, multi: true })); + expect(envelopeOf(write)).toEqual(INVALID_FILTER); + expect(write!.message).toContain('{ "owner": { "$in": [ID, …] } }'); }); // ── what the first cut keeps refusing ──────────────────────────────────── - it('keeps refusing, in the engine\'s words and before any read: a second level, a dotted key, an undeclared key, {}, an unregistered related object', async () => { + it('keeps refusing, in the engine\'s words and before any read: a fourth hop, a dotted key, an undeclared key at any hop, {}, an unregistered related object', async () => { const cases: ReadonlyArray = [ - [{ parent: { owner: { region: 'NA' } } }, 'where.parent', "'owner' is itself a lookup field of the related object 'nested_rel_ledger'"], - [{ owner: { account: { title: 'a' } } }, 'where.owner', "'account' is itself a lookup field of the related object 'nested_rel_owner'"], - [{ owner: { 'account.title': 'a' } }, 'where.owner', "'account.title' is a dotted path: the condition reaches one level only"], + [{ owner: { account: { owner: { account: { title: 'a' } } } } }, 'where.owner.account.owner', "'account' holds a condition of its own past the 3-relationship limit"], + [{ parent: { parent: { owner: { account: { title: 'a' } } } } }, 'where.parent.parent.owner', "'account' is itself a lookup field of the related object 'nested_rel_owner'"], + [{ owner: { account: { titel: 'a' } } }, 'where.owner.account', "'titel' is not a field of the related object 'nested_rel_ledger'"], + [{ owner: { 'account.title': 'a' } }, 'where.owner', "'account.title' is a dotted path: nest each relation instead"], [{ owner: { regio: 'NA' } }, 'where.owner', "'regio' is not a field of the related object 'nested_rel_owner'"], [{ owner: {} }, 'where.owner', 'names no field of the related object'], [{ stray: { region: 'NA' } }, 'where.stray', "no object 'nested_rel_missing' is registered here"], @@ -371,3 +441,257 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se } }); }); + +/** + * The semi-join is taken ONLY where it is provably the same read as the id + * read (`relation-semi-join.ts`); every other case keeps that id read — the + * related object read as the caller, `id` only, one row past the cap, then + * `$in` — exactly as before the semi-join existed. Each case below asserts + * the related read RAN (it is in the driver's reads) and the outer read + * carries the id list, never a composed leaf, and is served, never refused. + */ +describe('[#33626] the semi-join falls back to the id read wherever it is not provably that read', () => { + const OUTER_REF = { owner: { $in: ['u1'] } }; + + async function makeEngine(driverName?: string) { + const rec = makeRecordingDriver(driverName); + const engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + engine.registry.registerObject(OWNER_OBJECT as any, 'test'); + engine.registry.registerObject(LEDGER as any, 'test'); + return { engine, rec }; + } + + /** The related read and the outer read the driver saw for `{ owner: { region: 'NA' } }`. */ + async function readsOf(engine: ObjectQL, rec: ReturnType, context?: any) { + rec.reads.length = 0; + await engine.find(OBJECT, { where: { owner: { region: 'NA' } }, ...(context ? { context } : {}) } as EngineQueryOptions); + const related = rec.reads.filter((r) => r.object === OWNER); + const outer = rec.reads.filter((r) => r.object === OBJECT); + return { related, outerWhere: outer[outer.length - 1]?.ast?.where }; + } + + function expectIdRead(r: { related: SeenRead[]; outerWhere: unknown }, ids: unknown[], name: string) { + expect(r.related, name).toHaveLength(1); + expect(r.related[0].ast.where, name).toEqual({ region: 'NA' }); + expect(r.related[0].ast.limit, name).toBe(RELATION_FILTER_ID_CAP + 1); + expect(normalized(r.outerWhere), name).toEqual({ owner: { $in: ids } }); + } + + it('a driver that compiles no subquery (MongoDB, OData, any unnamed driver) keeps the capped id read', async () => { + for (const name of ['com.objectstack.driver.mongodb', 'com.objectstack.driver.odata', 'recording']) { + const { engine, rec } = await makeEngine(name); + rec.answers.set(OWNER, idRows('u1')); + expectIdRead(await readsOf(engine, rec), ['u1'], name); + // …and past the cap it is refused as it always was, never run over a cut-off list. + rec.answers.set(OWNER, Array.from({ length: RELATION_FILTER_ID_CAP + 1 }, (_, i) => ({ id: `u${i}` }))); + expect(envelopeOf(await refusalOf(engine.find(OBJECT, { where: { owner: { region: 'NA' } } }))), name).toEqual(INVALID_FILTER); + } + }); + + it('CONTROL a compiling driver plans the read: no id read, one composed leaf', async () => { + const { engine, rec } = await makeEngine(); + rec.answers.set(OWNER, idRows('u1')); + const r = await readsOf(engine, rec); + expect(r.related).toHaveLength(0); + expect(normalized(r.outerWhere)).toEqual({ owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } } }); + }); + + it('a related object an object-keyed middleware narrows keeps the id read — that middleware runs on it, and the read is served', async () => { + const { engine, rec } = await makeEngine(); + rec.answers.set(OWNER, idRows('u1', 'u2')); + // Narrows AFTER the driver call: no planned `where` could carry it. + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + await next(); + if (Array.isArray(opCtx.result)) opCtx.result = opCtx.result.filter((row: any) => row.id === 'u1'); + }, { object: OWNER }); + expectIdRead(await readsOf(engine, rec), ['u1'], 'object-keyed middleware'); + }); + + it('a read rule the related object applies after its driver call (an afterFind hook) gives the id read\'s answer', async () => { + const { engine, rec } = await makeEngine(); + rec.answers.set(OWNER, idRows('u1', 'u2')); + engine.registerHook('afterFind', async (ctx: any) => { + ctx.result = (ctx.result as any[]).filter((row) => row.id === 'u1'); + }, { object: OWNER }); + expectIdRead(await readsOf(engine, rec), ['u1'], 'afterFind'); + // The same answer as the hand-written two-step route over those ids. + expect(normalized((await readsOf(engine, rec)).outerWhere)).toEqual(OUTER_REF); + }); + + it('a global middleware that answers the related read without its driver, or adds rows after it, keeps the id read; one that reshapes the rows does not', async () => { + { + // CONTROL the field mask's shape: every row mapped to a copy — no id changes, the read is still planned. + const { engine, rec } = await makeEngine(); + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + await next(); + if (Array.isArray(opCtx.result)) opCtx.result = opCtx.result.map((row: any) => ({ ...row })); + }); + const r = await readsOf(engine, rec); + expect(r.related).toHaveLength(0); + expect(normalized(r.outerWhere)).toEqual({ owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } } }); + } + for (const mode of ['short-circuit', 'replace'] as const) { + const { engine, rec } = await makeEngine(); + rec.answers.set(OWNER, idRows('u2')); + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object !== OWNER) return next(); + if (mode === 'short-circuit') { opCtx.result = [{ id: 'u9' }]; return; } + await next(); + opCtx.result = [...(opCtx.result as any[]), { id: 'u9' }]; + }); + const r = await readsOf(engine, rec); + const related = rec.reads.filter((x) => x.object === OWNER); + expect(related, mode).toHaveLength(mode === 'short-circuit' ? 0 : 1); + expect(normalized(r.outerWhere), mode).toEqual({ owner: { $in: mode === 'short-circuit' ? ['u9'] : ['u2', 'u9'] } }); + } + }); + + it('a related object on another datasource keeps the id read on its own driver — served, no 400', async () => { + const rec = makeRecordingDriver(); + const far = makeRecordingDriver('far'); + const engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + engine.registerDriver(far.driver); + await engine.init(); + engine.registry.registerObject({ ...OWNER_OBJECT, datasource: 'far' } as any, 'test'); + engine.registry.registerObject(LEDGER as any, 'test'); + far.answers.set(OWNER, idRows('u1')); + rec.reads.length = 0; + await engine.find(OBJECT, { where: { owner: { region: 'NA' } } }); + expect(far.reads.map((r) => [r.object, r.ast.where, r.ast.limit])).toEqual([[OWNER, { region: 'NA' }, RELATION_FILTER_ID_CAP + 1]]); + expect(normalized(rec.reads[rec.reads.length - 1].ast.where)).toEqual(OUTER_REF); + }); + + it('a federated related object keeps the id read, decided before planning: the related read is dispatched once', async () => { + const { engine, rec } = await makeEngine(); + // ADR-0015 `external`, on the read's own datasource and driver. + engine.registry.registerObject({ ...OWNER_OBJECT, external: { remoteName: 'owners' } } as any, 'test'); + const dispatched = countRelatedDispatch(engine); + rec.answers.set(OWNER, idRows('u1')); + expectIdRead(await readsOf(engine, rec), ['u1'], 'federated related object'); + expect(dispatched).toEqual({ middleware: 1, beforeFind: 1 }); + }); + + /** + * Counts the related object's dispatches: a GLOBAL middleware (an + * object-keyed one would itself keep the id read) and a `beforeFind` hook, + * each counting only the related object's reads. + */ + function countRelatedDispatch(engine: ObjectQL) { + const n = { middleware: 0, beforeFind: 0 }; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object === OWNER && opCtx.operation === 'find') n.middleware += 1; + return next(); + }); + engine.registerHook('beforeFind', async () => { n.beforeFind += 1; }, { object: OWNER }); + return n; + } + + /** Records the `tenantId` each driver read was handed. */ + function recordTenantIds(rec: ReturnType) { + const seen: Array<{ object: string; tenantId: unknown }> = []; + const find = rec.driver.find; + rec.driver.find = async (o: string, ast: any, options: any) => { seen.push({ object: o, tenantId: options?.tenantId }); return find.call(rec.driver, o, ast); }; + return seen; + } + + for (const [direction, ledger, owner, expected] of [ + // The ledger is no tenant's; the owner is tenant-scoped. Under a wall the + // owner's read carries `tenantId`, the ledger's does not. + ['the read\'s object is platform-global, the related object tenant-scoped', { ...LEDGER, tenancy: { enabled: false } }, OWNER_OBJECT, + [{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]], + // The opposite: the ledger is tenant-scoped, the owner platform-global. + ['the read\'s object is tenant-scoped, the related object platform-global', LEDGER, { ...OWNER_OBJECT, tenancy: { enabled: false } }, + [{ object: OWNER, tenantId: undefined }, { object: OBJECT, tenantId: 'org_b' }]], + ] as const) { + it(`another tenancy class under a walled posture (${direction}): driver options differ → id read, decided before planning — the related read is dispatched once`, async () => { + const { engine, rec } = await makeEngine(); + engine.registry.registerObject(ledger as any, 'test'); + engine.registry.registerObject(owner as any, 'test'); + engine.setTenancyPostureProvider(() => 'isolated'); + const seen = recordTenantIds(rec); + const dispatched = countRelatedDispatch(engine); + rec.answers.set(OWNER, idRows('u1')); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expectIdRead(r, ['u1'], direction); + expect(seen, direction).toEqual(expected); + expect(dispatched, direction).toEqual({ middleware: 1, beforeFind: 1 }); + }); + } + + it('CONTROL a planned hop dispatches the related read once, and the driver is never asked', async () => { + const { engine, rec } = await makeEngine(); + const dispatched = countRelatedDispatch(engine); + const r = await readsOf(engine, rec); + expect(r.related).toHaveLength(0); + expect(dispatched).toEqual({ middleware: 1, beforeFind: 1 }); + }); + + it('driver options that differ only by a per-object verdict the request records: the ids are read at the executor boundary — a fallback after planning, which dispatches the related read twice', async () => { + const { engine, rec } = await makeEngine(); + engine.setTenancyPostureProvider(() => 'isolated'); + // Both objects tenant-scoped (the registry cannot tell them apart); the + // recorded verdict lifts the scope on the ledger's read only. + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + opCtx.tenantLayer0Verdict = opCtx.object === OBJECT ? { kind: 'none' } : { kind: 'organization', organizationId: 'org_b' }; + return next(); + }); + const seen = recordTenantIds(rec); + const dispatched = countRelatedDispatch(engine); + rec.answers.set(OWNER, idRows('u1')); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expectIdRead(r, ['u1'], 'boundary fallback'); + expect(seen).toEqual([{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]); + expect(dispatched).toEqual({ middleware: 2, beforeFind: 2 }); + }); + + it('a related read a middleware answers itself falls back after planning, which dispatches the related read twice', async () => { + const { engine, rec } = await makeEngine(); + const dispatched = countRelatedDispatch(engine); + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object !== OWNER) return next(); + opCtx.result = [{ id: 'u9' }]; + }); + const r = await readsOf(engine, rec); + expect(normalized(r.outerWhere)).toEqual({ owner: { $in: ['u9'] } }); + // The answering middleware stops both dispatches before `beforeFind`. + expect(dispatched).toEqual({ middleware: 2, beforeFind: 0 }); + }); + + it('CONTROL without a wall (the single posture) two tenancy classes read under the same options, and the leaf is composed', async () => { + const { engine, rec } = await makeEngine(); + engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); + engine.setTenancyPostureProvider(() => 'single'); + const dispatched = countRelatedDispatch(engine); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expect(r.related).toHaveLength(0); + expect(normalized(r.outerWhere)).toEqual({ owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } } }); + expect(dispatched).toEqual({ middleware: 1, beforeFind: 1 }); + }); + + it('a read whose leaves are all planned does not report, nor spend, the once-only "no usable security service" warning', async () => { + const { engine, rec } = await makeEngine(); + const warned: string[] = []; + const logger = (engine as any).logger; + const warn = logger.warn.bind(logger); + logger.warn = (msg: unknown, ...rest: unknown[]) => { warned.push(String(msg)); return warn(msg, ...rest); }; + const noService = (w: string[]) => w.filter((m) => m.includes('no usable "security" service')); + await readsOf(engine, rec); + expect(noService(warned)).toEqual([]); + // CONTROL an ordinary ADR-0139 leaf asks the service, and so reports its absence — once. + await engine.find(OBJECT, { where: { owner: { $in: ReadableIds.of(OWNER) } } }); + await engine.find(OBJECT, { where: { owner: { $in: ReadableIds.of(OWNER) } } }); + expect(noService(warned)).toHaveLength(1); + }); + + it('CONTROL the same wall on both objects: the options are the related read\'s own, and the leaf is composed', async () => { + const { engine, rec } = await makeEngine(); + engine.setTenancyPostureProvider(() => 'isolated'); + rec.answers.set(OWNER, idRows('u1')); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expect(r.related).toHaveLength(0); + expect(JSON.stringify(normalized(r.outerWhere))).toContain(`"SEMI_JOIN":"${OWNER}"`); + }); +}); diff --git a/packages/objectql/src/engine-query-lowering.ts b/packages/objectql/src/engine-query-lowering.ts index 9ca33694539..89113c3f199 100644 --- a/packages/objectql/src/engine-query-lowering.ts +++ b/packages/objectql/src/engine-query-lowering.ts @@ -71,6 +71,8 @@ import { relationFilterCapError, type RelationReplacement, } from './relation-filter-lowering.js'; +import { planRelationSemiJoinLeaf, RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; +import type { EngineReadOptions } from './engine-top-level.js'; import { aggregatedRowColumnClasses } from './having-filter.js'; import { relationSitesOf, resolveThenLowerWhere, SECURITY_SERVICE_SOURCE_SLOT } from './engine.js'; import type { ObjectQL } from './engine.js'; @@ -90,6 +92,8 @@ export interface QueryLoweringHost { readonly [SECURITY_SERVICE_SOURCE_SLOT]: unknown; resolveRelateThenLowerWhere: ObjectQL['resolveRelateThenLowerWhere']; find: ObjectQL['find']; + /** `relation-semi-join.ts`'s `relationSemiJoinServes`, bound to the engine. */ + relationSemiJoinServes: (object: string, target: string) => boolean; } /** @@ -173,7 +177,14 @@ export async function resolveWhereTokens( * doors judge the condition's comparands against its own declarations. A * refusal from any of them is the answer, loudly; nothing is swallowed. * - * **Bounded.** The read asks for one id more than + * **A subquery only where it is provably the same read; the id read + * everywhere else.** On a read verb a single-valued relation's related read + * may be PLANNED, not run, and its final `where` becomes the scope of a + * `ReadableIds` leaf the driver compiles into one nested subquery — no id + * list, no cap — only where that subquery is provably the related read's own + * statement (`relation-semi-join.ts` names the conditions). In every other + * case — a multi-valued relation, a write verb's `where`, and each fallback + * that module names — the ids are read: the read asks for one id more than * {@link RELATION_FILTER_ID_CAP}; receiving it, the filter is refused * (`INVALID_FILTER` / 400, the two-step route in the words), never run over * a cut-off list. @@ -181,8 +192,16 @@ export async function resolveWhereTokens( * Returns `where` by reference when it holds no condition — the common path * reads nothing and allocates nothing beyond one walk. */ +/** + * The verbs whose `where` reaches the engine's executor boundary, where a + * `ReadableIds` leaf is composed (ADR-0139 D2): a single-valued relation + * condition is served as a semi-join there. A write verb's `where` + * (`update`, `delete`) keeps the id read, under the cap. + */ +const SEMI_JOIN_READ_VERBS: ReadonlySet = new Set(['find', 'findOne', 'count', 'aggregate']); + export async function lowerRelationConditions( - this: Pick, + this: Pick, object: string, operation: string, where: W, @@ -194,7 +213,9 @@ export async function lowerRelationConditions( if (sites.length === 0) return where; const context = `${operation}('${object}')`; const replacements: RelationReplacement[] = []; - for (const site of sites) { + // The id read the engine has always run for a relation condition: the + // related object read as the caller, `id` only, one id past the cap. + const readIds = async (site: (typeof sites)[number]): Promise => { const rows = await this.find(site.target, { where: site.condition as FilterCondition, fields: ['id'], @@ -205,10 +226,40 @@ export async function lowerRelationConditions( if (matched.length > RELATION_FILTER_ID_CAP) { throw relationFilterCapError(site, context, RELATION_FILTER_ID_CAP); } - replacements.push(lowerRelationSite( - site, - matched.map((row) => (row as { id?: unknown } | null)?.id).filter((id) => id !== undefined && id !== null), - )); + return matched.map((row) => (row as { id?: unknown } | null)?.id).filter((id) => id !== undefined && id !== null); + }; + for (const site of sites) { + if (!site.multiple && SEMI_JOIN_READ_VERBS.has(operation) && this.relationSemiJoinServes(object, site.target)) { + // [relation semi-join] The SAME read as the id read below — same + // object, condition, projection, limit and context — PLANNED: stopped + // at its driver call, its final `where` and driver options captured + // (`relation-semi-join.ts`). `null` when it is not provably that read: + // the ids are read below instead. + const leaf = await planRelationSemiJoinLeaf( + site.target, + (plan: RelationScopePlan) => this.find( + site.target, + { + where: site.condition as FilterCondition, + fields: ['id'], + limit: RELATION_FILTER_ID_CAP + 1, + ...(execCtx ? { context: execCtx } : {}), + }, + { [RELATION_SCOPE_PLAN]: plan } as EngineReadOptions, + ), + () => readIds(site), + ); + if (leaf !== null) { + replacements.push({ kind: 'value', value: { $in: leaf } }); + continue; + } + } + // A multi-valued relation (a JSON list column) has no `IN` membership + // test on the SQL family, a write verb's `where` reaches no executor + // boundary, and every case the semi-join is not provably the same read: + // the condition is matched against the ids the related read returns, + // under the cap. + replacements.push(lowerRelationSite(site, await readIds(site))); } let next = 0; return mapRelationConditions(object, operation, schema, where, { diff --git a/packages/objectql/src/engine-readable-ids-nested-composition.test.ts b/packages/objectql/src/engine-readable-ids-nested-composition.test.ts index b7ba69fb66f..4926dfe131f 100644 --- a/packages/objectql/src/engine-readable-ids-nested-composition.test.ts +++ b/packages/objectql/src/engine-readable-ids-nested-composition.test.ts @@ -532,6 +532,29 @@ describe('[#33696 ruling 6893666857] the required master\'s leaf over an unrestr } }); + it('a condition the caller writes on the required master, in the same read, is never dropped with the master\'s own leaf', async () => { + // A driver the nested-relation lowering plans a subquery for: the + // caller's `{ opp: { name: 'x' } }` becomes a leaf over the same master. + const rec = makeRecordingDriver('com.objectstack.driver.sql'); + const planned = new ObjectQL(); + planned.registerDriver(rec.driver, true); + await planned.init(); + for (const def of [ACCOUNT, OPP, LINE]) planned.registry.registerObject(def as any, 'test'); + const { svc } = chain(undefined); + wire(planned, () => svc); + rec.calls.length = 0; + await planned.find('rid_r4_line', { where: { $and: [leafOn('opp', 'rid_r4_opp'), { opp: { name: 'x' } }] }, context: { userId: 'u1' } as any }); + // One driver call: the related read was planned, not run. + expect(rec.calls.map((c) => c.verb)).toEqual(['find']); + const where = rec.calls[0].ast.where; + // The master's own leaf is dropped for this View All reader; the caller's condition stays, as its subquery. + expect(where.$and).toHaveLength(1); + const leaf = where.$and[0].opp.$in; + expect(isComposedReadableIds(leaf)).toBe(true); + expect(leaf.object).toBe('rid_r4_opp'); + expect(leaf.scope).toEqual({ name: 'x' }); + }); + it('a master the caller may not read keeps the leaf, answered `$in: []`', async () => { const { svc } = makeSecurity({ canRead: (object) => object !== 'rid_r4_opp' }); wire(engine, () => svc); diff --git a/packages/objectql/src/engine-readable-ids-permission-formula.ts b/packages/objectql/src/engine-readable-ids-permission-formula.ts index 5b11fe55225..4bf1bd361dc 100644 --- a/packages/objectql/src/engine-readable-ids-permission-formula.ts +++ b/packages/objectql/src/engine-readable-ids-permission-formula.ts @@ -71,6 +71,7 @@ */ import { AsyncLocalStorage } from 'node:async_hooks'; +import { isPlannedRelationLeaf, plannedRelationLeafVerdict } from './relation-semi-join.js'; import { ReadableIds, RLS_DENY_FILTER, controlledByParentMasterOf, filterSubtreeProvenanceOf, isReadableIds, markFilterSubtreeProvenance } from '@objectstack/spec/data'; import type { FilterCondition } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -188,7 +189,15 @@ export async function composeReadableIdsChain( ): Promise { const { object, operation } = chain; const parents = this.refuseUncomposableReadableIdsClasses(object, operation, sites); + // [relation semi-join] A leaf the nested-relation lowering built carries its + // own planned scope (`relation-semi-join.ts`): the related object's read was + // already run through its whole pipeline as the caller, so the security + // service is not asked about a parent only such leaves name. + const askedParents = new Set( + sites.filter((s) => !isPlannedRelationLeaf(s.leaf)).map((s) => s.leaf.object), + ); for (const parent of parents) { + if (!askedParents.has(parent)) continue; if (chain.answers.has(parent)) continue; const site = sites.find((s) => s.leaf.object === parent)!; const branch = [object, ...ancestors, parent]; @@ -231,19 +240,38 @@ export async function composeReadableIdsChain( chain.answers.set(parent, { scope: isEmptyCondition(composed) ? undefined : composed }); } // [#33696] Step 5: the required master's leaf over an unrestricted master, - // for a reader who holds View All on the object this node scopes. + // for a reader who holds View All on the object this node scopes. A leaf + // the nested-relation lowering planned is the caller's own condition on the + // master, never the master's read scope, so it is never dropped here. const scoped = ancestors.length === 0 ? object : ancestors[ancestors.length - 1]!; const master = requiredControlledByParentMasterOf(this._registry.getObject(scoped)); const vacuous = (leaf: ReadableIds): boolean => { + if (isPlannedRelationLeaf(leaf)) return false; const answer = chain.answers.get(leaf.object); return leaf.object === master?.master && answer != null && answer.scope === undefined; }; const pruned = master && sites.some((site) => vacuous(site.leaf)) && await readerViewsAllOf(chain, scoped) ? unrestrictedRequiredMasterLeavesDropped(node, master, vacuous) : node; + // [relation semi-join] A planned leaf whose read's driver options are not + // the related read's own is answered by the id read, as the caller, under + // the cap — read here, once per leaf that survived the step above, before + // the synchronous rewrite. + const surviving = new Set(); + if (pruned !== node) composeReadableIdsLeaves(pruned, (leaf) => { surviving.add(leaf); return []; }); + const readIdsFor = new Map(); + for (const s of sites) { + if (pruned !== node && !surviving.has(s.leaf)) continue; + const verdict = plannedRelationLeafVerdict(s.leaf, chain.driverOptions); + if (verdict?.kind === 'read' && !readIdsFor.has(s.leaf)) readIdsFor.set(s.leaf, [...await verdict.readIds()]); + } // A parent with no answer (`null`, or never asked: not registered) is // `$in: []`. return composeReadableIdsLeaves(pruned, (leaf) => { + const ids = readIdsFor.get(leaf); + if (ids !== undefined) return ids; + const planned = plannedRelationLeafVerdict(leaf, chain.driverOptions); + if (planned !== undefined) return planned.kind === 'compose' ? ReadableIds.compose(leaf, planned.scope) : []; const answer = chain.answers.get(leaf.object); return answer ? ReadableIds.compose(leaf, answer.scope) : []; }); diff --git a/packages/objectql/src/engine-security-resolvers.ts b/packages/objectql/src/engine-security-resolvers.ts index 02fe55e7693..c66a13d2d3e 100644 --- a/packages/objectql/src/engine-security-resolvers.ts +++ b/packages/objectql/src/engine-security-resolvers.ts @@ -35,6 +35,7 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ +import { isPlannedRelationLeaf } from './relation-semi-join.js'; import { referenceTargetOf } from '@objectstack/spec/data'; import type { EngineQueryOptions, QueryAST } from '@objectstack/spec/data'; import { collectComposableReadableIds, describeReadableIdsLeaf, readableIdsRefusalError } from './filter-comparand-shape.js'; @@ -220,7 +221,7 @@ export class SecurityResolversFacet { * aggregations' own filters are judged here too, so a leaf a middleware * wrote there is refused rather than evaluated in memory. */ - static async composeReadableIdsAtBoundary(this: Pick, object: string, operation: 'find' | 'findOne' | 'count' | 'aggregate', ast: A, context: ExecutionContext | undefined): Promise { + static async composeReadableIdsAtBoundary(this: Pick, object: string, operation: 'find' | 'findOne' | 'count' | 'aggregate', ast: A, context: ExecutionContext | undefined, driverOptions?: unknown): Promise { if (operation === 'aggregate') { collectComposableReadableIds(object, operation, ast.having, 'having'); const aggregations = Array.isArray(ast.aggregations) ? ast.aggregations : []; @@ -232,7 +233,11 @@ export class SecurityResolversFacet { if (sites.length === 0) return ast; const security = this.resolveReadableIdsSecurity(); - if (security.kind !== 'usable' && !this.readableIdsSecurityReported.has(security.kind)) { + // A planned relation leaf asks the security service nothing + // (`relation-semi-join.ts`): a read whose leaves are all planned neither + // reports the missing service nor spends the once-only report. + const asksSecurity = sites.some((site) => !isPlannedRelationLeaf(site.leaf)); + if (asksSecurity && security.kind !== 'usable' && !this.readableIdsSecurityReported.has(security.kind)) { this.readableIdsSecurityReported.add(security.kind); this.logger.warn( `[ObjectQL] ${operation}('${object}') composes a ReadableIds leaf with no usable "security" service ` + @@ -241,7 +246,7 @@ export class SecurityResolversFacet { 'Reported once for this engine; later leaves are answered the same way.', ); } - const chain: ReadableIdsChain = { object, operation, security, context, answers: new Map() }; + const chain: ReadableIdsChain = { object, operation, security, context, answers: new Map(), driverOptions }; const where = await this.composeReadableIdsChain(chain, ast.where, sites, []); return { ...ast, where }; } diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 6d0821fe358..cce21abf515 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -5110,6 +5110,12 @@ export interface ReadableIdsChain { readonly security: ReadableIdsSecurityResolution; readonly context: ExecutionContext | undefined; readonly answers: Map; + /** + * The driver options the read's driver call is handed — what a planned + * relation leaf's own options are compared with (`relation-semi-join.ts`); + * `undefined` is a bag with no keys. Every executor boundary passes them. + */ + readonly driverOptions?: unknown; } /** diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 7bbfc0ea205..09ba891d867 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -51,6 +51,7 @@ import { negotiatedMessageLocale, objectDisplayLabel, validationMessageContext } // [#25522 cut 2] The datasource-routing bodies; the methods of the same names // below hand each body the members it reads (`DatasourceRoutingHost`). import { getDriver, matchPattern, resolveDatasourceFromMapping } from './engine-datasource-routing.js'; +import { relationSemiJoinServes } from './relation-semi-join.js'; // [#25522 cut 3] The lifecycle health bodies; the methods of the same names // below hand each body the members it reads (`LifecycleHealthHost`). import { checkDriversHealth, resolvePrimaryDatasource } from './engine-lifecycle-health.js'; @@ -1544,9 +1545,10 @@ export class ObjectQL implements IObjectQLEngine { operation: 'find' | 'findOne' | 'count' | 'aggregate', ast: A, context: ExecutionContext | undefined, + driverOptions?: unknown, ): Promise { // [#29986 codemod] The body moved to `engine-security-resolvers.ts`, its docblock with it (see `SecurityResolversHost`). - return (SecurityResolversFacet.composeReadableIdsAtBoundary).call(securityResolversHost.of(this), object, operation, ast, context); + return (SecurityResolversFacet.composeReadableIdsAtBoundary).call(securityResolversHost.of(this), object, operation, ast, context, driverOptions); } private async composeReadableIdsChain( @@ -4266,10 +4268,23 @@ export class ObjectQL implements IObjectQLEngine { get _registry() { return readRegistry(); }, get relatedSchemaOf() { return readRelatedSchemaOf(); }, find: (...a) => this.find(...a), + relationSemiJoinServes: (...a) => this.relationSemiJoinServes(...a), }; return (lowerRelationConditions).call(host, object, operation, where, execCtx); } + /** Whether a read of `object` may plan its relation condition on `target` as a semi-join (`relation-semi-join.ts`). */ + private relationSemiJoinServes(object: string, target: string): boolean { + const host: ThisParameterType = { + uncomposableReadableIdsParent: (...a) => this.uncomposableReadableIdsParent(...a), + hasHooksFor: (...a) => this.hasHooksFor(...a), + getDriver: (...a) => this.getDriver(...a), + getObjectSchema: (name) => this._registry.getObject(name), + resolveEnginePosture: () => this.resolveEnginePosture(), + }; + return relationSemiJoinServes.call(host, object, target); + } + private withResolvedWhere( object: string, operation: string, diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 8606e3f6edf..03a0182ab3a 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -224,6 +224,14 @@ const READERS: Record = { disposition: 'exempt', why: 'resolves the wall column only after the federated exemption', }, + 'engine-driver-options.ts#isDriverTenantScopedSchema :: isFederatedObject()': { + disposition: 'exempt', + why: "the tenancy class a read's driver options follow: a federated object is handed no organization wall; it reads no row", + }, + 'relation-semi-join.ts#relationSemiJoinServes :: isFederatedObject()': { + disposition: 'exempt', + why: 'a federated related object keeps the id read, so no subquery is compiled against it; it reads no row', + }, // [#24197] The one-hop loader moved out of `resolvePredicateRelated` so // validation predicates and formula fields share it; a formula's hop is read // as the caller outright, so its federated answer is the caller's own read. diff --git a/packages/objectql/src/number-comparand-declared-type-door.ts b/packages/objectql/src/number-comparand-declared-type-door.ts index acdfa13031d..bfbf1a66bc9 100644 --- a/packages/objectql/src/number-comparand-declared-type-door.ts +++ b/packages/objectql/src/number-comparand-declared-type-door.ts @@ -147,8 +147,8 @@ * The nested-relation form is SERVED at `where` (`relation-filter-lowering.ts`). * There a no-operator object beneath a relation column is not refused by the * arm above: it is admitted against the related object's declarations - * (`admitRelationCondition` — one level, declared keys, a registered related - * object) or refused in words of its own. The engine then walks the admitted + * (`admitRelationCondition` — up to three relationships, declared keys, a + * registered related object) or refused in words of its own. The engine then walks the admitted * `where` again with this SAME walk ({@link mapRelationConditions}) to collect * each condition and, after reading the related object, to replace it — so the * door and the lowering find a condition at the same boundaries by diff --git a/packages/objectql/src/query-expression-conformance.test.ts b/packages/objectql/src/query-expression-conformance.test.ts index bd32e26c1e7..9fc6b77c609 100644 --- a/packages/objectql/src/query-expression-conformance.test.ts +++ b/packages/objectql/src/query-expression-conformance.test.ts @@ -52,6 +52,7 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { isComposedReadableIds } from '@objectstack/spec/data'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; @@ -162,7 +163,16 @@ function makeStubDriver() { } if (k.startsWith('$')) continue; if (v && typeof v === 'object' && '$in' in (v as any)) { - if (!(v as any).$in.map(String).includes(String(row[k]))) return false; + // A composed `ReadableIds` leaf (the semi-join form of a + // single-valued nested-relation condition): the ids of the + // parent's rows its scope matches, evaluated in process. + const comparand = (v as any).$in; + const ids: unknown[] = isComposedReadableIds(comparand) + ? Array.from(storeFor(comparand.object).values()) + .filter((parent) => matchesWhere(parent, comparand.scope)) + .map((parent) => parent.id) + : comparand; + if (!ids.map(String).includes(String(row[k]))) return false; continue; } // [#7641] Keyed on `$icontains` since the compiler emits it. The @@ -1232,8 +1242,9 @@ describe('#4226 — sort / select / expand on the list path (real ObjectQL engin // INVALID_FIELD, that verdict has started judging comparand VALUES, // which is a different (and wrong) gate. [#20745] The engine refused // the form itself for a while — no driver served it. [#20802] It is - // SERVED now: the engine reads the related object with the condition - // and hands the driver `$in` on its ids, so both doors answer the rows + // SERVED now: the engine plans the related object's read with the + // condition and hands the driver `$in` on a semi-join leaf scoped by + // it, so both doors answer the rows // the undotted `{ project_id: 'p1' }` control answers. const byFk: any = await protocol.findData({ object: 'showcase_task', query: { where: { project_id: 'p1' } } }); const wanted = byFk.records.map((r: any) => r.id).sort(); diff --git a/packages/objectql/src/relation-condition-prescription-cap.test.ts b/packages/objectql/src/relation-condition-prescription-cap.test.ts index e59e0ec4dc9..52bbad3455d 100644 --- a/packages/objectql/src/relation-condition-prescription-cap.test.ts +++ b/packages/objectql/src/relation-condition-prescription-cap.test.ts @@ -11,7 +11,7 @@ * reasoning, and this file reads every reason the way a client does — through * `mapDataError` — and requires the whole route in what survives the cut, * ahead of "NOT applied". Run against the words as they stood on `origin/main` - * `cf218eed1`, the second-level and dotted-key routes are cut on the card's + * `cf218eed1`, the second-level (now hop-limit) and dotted-key routes are cut on the card's * fixture, and every reason's route is cut on the stress fixture. * * Two fixtures. The card's — a 21-character object, a 21-character field, a @@ -71,8 +71,9 @@ const STRESS_MULTI: Fixture = { ...STRESS, multiple: true }; function routes(f: Fixture): Record { const ids = f.multiple ? '"$contains": ID } }, one per id.' : '"$in": [ID, …] } }.'; return { - secondLevel: [`Read '${f.target}' with { "parent_account": { … } }`, ids], - dottedKey: [`Read '${f.target}' with that condition`, ids], + // Refused at the third hop, on the single-valued `parent_account`, so its route is `$in`. + hopLimit: [`Read '${f.target}' with { "parent_account": { … } }`, '"$in": [ID, …] } }.'], + dottedKey: [`read '${f.target}' with that condition`, ids], empty: ['Name one (', '"$null": false } }.'], undeclaredKey: ['Name a field it declares', '"FIELD": VALUE } }.'], unregistered: ['Match ', ids], @@ -130,8 +131,10 @@ describe('[#27351] the nested-relation condition refusal: every route lands insi const route = routes(f); const condition = conditionOf(f); - it('a second-level relation', () => { - expectRouteInside(f, refusal(f, { ...condition, parent_account: { [f.keys[0]]: 'x' } }), route.secondLevel); + it('a relation past the hop limit', () => { + // Four hops through the self-referencing `parent_account`: refused at the third. + const hop = (inner: unknown) => ({ parent_account: inner }); + expectRouteInside(f, refusal(f, { ...condition, ...hop(hop(hop({ [f.keys[0]]: 'x' }))) }), route.hopLimit); }); it('a dotted key', () => { diff --git a/packages/objectql/src/relation-filter-lowering.ts b/packages/objectql/src/relation-filter-lowering.ts index 2f1d2a495ff..417badb8672 100644 --- a/packages/objectql/src/relation-filter-lowering.ts +++ b/packages/objectql/src/relation-filter-lowering.ts @@ -10,11 +10,15 @@ * * ## The cut, closed (maintainer ruling on #20802, letter A) * - * - **Forward, one level.** The condition names a relation field of the - * queried object and fields of the related object. A second relation beneath - * it (`{ owner: { account: { name: 'x' } } }`, or the dotted - * `{ owner: { 'account.name': 'x' } }`) is refused, loudly. The reverse form - * (a parent filtered by its children) is not served here at all. + * - **Forward, up to {@link RELATION_CONDITION_MAX_HOPS} relationships.** The + * condition names a relation field of the queried object and fields of the + * related object; one of those may itself be a relation holding a condition + * of its own (`{ owner: { account: { name: 'x' } } }`), down to ADR-0071's + * hop limit. A condition past it, and the dotted spelling + * (`{ owner: { 'account.name': 'x' } }`), are refused, loudly. Each hop is + * the related object's own read (below), so each carries that object's read + * scope. The reverse form (a parent filtered by its children) is not served + * here at all. * - **Where.** `where`, on every verb that takes one (`find`, `findOne`, * `count`, `aggregate`, `update`, `delete`) and on the judge-only * `judgeFilter`. An aggregation's own `filter` and `having` keep the @@ -27,7 +31,14 @@ * one field-predicate check that refuses it on a direct read (the security * layer's filter-oracle guard, a loud `PERMISSION_DENIED`), never answered * with an empty result. There is no second copy of that rule here. - * - **Bounded, loudly.** At most {@link RELATION_FILTER_ID_CAP} related ids + * - **A subquery on a read verb, where it is provably the same read.** On + * `find`, `findOne`, `count` and `aggregate` a single-valued relation is + * matched by one in-database subquery scoped by the related object's own + * planned read where that subquery is provably the related read's own + * statement (`relation-semi-join.ts` names the conditions): no id list, so + * none of the bound below. Everywhere else the ids are read. + * - **Bounded, loudly, where ids are read** (a multi-valued relation, a write + * verb, every case the subquery is not taken). At most {@link RELATION_FILTER_ID_CAP} related ids * feed one condition. The read asks for one more than the cap; when it gets * it, the filter is refused `INVALID_FILTER` / 400 with the two-step route in * the words — ⛔ never a truncated match. @@ -83,6 +94,14 @@ import { isNoOperatorObject, provisionedNoOperatorObjectColumn } from './no-oper */ export const RELATION_FILTER_ID_CAP = 1000; +/** + * The most relationships one nested-relation condition may traverse: ADR-0071's + * hop limit (3 to-one hops, four objects), the one the dataset `include` path + * carries. `{ a: { b: { c: { field: v } } } }` is three hops; a condition + * beneath a fourth relation is refused (`hop-limit`), never cut. + */ +export const RELATION_CONDITION_MAX_HOPS = 3; + /** One nested-relation condition the walk found and admitted. */ export interface RelationFilterSite { /** The relation field of the queried object — the filter key. */ @@ -105,7 +124,7 @@ export type RelationConditionRefusalReason = | 'empty' | 'dotted-key' | 'undeclared-key' - | 'second-level'; + | 'hop-limit'; /** A condition the admission refused: the site, the reason, and the key at fault. */ export interface RelationConditionRefusal { @@ -118,9 +137,9 @@ export interface RelationConditionRefusal { readonly path: string; /** The condition's own keys, in order. */ readonly keys: readonly string[]; - /** The key the refusal is about (`dotted-key`, `undeclared-key`, `second-level`). */ + /** The key the refusal is about (`dotted-key`, `undeclared-key`, `hop-limit`). */ readonly key?: string; - /** `second-level`: the declared type of the related object's relation field. */ + /** `hop-limit`: the declared type of the related object's relation field. */ readonly keyType?: string; } @@ -155,9 +174,12 @@ function declaredTypeOf(def: unknown): string | undefined { * (`schemaOf` answers its declared field map), the condition names at least * one field, and every key is a field the related object declares — or a * column the platform provisions on every record (`id`, `created_at`, - * `updated_at`) — undotted, and not itself a relation holding a condition of - * its own (one level). What each key is compared WITH is the related object's - * own doors' question, asked when the related object is read. + * `updated_at`) — undotted. A key that is itself a relation holding a + * condition of its own is admitted the same way, one hop further, up to + * {@link RELATION_CONDITION_MAX_HOPS}; its refusal is the answer for the whole + * condition (it names its own field and path). What each key is compared WITH + * is the related object's own doors' question, asked when the related object + * is read. */ export function admitRelationCondition( field: string, @@ -165,6 +187,7 @@ export function admitRelationCondition( condition: Record, path: string, schemaOf: ((name: string) => unknown) | undefined, + hops = 1, ): RelationConditionVerdict { const type = declaredTypeOf(def) ?? 'lookup'; const target = referenceTargetOf(def); @@ -194,7 +217,11 @@ export function admitRelationCondition( } const keyType = declaredTypeOf(declared); if (keyType !== undefined && REFERENCE_VALUE_TYPES.has(keyType) && isNoOperatorObject(condition[key])) { - return refuse('second-level', key, keyType); + if (hops >= RELATION_CONDITION_MAX_HOPS) return refuse('hop-limit', key, keyType); + const inner = admitRelationCondition( + key, declared, condition[key] as Record, `${path}.${key}`, schemaOf, hops + 1, + ); + if (!inner.ok) return inner; } } return { ok: true, site: { field, type, target, multiple, condition, path } }; @@ -283,14 +310,14 @@ export function relationConditionRefusalMessage(refusal: RelationConditionRefusa ); case 'dotted-key': return ( - `${head}, and '${key}' is a dotted path: the condition reaches one level only. ` - + `Read ${named} with that condition, ${twoStep} ${verdict}` + `${head}, and '${key}' is a dotted path: nest each relation ` + + `instead, or read ${named} with that condition, ${twoStep} ${verdict}` ); - case 'second-level': + case 'hop-limit': default: return ( - `${head}, and '${key}' holds a condition of its own: one level only. Read ${named} with ` - + `{ "${key}": { … } }, ${twoStep} ${verdict} '${key}' is itself a ` + `${head}, and '${key}' holds a condition of its own past the ${RELATION_CONDITION_MAX_HOPS}-relationship ` + + `limit. Read ${named} with { "${key}": { … } }, ${twoStep} ${verdict} '${key}' is itself a ` + `${refusal.keyType ?? 'relation'} field of ${related}.` ); } diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts new file mode 100644 index 00000000000..20c004e45f9 --- /dev/null +++ b/packages/objectql/src/relation-semi-join.ts @@ -0,0 +1,269 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The nested-relation condition, served as an IN-DATABASE SEMI-JOIN on a + * single-valued relation: `{ account: { status: { $ne: 'cancelled' } } }` on + * `order` reaches the driver as ONE statement, + * `account IN (SELECT id FROM account WHERE AND + * status <> 'cancelled' AND )`, with no id list read first and + * no cap on how many related records match. + * + * ## How the related half is built: the related object's own read, planned + * + * The condition is handed to the engine's own `find` on the related object, + * under the CALLER's execution context, exactly as the id-reading lowering + * did — the related object's CRUD gate, every read middleware (row-level + * scope, the filter-oracle guard on the condition's fields), the + * `beforeFind` hooks, its comparand doors and its value lowering all run. + * Only the last step differs: at the driver call, the read is PLANNED, not + * executed. The final `where` the driver would have been handed — the + * condition AND-ed with every scope the pipeline injected, its own + * `ReadableIds` leaves already composed — is captured + * ({@link RELATION_SCOPE_PLAN}), and no driver is asked. + * + * That captured `where` becomes the scope of a `ReadableIds` leaf over the + * related object, which the outer read carries as the relation field's `$in` + * comparand. The engine's executor boundary composes it with THAT scope + * ({@link plannedRelationLeafVerdict}), never by asking the security service + * a second, narrower question. The driver applies its tenant wall to the + * related table with the OUTER read's options (ADR-0139 D3), so the leaf is + * composed only when those options are the related read's own; with that, + * a related record is in the subquery exactly when the id read would have + * returned it. + * + * ## Taken only where it is provably the same read as the id read + * + * Every other case reads the related ids as the caller and matches the field + * with `$in`, under the cap — the id read the engine has always run, unchanged + * ({@link relationSemiJoinServes}, then the planned read's own outcome, then + * the executor boundary's comparison): + * + * - **Before planning** — the registry already answers: the related object + * has a restriction no planned `where` can carry, or the read's driver + * compiles no subquery: an object-scoped middleware or an `afterFind` hook + * on the related object (both act after its driver call), another + * datasource than the read's object, a federated related object, a related + * object of another tenancy class than the read's object under a walled + * posture (its driver options differ), or a driver outside + * {@link SEMI_JOIN_COMPILING_DRIVERS}. The related read is dispatched once. + * - **After planning** — the related read did not reach exactly one driver + * call, or came back with rows the driver never returned (a middleware + * answered without the driver, or added rows after it). + * - **At the executor boundary** — the outer read's driver options differ + * from the ones the related read's own driver call was given + * ({@link sameReadDriverOptions}) in a way only the request decides (a + * per-object verdict recorded for the caller): the subquery is compiled + * with the outer read's options, so only identical options make it the + * related read's own statement. The ids are then read there, as the + * caller, under the cap. + * + * A hop that falls back after planning (either of the last two) dispatches + * the related read twice: its middleware chain and `beforeFind` hooks run + * for the planned read and again for the id read. + * + * ## What the semi-join means at its edges + * + * - **No related record matches** (or none the caller can read): the + * subquery is empty, `IN` is FALSE, the row is not selected. + * - **An empty relation** (`NULL`) is never `IN` any subquery: the row is not + * selected, whatever the condition's operator, `$ne` included — exactly as + * `IN` over the id list. + * - **The planned scope is the deny sentinel**: `$in: []`, as the id read + * over it answers. + * + * ## Who evaluates the leaf + * + * The composed leaf is ADR-0139's: `driver-sql` (every dialect, Turso and + * the WASM SQLite face included) compiles it into a nested subquery; + * `driver-memory` evaluates it in process. Every other driver keeps the id + * read: no capability bit says which drivers compile the leaf yet, so the + * engine names the ones it knows do, and an unnamed driver is never handed + * one by this lowering. + * + * ## Forgery + * + * The planned scope lives in a module-private `WeakMap` keyed by the identity + * of a leaf only this module builds. A caller who writes `ReadableIds.of(P)` + * gets an ordinary leaf, composed with P's read scope as ADR-0139 says; no + * caller can name a leaf this map holds, and a copy of one is a different + * object the map does not hold. + */ + +import { ReadableIds, RLS_DENY_FILTER, type FilterCondition } from '@objectstack/spec/data'; +import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; +import { isDriverTenantScopedSchema } from './engine-driver-options.js'; +import { isFederatedObject } from './federated-object.js'; + +/** + * The key of the internal read option that turns a `find` into a PLAN: when + * `options[RELATION_SCOPE_PLAN]` holds a {@link RelationScopePlan}, `find` + * hands it the final driver `where` and driver options in place of the + * driver call and answers the plan's own empty `rows`. + * A symbol, so no wire request, JSON body or spread author input can carry + * it; never exported from the package. + */ +export const RELATION_SCOPE_PLAN: unique symbol = Symbol('objectql.relationScopePlan'); + +/** What a planned read is handed: where to put its driver call, and what to answer. */ +export interface RelationScopePlan { + /** Called at the driver call with exactly what the driver would have been handed. */ + capture(where: FilterCondition | undefined, driverOptions: unknown): void; + /** The answer the planned read gives in place of the driver's: an empty array of this plan's own. */ + readonly rows: unknown[]; +} + +/** The driver names whose drivers compile (or, in process, evaluate) a composed `ReadableIds` leaf. */ +export const SEMI_JOIN_COMPILING_DRIVERS: ReadonlySet = new Set([ + 'com.objectstack.driver.sql', + 'com.objectstack.driver.turso', + 'com.objectstack.driver.sqlite-wasm', + 'com.objectstack.driver.memory', +]); + +/** What {@link relationSemiJoinServes} reads off the engine. */ +export interface RelationSemiJoinServesHost { + uncomposableReadableIdsParent(object: string, parent: string): unknown; + hasHooksFor(event: string, object: string): boolean; + getDriver(object: string): { readonly name?: unknown } | undefined; + /** The registered schema of `object` (`undefined` when none is registered). */ + getObjectSchema(object: string): unknown; + /** The tenancy posture in force, as the engine's driver options read it. */ + resolveEnginePosture(): TenancyPosture; +} + +/** + * Whether a read of `object` may PLAN its relation condition on `target` as a + * semi-join at all. `false` keeps the id read. Registry facts only — nothing + * is read and the caller's context is not consulted: + * + * - `target` is in neither of ADR-0139 D5's remaining classes for `object` + * (an object-scoped read middleware narrows its rows after its driver call; + * it is bound to another datasource than `object`); + * - no `afterFind` hook is registered for `target` (a hook may filter the + * rows the id read returns, after its driver call); + * - `target` is not federated (ADR-0015 `external`): the driver prepares a + * federated object's remote catalog facts for the object a read door is + * reading, and a subquery's object is not that object; + * - under a walled posture, `object` and `target` are of the same tenancy + * class ({@link isDriverTenantScopedSchema}): otherwise one read's driver + * options carry a tenant scope the other's do not, and the executor + * boundary would fall back after the related read was already planned — + * dispatching it a second time. Deciding it here dispatches it once. + * - `object`'s driver compiles the composed leaf ({@link SEMI_JOIN_COMPILING_DRIVERS}). + */ +export function relationSemiJoinServes(this: RelationSemiJoinServesHost, object: string, target: string): boolean { + if (this.uncomposableReadableIdsParent(object, target) !== undefined) return false; + if (this.hasHooksFor('afterFind', target)) return false; + const targetSchema = this.getObjectSchema(target); + if (isFederatedObject(targetSchema)) return false; + if ( + postureEnforcesWall(this.resolveEnginePosture()) && + isDriverTenantScopedSchema(this.getObjectSchema(object)) !== isDriverTenantScopedSchema(targetSchema) + ) return false; + const name = this.getDriver(object)?.name; + return typeof name === 'string' && SEMI_JOIN_COMPILING_DRIVERS.has(name); +} + +/** What a planned related read answered for one leaf. */ +interface PlannedRelationScope { + /** The captured driver `where`. */ + readonly where: FilterCondition | undefined; + /** The captured driver options of the related read's own driver call. */ + readonly driverOptions: unknown; + /** The id read, as the caller, under the cap — for an outer read whose options differ. */ + readonly readIds: () => Promise; +} + +const plannedScopes = new WeakMap(); + +/** + * Plan the related read and build the `ReadableIds` leaf over `target` whose + * scope is its final driver `where`. `plan(p)` runs that read, handing `p` to + * it as the {@link RELATION_SCOPE_PLAN} option; a refusal from it propagates, + * as the id read's would. `readIds` is the id read itself. + * + * Answers `null` — read the ids instead — unless the read reached exactly one + * driver call and its answer came back with no row in it. A middleware that + * answered without the driver, or that added rows after it, is a read the + * planned `where` does not describe. A middleware that reshapes the rows + * (the field mask maps each row to a masked copy) changes no id and is not + * one. A read rule that narrows the related object's rows after its driver + * call bounds a relation condition only when it is registered for that + * object, as ADR-0139 D5.2 bounds a `ReadableIds` parent: an object-keyed + * middleware or an `afterFind` hook, for which {@link relationSemiJoinServes} + * keeps the id read. + */ +export async function planRelationSemiJoinLeaf( + target: string, + plan: (p: RelationScopePlan) => Promise, + readIds: () => Promise, +): Promise | null> { + const captured: Array<{ where: FilterCondition | undefined; driverOptions: unknown }> = []; + const rows: unknown[] = []; + const answer = await plan({ rows, capture: (where, driverOptions) => { captured.push({ where, driverOptions }); } }); + if (captured.length !== 1 || !Array.isArray(answer) || answer.length !== 0 || rows.length !== 0) return null; + const leaf = ReadableIds.of(target); + plannedScopes.set(leaf, { ...captured[0], readIds }); + return leaf; +} + +/** Whether this module built `leaf` (a planned relation semi-join leaf). */ +export function isPlannedRelationLeaf(leaf: unknown): boolean { + return leaf !== null && typeof leaf === 'object' && plannedScopes.has(leaf); +} + +/** + * Driver option keys that never change which rows a read returns: they are + * not compared. Every other key — the tenant scope, the transaction, the + * timezone, and any key added later — must be equal. + */ +const ROW_NEUTRAL_DRIVER_OPTIONS: ReadonlySet = new Set(['bypassTenantAudit', 'traceContext', 'timeoutMs', 'skipCache']); + +const isBlank = (v: unknown): boolean => v === undefined || v === null || v === ''; + +/** + * Whether the outer read's driver options are the related read's own, for + * every key that can change the rows a read returns — then the subquery the + * driver compiles with the outer options is the related read's own statement. + * Arrays compare element-wise; everything else by identity. + */ +export function sameReadDriverOptions(outer: unknown, related: unknown): boolean { + const a = (outer !== null && typeof outer === 'object' ? outer : {}) as Record; + const b = (related !== null && typeof related === 'object' ? related : {}) as Record; + for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) { + if (ROW_NEUTRAL_DRIVER_OPTIONS.has(key)) continue; + const x = a[key]; + const y = b[key]; + if (isBlank(x) && isBlank(y)) continue; + if (Array.isArray(x) && Array.isArray(y)) { + if (x.length !== y.length || x.some((v, i) => v !== y[i])) return false; + continue; + } + if (x !== y) return false; + } + return true; +} + +/** How the executor boundary answers a planned leaf. */ +export type PlannedRelationLeafVerdict = + | { readonly kind: 'compose'; readonly scope: FilterCondition | undefined } + | { readonly kind: 'empty' } + | { readonly kind: 'read'; readonly readIds: () => Promise }; + +/** + * The executor boundary's answer for `leaf` in a read whose driver is handed + * `outerDriverOptions`: `compose` with the planned scope when the options are + * the related read's own; `empty` (`$in: []`) when the planned scope is the + * deny sentinel, whatever the options (an empty set stays empty); otherwise + * `read` — the ids, read as the caller under the cap. `undefined` when this + * module did not build `leaf`: an ordinary ADR-0139 leaf, composed through the + * security service. + */ +export function plannedRelationLeafVerdict(leaf: unknown, outerDriverOptions: unknown): PlannedRelationLeafVerdict | undefined { + if (leaf === null || typeof leaf !== 'object') return undefined; + const entry = plannedScopes.get(leaf); + if (entry === undefined) return undefined; + if (entry.where === (RLS_DENY_FILTER as unknown)) return { kind: 'empty' }; + if (!sameReadDriverOptions(outerDriverOptions, entry.driverOptions)) return { kind: 'read', readIds: entry.readIds }; + return { kind: 'compose', scope: entry.where }; +} diff --git a/packages/rest/src/analytics-nested-relation-filter.test.ts b/packages/rest/src/analytics-nested-relation-filter.test.ts index d9016fe8bdd..5e41be79516 100644 --- a/packages/rest/src/analytics-nested-relation-filter.test.ts +++ b/packages/rest/src/analytics-nested-relation-filter.test.ts @@ -93,13 +93,14 @@ const SERVED: ReadonlyArray = [ ['under $not', { $not: { owner: { region: 'NA' } } }], ['multi-valued under $not', { $not: { owners: { region: 'NA' } } }], ['inside $or', { $or: [{ owner: { region: 'NA' } }, { title: 'b' }] }], + // A single-valued relation is one subquery on a SQL driver: no id list, no cap. + ['single-valued, more related matches than the id cap', { owner: { region: 'CAP' } }], ]; /** Conditions the engine REFUSES: its envelope is the answer every face must give. */ const REFUSED: ReadonlyArray = [ ['a related field the caller cannot read', { owner: { secret: 's1' } }, { code: 'PERMISSION_DENIED', status: 403 }], ['a related field the caller cannot read, multi-valued', { owners: { secret: 's1' } }, { code: 'PERMISSION_DENIED', status: 403 }], - ['past the cap', { owner: { region: 'CAP' } }, { code: 'INVALID_FILTER', status: 400 }], ['past the cap, multi-valued', { owners: { region: 'CAP' } }, { code: 'INVALID_FILTER', status: 400 }], ]; @@ -155,7 +156,7 @@ const titlesOf = (rows: ReadonlyArray>, key: string) => interface Harness { engine: ObjectQL; analytics: AnalyticsService; - dataset: (selection: Record) => Promise<{ status: number; body: any }>; + dataset: (selection: Record, def?: Record) => Promise<{ status: number; body: any }>; } /** @@ -250,9 +251,9 @@ async function boot(opts: { caps?: 'objectql'; getReadScope?: (object: string) = rest.registerRoutes(); const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/analytics/dataset/query'); expect(route).toBeDefined(); - const dataset = async (selection: Record) => { + const dataset = async (selection: Record, def: Record = DATASET) => { const res = makeRes(); - const body = JSON.parse(JSON.stringify({ dataset: DATASET, selection })); + const body = JSON.parse(JSON.stringify({ dataset: def, selection })); await route!.handler({ method: 'POST', params: {}, headers: {}, body, query: {} } as any, res); return { status: res.statusCode, body: res.body }; }; @@ -405,7 +406,7 @@ describe('[#20887] a read scope carrying the nested-relation form', () => { * engine-aggregate path. `engine.aggregate` cannot join, so `ObjectQLStrategy` * refused every such `where` leaf (`400 INVALID_FIELD`, "cannot join in an * aggregate"), and a dashboard over detail rows could not leave out the rows of - * a cancelled parent. It now hands a one-hop leaf to the engine as the + * a cancelled parent. It now hands the leaf (up to three hops, #33626) to the engine as the * nested-relation condition above (`cross-object-where.ts`), so its answer is * the engine's for that condition, computed here as the reference: the related * object read as the caller, its row scope and field permissions applied, an @@ -418,7 +419,7 @@ describe('[#20887] a read scope carrying the nested-relation form', () => { * questions: what a child with NO parent gets under a negative operator (it is * not selected — a cross-object leaf requires a related record the caller can * read; OR in `{ owner: { $null: true } }` to keep such rows), and that the - * shapes this path cannot serve exactly (under `$not`, two hops) stay refused + * shapes this path cannot serve exactly (under `$not`, past three hops) stay refused * rather than answered differently. */ describe('[#33335] a dotted cross-object where on the engine-aggregate path answers the engine\'s nested-relation condition', () => { @@ -484,15 +485,39 @@ describe('[#33335] a dotted cross-object where on the engine-aggregate path answ } }); - it('a related field the caller cannot read, and a match past the cap, are refused as the engine refuses them', async () => { + it('a related field the caller cannot read is refused as the engine refuses it; a single-valued match past the id cap is served', async () => { const cases: ReadonlyArray = [ [{ 'owner.secret': 's1' }, { owner: { secret: 's1' } }, { code: 'PERMISSION_DENIED', status: 403 }], - [{ 'owner.region': 'CAP' }, { owner: { region: 'CAP' } }, { code: 'INVALID_FILTER', status: 400 }], ]; for (const [dotted, nested, expected] of cases) { expect(await reference(nested), JSON.stringify(nested)).toEqual({ refused: expected }); expect(await cubeRead(dotted), JSON.stringify(dotted)).toEqual({ refused: expected }); } + // One subquery, no id list: the 1001 `CAP` owners select no ledger row, served. + const pastCap = await reference({ owner: { region: 'CAP' } }); + expect(pastCap).not.toHaveProperty('refused'); + expect(await cubeRead({ 'owner.region': 'CAP' })).toEqual(pastCap); + }); + + it('[#33626] the dataset\'s OWN filter carrying a dotted leaf is served the same way: the engine\'s rows, the hidden and the orphan parent left out under $ne', async () => { + const scoped = (filter: FilterCondition) => ({ + ...DATASET, + name: 'nested_relation_scoped', + measures: [{ name: 'row_count', aggregate: 'count' }], + filter, + }); + for (const [dotted, nested] of [ + [{ 'owner.region': { $ne: 'NA' } }, { owner: { region: { $ne: 'NA' } } }], + [{ 'owner.region': 'NA' }, { owner: { region: 'NA' } }], + ] as Array<[FilterCondition, FilterCondition]>) { + const expected = await reference(nested); + expect(expected, JSON.stringify(nested)).toHaveProperty('titles'); + const ds = await h.dataset({ measures: ['row_count'], dimensions: ['title_dim'] }, scoped(dotted)); + expect(ds.status, `${JSON.stringify(dotted)}: ${JSON.stringify(ds.body)}`).toBe(200); + expect({ titles: titlesOf(ds.body.rows, 'title_dim') }, JSON.stringify(dotted)).toEqual(expected); + } + // The engine's titles for `$ne` exclude d4 (the hidden owner) and d5 (no owner). + expect(await reference({ owner: { region: { $ne: 'NA' } } })).toEqual({ titles: ['b'] }); }); it('a leaf under $not stays refused, never answered from a negated match that admits the hidden owner\'s row', async () => { diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index 0ff8d7b6186..76765f4e78c 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -17,7 +17,7 @@ * | `{ $or: [{ owner: { region: 'EU' } }, { title: 'a' }] }` | 400 | `d1`, `d2` | * | `{ owner: { region: 'APAC' } }` (no related record matches) | 400 | no rows | * | `{ meta: { a: 1 } }` (json; address alike), `{ id: { a: 1 } }` | 400 | 400, unchanged | - * | a second level, an undeclared key, `{}`, an unregistered related object | 400 | 400, in words of their own | + * | a fourth relationship (ADR-0071's limit is 3), an undeclared key, `{}`, an unregistered related object | 400 | 400, in words of their own | * | `aggregations[1].filter` / `having` `{ owner: { region: 'NA' } }` | 400 | 400, the words say `where` serves it | * * The InMemoryDriver cells were measured on this branch and are not pinned @@ -124,6 +124,14 @@ const SERVED: ReadonlyArray { + it('no cap on a single-valued relation (one subquery, no id list); a multi-valued one past the cap is REFUSED, never truncated', async () => { const many = Array.from({ length: RELATION_FILTER_ID_CAP }, (_, i) => ({ id: `cap_${i}`, region: 'CAP' })); // In batches: one multi-row INSERT of a thousand rows passes SQLite's // compound-SELECT limit. @@ -294,11 +302,14 @@ for (const cell of CELLS) { await engine.insert(OBJECT, { id: 'd_cap', title: 'cap', owner: 'cap_extra' } as any); try { const over = await query({ where: { owner: { region: { $in: ['CAP', 'CAP_EXTRA'] } } } }); - expect(over.status, JSON.stringify(over.body)).toBe(400); - expect(over.body.code).toBe('INVALID_FILTER'); - expect(over.body.error).toContain(`matched more than ${RELATION_FILTER_ID_CAP} records of the related object '${OWNER}'`); - expect(over.body.error).toContain('the filter was NOT applied'); - expect(over.body.error).toContain('{ "owner": { "$in": [ID, …] } }'); + expect(over.status, JSON.stringify(over.body)).toBe(200); + expect(idsOf(over.body)).toEqual(['d_cap']); + const overMulti = await query({ where: { owners: { region: { $in: ['CAP', 'CAP_EXTRA'] } } } }); + expect(overMulti.status, JSON.stringify(overMulti.body)).toBe(400); + expect(overMulti.body.code).toBe('INVALID_FILTER'); + expect(overMulti.body.error).toContain(`matched more than ${RELATION_FILTER_ID_CAP} records of the related object '${OWNER}'`); + expect(overMulti.body.error).toContain('the filter was NOT applied'); + expect(overMulti.body.error).toContain('{ "owners": { "$contains": ID } }'); // Exactly the cap: served, every id in play (no ledger row points at one). const at = await query({ where: { owner: { region: 'CAP' } } }); expect(at.status, JSON.stringify(at.body)).toBe(200); @@ -331,3 +342,373 @@ for (const cell of CELLS) { }, ); } + +// ── [#33626] up to three relationships, each hop its related object's own read ── + +const HOP_CASE = 'rest_hop_case_33626'; +const HOP_CONTACT = 'rest_hop_contact_33626'; +const HOP_ACCOUNT = 'rest_hop_account_33626'; +const HOP_REGION = 'rest_hop_region_33626'; + +const HOP_OBJECTS = [ + { name: HOP_REGION, label: 'Region 33626', fields: { name: { name: 'name', type: 'text' as const } } }, + { + name: HOP_ACCOUNT, label: 'Account 33626', + fields: { name: { name: 'name', type: 'text' as const }, region: { name: 'region', type: 'lookup' as const, reference: HOP_REGION } }, + }, + { name: HOP_CONTACT, label: 'Contact 33626', fields: { account: { name: 'account', type: 'lookup' as const, reference: HOP_ACCOUNT } } }, + { + name: HOP_CASE, label: 'Case 33626', + fields: { subject: { name: 'subject', type: 'text' as const }, contact: { name: 'contact', type: 'lookup' as const, reference: HOP_CONTACT } }, + }, +]; + +/** + * k1 → c1 → a1 → r1 (NA) · k2 → c2 → a2 → r2 (EU) · k3 → c3 → a3 → (no region) + * · k4 → c4 → a4 → r_gone (a region that does not exist: a missing parent) + * · k5 → c5 → (no account) · k6 → (no contact). + */ +const HOP_SEED: ReadonlyArray>]> = [ + [HOP_REGION, [{ id: 'r1', name: 'NA' }, { id: 'r2', name: 'EU' }, { id: 'r_gone', name: 'GONE' }]], + [HOP_ACCOUNT, [ + { id: 'a1', name: 'A1', region: 'r1' }, { id: 'a2', name: 'A2', region: 'r2' }, + { id: 'a3', name: 'A3' }, { id: 'a4', name: 'A4', region: 'r_gone' }, + ]], + [HOP_CONTACT, [{ id: 'c1', account: 'a1' }, { id: 'c2', account: 'a2' }, { id: 'c3', account: 'a3' }, { id: 'c4', account: 'a4' }, { id: 'c5' }]], + [HOP_CASE, [ + { id: 'k1', subject: 's', contact: 'c1' }, { id: 'k2', subject: 's', contact: 'c2' }, { id: 'k3', subject: 's', contact: 'c3' }, + { id: 'k4', subject: 's', contact: 'c4' }, { id: 'k5', subject: 's', contact: 'c5' }, { id: 'k6', subject: 't' }, + ]], +]; + +/** name · the nested `where` on the case · the region condition · the rows it means. */ +const HOPS: ReadonlyArray FilterCondition, FilterCondition, readonly string[]]> = [ + ['three hops', (r) => ({ contact: { account: { region: r } } }), { name: 'NA' }, ['k1']], + ['three hops, $ne — a missing or empty ancestor never matches', (r) => ({ contact: { account: { region: r } } }), { name: { $ne: 'NA' } }, ['k2']], + ['three hops, $null on the last field', (r) => ({ contact: { account: { region: r } } }), { name: { $null: true } }, []], + ['three hops, under $not — every row without a NA region', (r) => ({ $not: { contact: { account: { region: r } } } }), { name: 'NA' }, ['k2', 'k3', 'k4', 'k5', 'k6']], + ['three hops, inside $or beside a column', (r) => ({ $or: [{ subject: 't' }, { contact: { account: { region: r } } }] }), { name: 'EU' }, ['k2', 'k6']], +]; + +for (const cell of CELLS) { + const config = cell.config(); + describe.skipIf(!config)( + `[#33626] a nested-relation condition through three relationships — ${cell.label}${config ? '' : ` (skipped: set ${cell.env} to run this cell)`}`, + () => { + let engine: ObjectQL; + let driver: any; + + const dropTables = async () => { + if (cell.id === 'sqlite') return; + for (const o of HOP_OBJECTS.map((x) => x.name).reverse()) await driver?.execute(`drop table if exists ${o}`).catch(() => {}); + }; + + beforeAll(async () => { + driver = new SqlDriver(config as any); + await dropTables(); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of HOP_OBJECTS) engine.registry.registerObject(o as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const [object, rows] of HOP_SEED) for (const row of rows) await engine.insert(object, { ...row } as any); + // The missing parent: `a4` keeps pointing at a region row removed behind the engine's back. + await driver.execute(`delete from ${HOP_REGION} where id = 'r_gone'`); + }); + + afterAll(async () => { + await dropTables(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + /** The two-step route, hop by hop: read each related object's ids, then match the relation against them. */ + const twoStep = async (region: FilterCondition): Promise => { + const ids = async (object: string, where: FilterCondition) => + (await engine.find(object, { where, fields: ['id'] })).map((r: any) => r.id); + const regions = await ids(HOP_REGION, region); + const accounts = await ids(HOP_ACCOUNT, { region: { $in: regions } }); + const contacts = await ids(HOP_CONTACT, { account: { $in: accounts } }); + return { $in: contacts }; + }; + + it('each case answers the rows it means, and exactly what the two-step route answers — on find and count', async () => { + for (const [name, nest, region, rows] of HOPS) { + const nested = nest(region); + const got = (await engine.find(HOP_CASE, { where: nested })).map((r: any) => r.id).sort(); + expect(got, name).toEqual([...rows].sort()); + expect(await engine.count(HOP_CASE, { where: nested }), `count, ${name}`).toBe(rows.length); + // Parity: the same shape with the innermost three hops replaced by the hand-read id list. + const contactIds = await twoStep(region); + const reference = JSON.parse(JSON.stringify(nested).replace( + JSON.stringify({ account: { region } }), JSON.stringify(contactIds), + )); + const ref = (await engine.find(HOP_CASE, { where: reference })).map((r: any) => r.id).sort(); + expect(got, `two-step parity, ${name}: ${JSON.stringify(reference)}`).toEqual(ref); + } + }); + + it('one driver statement per read: no hop reads its ids first', async () => { + let calls = 0; + const real = driver.find.bind(driver); + driver.find = (...a: unknown[]) => { calls += 1; return real(...a); }; + try { + await engine.find(HOP_CASE, { where: { contact: { account: { region: { name: 'NA' } } } } }); + } finally { + driver.find = real; + } + expect(calls).toBe(1); + }); + }, + ); +} + +// ── [#33626] two tenants: related-object read restrictions are carried into the subquery, or the hop reads its ids ── + +const TEN_CASE = 'rest_ten_case_33626'; +const TEN_CONTACT = 'rest_ten_contact_33626'; +const TEN_ACCOUNT = 'rest_ten_account_33626'; +const TEN_REGION = 'rest_ten_region_33626'; +const TEN_TICKET = 'rest_ten_ticket_33626'; +const TEN_GRID = 'rest_ten_grid_33626'; +const ORG_A = 'org_ten_a'; +const ORG_B = 'org_ten_b'; + +/** + * The region is tenant-scoped; the case, contact and account are no tenant's + * (`tenancy.enabled: false`). Each tenant holds one NA region; each case + * reaches its own tenant's region in one hop (`region`) and in three + * (`contact` → `account` → `region`). + */ +const TEN_OBJECTS = [ + { name: TEN_REGION, label: 'Region T 33626', fields: { name: { name: 'name', type: 'text' as const } } }, + // The other direction: a tenant-scoped ticket on a grid that is no tenant's. + { name: TEN_GRID, label: 'Grid T 33626', tenancy: { enabled: false }, fields: { name: { name: 'name', type: 'text' as const } } }, + { name: TEN_TICKET, label: 'Ticket T 33626', fields: { grid: { name: 'grid', type: 'lookup' as const, reference: TEN_GRID } } }, + { + name: TEN_ACCOUNT, label: 'Account T 33626', tenancy: { enabled: false }, + fields: { region: { name: 'region', type: 'lookup' as const, reference: TEN_REGION } }, + }, + { + name: TEN_CONTACT, label: 'Contact T 33626', tenancy: { enabled: false }, + fields: { account: { name: 'account', type: 'lookup' as const, reference: TEN_ACCOUNT } }, + }, + { + name: TEN_CASE, label: 'Case T 33626', tenancy: { enabled: false }, + fields: { + contact: { name: 'contact', type: 'lookup' as const, reference: TEN_CONTACT }, + region: { name: 'region', type: 'lookup' as const, reference: TEN_REGION }, + }, + }, +]; + +const TEN_SEED: ReadonlyArray>]> = [ + [TEN_REGION, [{ id: 'tr_a', name: 'NA', organization_id: ORG_A }, { id: 'tr_b', name: 'NA', organization_id: ORG_B }]], + [TEN_ACCOUNT, [{ id: 'ta_a', region: 'tr_a' }, { id: 'ta_b', region: 'tr_b' }]], + [TEN_CONTACT, [{ id: 'tc_a', account: 'ta_a' }, { id: 'tc_b', account: 'ta_b' }]], + [TEN_CASE, [{ id: 'tk_a', contact: 'tc_a', region: 'tr_a' }, { id: 'tk_b', contact: 'tc_b', region: 'tr_b' }]], + [TEN_GRID, [{ id: 'tg_1', name: 'NA' }]], + [TEN_TICKET, [{ id: 'tt_a', grid: 'tg_1', organization_id: ORG_A }, { id: 'tt_b', grid: 'tg_1', organization_id: ORG_B }]], +]; + +/** name · the `where` on the case — both mean "my tenant's NA region". */ +const TEN_HOPS: ReadonlyArray = [ + ['one hop', { region: { name: 'NA' } }], + ['three hops', { contact: { account: { region: { name: 'NA' } } } }], +]; + +for (const cell of CELLS) { + const config = cell.config(); + describe.skipIf(!config)( + `[#33626] two tenants — a condition on tenant A's related rows never matches for a tenant B caller — ${cell.label}${config ? '' : ` (skipped: set ${cell.env} to run this cell)`}`, + () => { + let engine: ObjectQL; + let driver: any; + const CALLER_B = { userId: 'u_ten_b', tenantId: ORG_B }; + + const dropTables = async () => { + if (cell.id === 'sqlite') return; + for (const o of TEN_OBJECTS.map((x) => x.name).reverse()) await driver?.execute(`drop table if exists ${o}`).catch(() => {}); + }; + + beforeAll(async () => { + driver = new SqlDriver(config as any); + await dropTables(); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of TEN_OBJECTS) engine.registry.registerObject(o as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + // Seeded through the driver: each tenant's row carries its own organization. + for (const [object, rows] of TEN_SEED) for (const row of rows) await driver.create(object, { ...row }); + // The organization wall: the related read of the region is walled to the caller's tenant. + engine.setTenancyPostureProvider(() => 'isolated'); + }); + + afterAll(async () => { + await dropTables(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + /** The two-step route as the caller, hop by hop — what the id read answers. */ + const twoStep = async (hops: number): Promise => { + const ids = async (object: string, where: FilterCondition) => + (await engine.find(object, { where, fields: ['id'], context: CALLER_B })).map((r: any) => r.id); + const regions = await ids(TEN_REGION, { name: 'NA' }); + if (hops === 1) return (await ids(TEN_CASE, { region: { $in: regions } })).sort(); + const accounts = await ids(TEN_ACCOUNT, { region: { $in: regions } }); + const contacts = await ids(TEN_CONTACT, { account: { $in: accounts } }); + return (await ids(TEN_CASE, { contact: { $in: contacts } })).sort(); + }; + + it('CONTROL the region read is walled: tenant B reads its own NA region only', async () => { + const regions = await engine.find(TEN_REGION, { where: { name: 'NA' }, context: CALLER_B }); + expect(regions.map((r: any) => r.id)).toEqual(['tr_b']); + }); + + for (const [name, where] of TEN_HOPS) { + it(`${name}: only tenant B's case, exactly the two-step route's answer — on find and count`, async () => { + const got = (await engine.find(TEN_CASE, { where, context: CALLER_B })).map((r: any) => r.id).sort(); + expect(got, name).toEqual(['tk_b']); + expect(got, `two-step parity, ${name}`).toEqual(await twoStep(name === 'one hop' ? 1 : 3)); + expect(await engine.count(TEN_CASE, { where, context: CALLER_B }), `count, ${name}`).toBe(1); + }); + } + + it('the other direction — a tenant-scoped ticket on a grid that is no tenant\'s: tenant B\'s ticket, the two-step route\'s answer, the grid read dispatched once', async () => { + const grids = { n: 0 }; + const packageId = 'test.ten-grid-dispatch'; + engine.registerHook('beforeFind', async () => { grids.n += 1; }, { object: TEN_GRID, packageId }); + try { + const idsAs = async (object: string, where: FilterCondition) => + (await engine.find(object, { where, fields: ['id'], context: CALLER_B })).map((r: any) => r.id).sort(); + const got = await idsAs(TEN_TICKET, { grid: { name: 'NA' } }); + expect(got).toEqual(['tt_b']); + // Decided from the registry before planning: one dispatch of the grid read. + expect(grids.n).toBe(1); + expect(got, 'two-step parity').toEqual(await idsAs(TEN_TICKET, { grid: { $in: await idsAs(TEN_GRID, { name: 'NA' }) } })); + expect(await engine.count(TEN_TICKET, { where: { grid: { name: 'NA' } }, context: CALLER_B }), 'count').toBe(1); + } finally { + engine.unregisterHooksByPackage(packageId); + } + }); + + it('a read rule the region applies after its driver call gives the two-step route\'s answer', async () => { + const hook = async (ctx: any) => { ctx.result = (ctx.result as any[]).filter((row) => row.id !== 'tr_b'); }; + engine.registerHook('afterFind', hook, { object: TEN_REGION, packageId: 'test.ten-region-rule' }); + try { + for (const [name, where] of TEN_HOPS) { + const got = (await engine.find(TEN_CASE, { where, context: CALLER_B })).map((r: any) => r.id).sort(); + expect(got, name).toEqual([]); + expect(got, `two-step parity, ${name}`).toEqual(await twoStep(name === 'one hop' ? 1 : 3)); + } + } finally { + engine.unregisterHooksByPackage('test.ten-region-rule'); + } + }); + }, + ); +} + +// ── [#33626] the executor boundary: driver options differ → id read, in both directions ── + +const OPT_CASE = 'rest_opt_case_33626'; +const OPT_REGION = 'rest_opt_region_33626'; +const OPT_ORG_A = 'org_opt_a'; +const OPT_ORG_B = 'org_opt_b'; + +/** Both objects are tenant-scoped: the registry cannot tell their driver options apart. */ +const OPT_OBJECTS = [ + { name: OPT_REGION, label: 'Region O 33626', fields: { name: { name: 'name', type: 'text' as const } } }, + { name: OPT_CASE, label: 'Case O 33626', fields: { region: { name: 'region', type: 'lookup' as const, reference: OPT_REGION } } }, +]; + +/** Each organization holds one NA region; each holds one case on its own region and one on the other's. */ +const OPT_SEED: ReadonlyArray>]> = [ + [OPT_REGION, [{ id: 'or_a', name: 'NA', organization_id: OPT_ORG_A }, { id: 'or_b', name: 'NA', organization_id: OPT_ORG_B }]], + [OPT_CASE, [ + { id: 'ok_aa', region: 'or_a', organization_id: OPT_ORG_A }, { id: 'ok_ab', region: 'or_b', organization_id: OPT_ORG_A }, + { id: 'ok_ba', region: 'or_a', organization_id: OPT_ORG_B }, { id: 'ok_bb', region: 'or_b', organization_id: OPT_ORG_B }, + ]], +]; + +/** + * name · the object whose read the recorded per-object verdict leaves + * unscoped (`none`; the other is scoped to organization B) · the rows the + * id read answers. Each direction has its own one-sided edit of the + * boundary's comparison that would compose the leaf: a comparison reading + * only the outer read's keys misses the first, only the related read's keys + * the second. + */ +const OPT_DIRECTIONS: ReadonlyArray = [ + ['the outer read is unscoped, the related read scoped', OPT_CASE, ['ok_ab', 'ok_bb']], + ['the outer read is scoped, the related read unscoped', OPT_REGION, ['ok_ba', 'ok_bb']], +]; + +for (const cell of CELLS) { + const config = cell.config(); + describe.skipIf(!config)( + `[#33626] the executor boundary — driver options differ → id read, in both directions — ${cell.label}${config ? '' : ` (skipped: set ${cell.env} to run this cell)`}`, + () => { + let engine: ObjectQL; + let driver: any; + const CALLER_B = { userId: 'u_opt_b', tenantId: OPT_ORG_B }; + // The object a recorded verdict leaves unscoped, per direction. + let unscoped: string | undefined; + + const dropTables = async () => { + if (cell.id === 'sqlite') return; + for (const o of OPT_OBJECTS.map((x) => x.name).reverse()) await driver?.execute(`drop table if exists ${o}`).catch(() => {}); + }; + + beforeAll(async () => { + driver = new SqlDriver(config as any); + await dropTables(); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of OPT_OBJECTS) engine.registry.registerObject(o as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const [object, rows] of OPT_SEED) for (const row of rows) await driver.create(object, { ...row }); + engine.setTenancyPostureProvider(() => 'isolated'); + // A per-object verdict recorded for the request, as the security + // layer records one on each read: the registry cannot predict it, so + // the related read is planned and the boundary compares the options. + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (unscoped !== undefined) { + opCtx.tenantLayer0Verdict = opCtx.object === unscoped ? { kind: 'none' } : { kind: 'organization', organizationId: OPT_ORG_B }; + } + return next(); + }); + }); + + afterAll(async () => { + await dropTables(); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + /** The two-step route as the caller: the region ids, then the cases on them. */ + const twoStep = async (): Promise => { + const regions = (await engine.find(OPT_REGION, { where: { name: 'NA' }, fields: ['id'], context: CALLER_B })).map((r: any) => r.id); + return (await engine.find(OPT_CASE, { where: { region: { $in: regions } }, fields: ['id'], context: CALLER_B })).map((r: any) => r.id).sort(); + }; + + for (const [name, object, rows] of OPT_DIRECTIONS) { + it(`${name}: the related ids are read at the boundary — exactly the two-step route's answer, on find and count`, async () => { + unscoped = object; + try { + const where = { region: { name: 'NA' } }; + const got = (await engine.find(OPT_CASE, { where, context: CALLER_B })).map((r: any) => r.id).sort(); + expect(got, name).toEqual([...rows].sort()); + expect(got, `two-step parity, ${name}`).toEqual(await twoStep()); + expect(await engine.count(OPT_CASE, { where, context: CALLER_B }), `count, ${name}`).toBe(rows.length); + } finally { + unscoped = undefined; + } + }); + } + }, + ); +} diff --git a/packages/rest/src/data-nested-relation-permission.test.ts b/packages/rest/src/data-nested-relation-permission.test.ts index 4d50616dad0..cb14110801d 100644 --- a/packages/rest/src/data-nested-relation-permission.test.ts +++ b/packages/rest/src/data-nested-relation-permission.test.ts @@ -37,6 +37,8 @@ import { installDefaultOrganization } from './default-organization.testkit.js'; const OBJECT = 'rest_nested_perm_ledger'; const OWNER = 'rest_nested_perm_owner'; +/** [#33626] A note on a ledger row: two relationships from the owner. */ +const NOTE = 'rest_nested_perm_note'; const SYS_CTX = { isSystem: true, userId: 'usr_system' }; @@ -63,6 +65,7 @@ const ROWS = [ { id: 'd3', title: 'c', owner: 'u1' }, { id: 'd4', title: 'd', owner: 'u3' }, ]; +const NOTES = [{ id: 'n1', ledger: 'd1' }, { id: 'n2', ledger: 'd2' }, { id: 'n4', ledger: 'd4' }]; function createMockServer() { const noop = () => {}; @@ -118,6 +121,12 @@ describe('[#20802] the nested-relation form reads the related object as the call owner: { name: 'owner', type: 'lookup', reference: OWNER }, }, }, + { + name: NOTE, + label: 'Note', + sharingModel: 'public_read_write', + fields: { ledger: { name: 'ledger', type: 'lookup', reference: OBJECT } }, + }, ], } as never); await engine.syncSchemas(); @@ -150,6 +159,7 @@ describe('[#20802] the nested-relation form reads the related object as the call await engine.insert(OWNER, OWNERS.map((r) => ({ ...r })), { context: SYS_CTX } as never); await engine.insert(OBJECT, ROWS.map((r) => ({ ...r })), { context: SYS_CTX } as never); + await engine.insert(NOTE, NOTES.map((r) => ({ ...r })), { context: SYS_CTX } as never); const protocol = new ObjectStackProtocolImplementation(engine as any); const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); @@ -205,4 +215,31 @@ describe('[#20802] the nested-relation form reads the related object as the call const system = await engine.find(OBJECT, { where: { owner: { region: 'HIDDEN' } }, context: SYS_CTX } as never); expect(idsOf(system)).toEqual(['d4']); }); + + it('an unreadable related record excludes its row under $ne too: the subquery carries the related object\'s row scope', async () => { + // u3 (HIDDEN) satisfies `region != 'NA'`, but the caller cannot read it, + // so d4 is not selected — only d2, whose owner the caller can read. + const res = await query({ owner: { region: { $ne: 'NA' } } }); + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(idsOf(res.body)).toEqual(['d2']); + const system = await engine.find(OBJECT, { where: { owner: { region: { $ne: 'NA' } } }, context: SYS_CTX } as never); + expect(idsOf(system)).toEqual(['d2', 'd4']); + // The same holds through count and aggregate, the analytics verbs. + expect(await engine.count(OBJECT, { where: { owner: { region: { $ne: 'NA' } } }, context: MEMBER_CTX } as never)).toBe(1); + }); + + it('[#33626] two relationships: the second hop carries ITS object\'s row scope and field check — under $ne too', async () => { + // n4 → d4 → u3 (HIDDEN): u3 satisfies `region != 'NA'`, but the caller cannot read it. + const res = await query({ ledger: { owner: { region: { $ne: 'NA' } } } }, NOTE); + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(idsOf(res.body)).toEqual(['n2']); + const system = await engine.find(NOTE, { where: { ledger: { owner: { region: { $ne: 'NA' } } } }, context: SYS_CTX } as never); + expect(idsOf(system)).toEqual(['n2', 'n4']); + expect(await engine.count(NOTE, { where: { ledger: { owner: { region: { $ne: 'NA' } } } }, context: MEMBER_CTX } as never)).toBe(1); + // The unreadable field at the second hop: the same refusal a direct read of the owner answers. + const secret = await query({ ledger: { owner: { secret: 's1' } } }, NOTE); + expect(secret.status, JSON.stringify(secret.body)).toBe(403); + expect(JSON.stringify(secret.body)).toContain('PERMISSION_DENIED'); + expect(secret.body?.records).toBeUndefined(); + }); }); diff --git a/packages/services/service-analytics/src/__tests__/crossobject-conjunct-refusal.test.ts b/packages/services/service-analytics/src/__tests__/crossobject-conjunct-refusal.test.ts index 0eec53b78ed..ec1b313da19 100644 --- a/packages/services/service-analytics/src/__tests__/crossobject-conjunct-refusal.test.ts +++ b/packages/services/service-analytics/src/__tests__/crossobject-conjunct-refusal.test.ts @@ -199,6 +199,17 @@ const MIXED_SCOPED_SALES: Dataset = DatasetSchema.parse({ measures: [{ name: 'revenue', aggregate: 'sum', field: 'amount' }], }) as Dataset; +/** [#33626] A dataset scope this path cannot serve exactly: a cross-object leaf under `$not`. */ +const NEGATED_SCOPED_SALES: Dataset = DatasetSchema.parse({ + name: 'negated_scoped_sales', + label: 'Negated scoped sales', + object: 'opportunity', + include: ['account'], + filter: { $not: { 'account.region': 'West' } }, + dimensions: [{ name: 'stage', field: 'stage', type: 'string' }], + measures: [{ name: 'revenue', aggregate: 'sum', field: 'amount' }], +}) as Dataset; + /** * [commit 399ecad58] ONE dataset carrying all three of ⑦/⑧'s directions, so the * distinctions are structural rather than three fixtures that happen to differ. @@ -514,54 +525,45 @@ describe('[#10759] the #10413-phase-1 dataset filter conjunct is not misread', ( * CARRYING its predicate — dropping the scope silently widens the answer just * as badly as refusing it wrongly narrows the product. */ -describe('[#10861] a CROSS-OBJECT definition-level filter is refused on BOTH doors', () => { - it('execute() refuses with the ADR-0112 envelope, before the engine is asked', async () => { +describe('[#10861, #33626] a CROSS-OBJECT definition-level filter: served as the engine\'s nested-relation condition, refused where it cannot be served exactly', () => { + // [#33626] The card's second door: the dataset's own `filter` takes the + // route the caller's `where` takes (`servedScope`), so the engine receives + // the nested-relation condition and serves it as a read-scoped subquery. + it('execute() hands the engine the relation condition in the leaf\'s place — never the dotted member', async () => { const { execute, calls } = await bothDoors('xobj_scoped_sales', { dimensions: ['stage'], measures: ['revenue'], }, [XOBJ_SCOPED_SALES]); - - expect(execute, 'accepted — the dataset scope was invisible to the envelope check') - .toBeInstanceOf(Error); - // Read exactly as `rest-server.ts`'s catch reads them: a 4xx status AND a - // code, or the route falls through to 500 ANALYTICS_QUERY_FAILED. Asserting - // only that it throws would pass on a bare `Error` and report the platform - // broken for what is a dataset-authoring mistake on this deployment. - expect(execute?.code, 'no `code` ⇒ 500 ANALYTICS_QUERY_FAILED').toBe('INVALID_FIELD'); - expect(execute?.status, 'no `status` ⇒ 500 ANALYTICS_QUERY_FAILED').toBe(400); - // The member as the DATASET spelled it, and the dataset named as the - // document to go and edit. - expect(execute?.member).toBe('account.region'); - expect(execute?.cube).toBe('xobj_scoped_sales'); - expect(String(execute?.message)).toMatch(DATASET_SCOPE_MESSAGE); - // `param` is ABSENT on purpose, and this assertion is the pin on that - // choice rather than an omission nobody noticed. `AnalyticsRequestKey` is - // the analytics REQUEST vocabulary; `AnalyticsQuerySchema` is strict and has - // no `filter` key, and this request carries no `where` at all. Both - // `param: 'where'` and a widened `param: 'filter'` would send the caller to - // a key that does not exist on what they sent. `cube` is the locator that - // does. - expect(execute?.param, '`param` must not name a key the request has no room for') - .toBeUndefined(); - // Refused BEFORE the engine was asked, not after it mis-bucketed. This is - // the assertion the whole card is about: the BEFORE run reached it once, - // carrying `{"$and":[{"account.region":"West"}]}`. - expect(calls, 'engine.aggregate was reached — it cannot join').toEqual([]); + expect(execute, `refused: ${execute?.message}`).toBeUndefined(); + expect(calls).toHaveLength(1); + const sent = JSON.stringify(calls[0].filter); + expect(sent).toContain(RELATION_FORM); + expect(sent, 'the dotted member reached the engine, which cannot join it').not.toContain('account.region'); }); - it('both doors agree', async () => { - const { execute, generateSql } = await bothDoors('xobj_scoped_sales', { + it('the SQL echo refuses the served scope in the where-door envelope, naming the dataset\'s member', async () => { + const { generateSql } = await bothDoors('xobj_scoped_sales', { dimensions: ['stage'], measures: ['revenue'], }, [XOBJ_SCOPED_SALES]); - // One fact about one query, not two independent expectations — the same - // shape ① uses. Two expectations that happen to coincide do not pin an - // invariant BETWEEN two call sites; this does. - expect( - [execute === undefined, generateSql === undefined], - 'the preview and the execution door accept/reject the same set', - ).toEqual([false, false]); - expect(generateSql?.code).toBe('INVALID_FIELD'); - expect(generateSql?.status).toBe(400); - expect(String(generateSql?.message)).toMatch(DATASET_SCOPE_MESSAGE); + expect({ code: generateSql?.code, status: generateSql?.status }).toEqual({ code: 'INVALID_FILTER', status: 400 }); + expect(String(generateSql?.message)).toContain('"account.region"'); + }); + + it('a leaf this path cannot serve exactly (under $not) keeps the dataset-scope refusal on BOTH doors, before the engine', async () => { + const { execute, generateSql, calls } = await bothDoors('negated_scoped_sales', { + dimensions: ['stage'], measures: ['revenue'], + }, [NEGATED_SCOPED_SALES]); + expect([execute === undefined, generateSql === undefined]).toEqual([false, false]); + for (const refusal of [execute, generateSql]) { + // Read exactly as `rest-server.ts`'s catch reads them: a 4xx status AND a code. + expect(refusal?.code).toBe('INVALID_FIELD'); + expect(refusal?.status).toBe(400); + expect(refusal?.member).toBe('account.region'); + expect(refusal?.cube).toBe('negated_scoped_sales'); + expect(String(refusal?.message)).toMatch(DATASET_SCOPE_MESSAGE); + // `param` is ABSENT on purpose: the request has no key that holds the dataset's filter. + expect(refusal?.param).toBeUndefined(); + } + expect(calls, 'engine.aggregate was reached with a negated relation match').toEqual([]); }); it('the still-served neighbour: an ORDINARY dataset scope still reaches the engine carrying its predicate', async () => { @@ -584,16 +586,15 @@ describe('[#10861] a CROSS-OBJECT definition-level filter is refused on BOTH doo ).toContain('is_deleted'); }); - it('a base-object leaf beside a cross-object one in the SAME dataset scope is still refused', async () => { - // The counter-shape for the test above: refusing is not a property of the - // scope having more than one leaf, and serving is not a property of it - // having a base leaf anywhere in it. The cross-object leaf decides. - const { execute, generateSql, calls } = await bothDoors('mixed_scoped_sales', { + it('a base-object leaf beside a cross-object one in the SAME dataset scope: both reach the engine, the base leaf as a column', async () => { + const { execute, calls } = await bothDoors('mixed_scoped_sales', { dimensions: ['stage'], measures: ['revenue'], }, [MIXED_SCOPED_SALES]); - expect([execute === undefined, generateSql === undefined]).toEqual([false, false]); - expect(execute?.member).toBe('account.region'); - expect(calls).toEqual([]); + expect(execute, `refused: ${execute?.message}`).toBeUndefined(); + const sent = JSON.stringify(calls[0]?.filter); + expect(sent).toContain('is_deleted'); + expect(sent).toContain(RELATION_FORM); + expect(sent).not.toContain('account.region'); }); it('the KNOWN-PRESENT control: a cross-object member in the CALLER\u2019s where keeps its own diagnostic', async () => { @@ -849,6 +850,21 @@ describe('[#33335] a one-hop cross-object where leaf reaches the engine as its n }); }); + it('[#33626] two and three relationships deep: each relation holds the next one\'s condition; leaves through one path share it', async () => { + const two = await planRun(planQuery({ 'cb_order.customer.tier': 'gold' })); + expect(two.execute, String(two.execute?.message)).toBeUndefined(); + expect(two.calls[0]?.filter).toEqual({ $and: [{ cb_order: { customer: { tier: 'gold' } } }] }); + const three = await planRun(planQuery({ + 'cb_order.customer.region.name': { $ne: 'EU' }, 'cb_order.customer.region.iso': 'x', 'cb_order.status': 'open', + })); + expect(three.calls[0]?.filter).toEqual({ + $and: [{ cb_order: { customer: { region: { name: { $ne: 'EU' }, iso: 'x' } } } }, { cb_order: { status: 'open' } }], + }); + // The echo refuses in the where-door envelope, spelling the nested form. + expect({ code: three.echo?.code, status: three.echo?.status }).toEqual({ code: 'INVALID_FILTER', status: 400 }); + expect(String(three.echo?.message)).toContain('{ "cb_order": { "customer": { "region": { "name": … } } } }'); + }); + it('a cross-object dimension\'s FK-expand carries the condition on its base aggregate', async () => { const { execute, calls } = await planRun(planQuery({ 'cb_order.region': 'EU' }, { dimensions: ['order_status'] })); expect(execute, String(execute?.message)).toBeUndefined(); @@ -865,7 +881,7 @@ describe('[#33335] a one-hop cross-object where leaf reaches the engine as its n }); const REFUSED: Array<{ name: string; query: AnalyticsQuery; member: string; param: string; echoCode?: string }> = [ - { name: 'two relationships deep', query: planQuery({ 'cb_order.customer.tier': 'gold' }), member: 'cb_order.customer.tier', param: 'where' }, + { name: 'four relationships deep (ADR-0071\'s limit is three)', query: planQuery({ 'cb_order.customer.region.zone.tier': 'gold' }), member: 'cb_order.customer.region.zone.tier', param: 'where' }, { name: 'under $not', query: planQuery({ $not: { 'cb_order.status': 'cancelled' } }), member: 'cb_order.status', param: 'where' }, // The echo declines every `{ $field }` comparand first, in its own // envelope (#7598); the execution face is this card's refusal. diff --git a/packages/services/service-analytics/src/read-scope-sql.ts b/packages/services/service-analytics/src/read-scope-sql.ts index 4a3c9c35a7f..b011efeefba 100644 --- a/packages/services/service-analytics/src/read-scope-sql.ts +++ b/packages/services/service-analytics/src/read-scope-sql.ts @@ -1475,7 +1475,7 @@ function compileField(field: string, value: unknown, qAlias: string, params: unk `which a read scope compiled to SQL cannot serve (fail-closed): the condition is answered by ` + `reading the related object, and this compile reads no other object. The engine serves the ` + `form in a query's where — it reads the related object as the caller, with that object's row ` + - `scope and field permissions, and refuses a match past its cap. In a read scope compiled to SQL, ` + + `scope and field permissions, and keeps the rows whose relation is a record that read admits. In a read scope compiled to SQL, ` + `name the related ids on a single-valued relation: { "${field}": { "$in": [ID, …] } }.`, ); } diff --git a/packages/services/service-analytics/src/strategies/cross-object-where.ts b/packages/services/service-analytics/src/strategies/cross-object-where.ts index 6af890024d2..91042f8ac05 100644 --- a/packages/services/service-analytics/src/strategies/cross-object-where.ts +++ b/packages/services/service-analytics/src/strategies/cross-object-where.ts @@ -14,11 +14,12 @@ * every verb `aggregate` included (`@objectstack/objectql`'s * `relation-filter-lowering.ts`). It reads the related object through the * engine's own `find`, AS THE CALLER — that object's CRUD gate, row scope and - * field permissions apply as they do to a direct read — and matches the - * relation field against the ids the read returns, refusing a match past its - * cap (`RELATION_FILTER_ID_CAP`) rather than truncating it. That is "resolve the - * parent ids first, then filter the base object with `IN`", with the security - * rule in the one place that owns it. This module only respells the member; it + * field permissions apply as they do to a direct read — and keeps the rows + * whose relation field is a record that read admits: a subquery in the same + * statement where that is provably the same read, otherwise the ids the read + * returns, refusing a match past the cap (`RELATION_FILTER_ID_CAP`) rather + * than truncating it. That is "resolve the parent ids first, then filter the + * base object with `IN`", with the security rule in the one place that owns it. This module only respells the member; it * reads no data and judges no permission. * * ## What a lowered leaf means @@ -49,10 +50,12 @@ * A leaf this path cannot serve EXACTLY is left as written, and * `ObjectQLStrategy.planCrossObject` refuses it with the reason recorded here: * - * - **`multi-hop`** — `a.b.field`. The engine's nested-relation form is one - * relationship deep (the related object's own relation fields cannot carry a - * condition), and a second hop resolved here would be a second copy of the - * engine's read, cap and field rule. The hop limit is ONE relationship. + * - **`multi-hop`** — a path past {@link CROSS_OBJECT_WHERE_MAX_HOPS} + * relationships (`a.b.c.d.field`). Up to that limit (ADR-0071's three hops) a + * path is respelled as the nested form one relation inside the next + * (`a.b.field` → `{ a: { b: { field } } }`), which the engine serves hop by + * hop, each hop its related object's own read as the caller; past it the + * engine refuses the nested form too. * - **`negated`** — a leaf under `$not`, at any depth. Negating the existential * test admits every row whose parent is absent or unreadable, so a parent the * caller cannot read would let its children through. The negation belongs @@ -84,6 +87,13 @@ import { findCrossFieldComparand } from '../comparand-shape.js'; import { resolvePathHops, type HopReference } from '../hop-object.js'; import type { Cube } from '@objectstack/spec/data'; +/** + * The most relationships a dotted `where` leaf may traverse and still be + * respelled: ADR-0071's hop limit, the one the engine's nested-relation form + * carries (`@objectstack/objectql`'s `RELATION_CONDITION_MAX_HOPS`). + */ +export const CROSS_OBJECT_WHERE_MAX_HOPS = 3; + /** Why a cross-object `where` leaf is left for the strategy to refuse. */ export type UnservedCrossObjectReason = 'multi-hop' | 'negated' | 'field-reference' | 'join-target'; @@ -95,6 +105,8 @@ export interface ServedCrossObjectLeaf { readonly field: string; /** The relation field of the base object the condition sits beneath. */ readonly relation: string; + /** Every relation field the path traverses, the base object's first (`[relation]` for one hop). */ + readonly path: readonly string[]; /** The related object the hop reads. */ readonly object: string; } @@ -191,7 +203,7 @@ export function lowerCrossObjectWhere( const field = reader.resolveField(key); if (!reader.isCrossObject(field)) continue; const segments = field.split('.'); - if (segments.length > 2) { + if (segments.length - 1 > CROSS_OBJECT_WHERE_MAX_HOPS) { unserved.set(field, { reason: 'multi-hop' }); continue; } @@ -204,29 +216,42 @@ export function lowerCrossObjectWhere( unserved.set(field, { reason: 'field-reference' }); continue; } - const [relation, attr] = segments; - const [hop] = resolvePathHops(reader.cube, reader.baseObject, [relation], reader.referenceOf); - if (hop.via === 'join') { - const declared = reader.referenceOf?.(reader.baseObject, relation); - if (declared !== undefined && declared !== '' && declared !== hop.object) { - unserved.set(field, { reason: 'join-target', joined: hop.object, declared }); - continue; - } + const relations = segments.slice(0, -1); + const attr = segments[segments.length - 1]; + const hops = resolvePathHops(reader.cube, reader.baseObject, relations, reader.referenceOf); + // Every hop the cube joins must join the object its field declares: the + // engine reads the declared reference, hop by hop. + const misjoined = hops.find((h) => { + if (h.via !== 'join') return false; + const declared = reader.referenceOf?.(h.from, h.field); + return declared !== undefined && declared !== '' && declared !== h.object; + }); + if (misjoined) { + unserved.set(field, { + reason: 'join-target', joined: misjoined.object, declared: reader.referenceOf?.(misjoined.from, misjoined.field), + }); + continue; } out ??= { ...cond }; delete out[key]; - const conditions = byRelation.get(hop.field) ?? []; + // One condition per relation PATH: leaves through the same relations + // share the record at its end (`a.b.x` and `a.b.y` are one `b` with both). + const pathKey = relations.join('.'); + const conditions = byRelation.get(pathKey) ?? []; const open = conditions.find((c) => !Object.prototype.hasOwnProperty.call(c, attr)); if (open) open[attr] = spec; else conditions.push({ [attr]: spec }); - byRelation.set(hop.field, conditions); - served.push({ member: key, field, relation: hop.field, object: hop.object }); + byRelation.set(pathKey, conditions); + served.push({ member: key, field, relation: hops[0].field, path: relations, object: hops[0].object }); } if (byRelation.size === 0) return out ?? cond; - const relationConditions = [...byRelation].flatMap(([relation, conditions]) => - conditions.map((condition) => ({ [relation]: condition })), + // `a.b` → `{ a: { b: CONDITION } }`: each relation holds the next one's condition. + const nest = (path: string, condition: Record): Record => + path.split('.').reduceRight>((inner, relation) => ({ [relation]: inner }), condition); + const relationConditions = [...byRelation].flatMap(([path, conditions]) => + conditions.map((condition) => nest(path, condition)), ); const result = out ?? { ...cond }; const prior = result.$and; diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index 7d8be55d570..eeae9e160c9 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -38,8 +38,10 @@ import { invalidMemberError } from '../dataset-refusal.js'; // A cross-object `where` leaf, served as the engine's nested-relation condition. import { CROSS_OBJECT_JOIN_ROUTE, + CROSS_OBJECT_WHERE_MAX_HOPS, lowerCrossObjectWhere, type CrossObjectWhereLowering, + type CrossObjectWhereReader, type ServedCrossObjectLeaf, type UnservedCrossObjectLeaf, } from './cross-object-where.js'; @@ -271,8 +273,9 @@ function unservedCrossObjectFilterRefused(field: string, leaf: UnservedCrossObje switch (leaf.reason) { case 'multi-hop': why = - `: it traverses ${field.split('.').length - 1} relationships, and ${served}, one relationship ` + - `deep. Filter on a field of the first related object instead, or remove the filter.`; + `: it traverses ${field.split('.').length - 1} relationships, and ${served}, up to ` + + `${CROSS_OBJECT_WHERE_MAX_HOPS} relationships deep (ADR-0071's hop limit). Filter on a field ` + + `at most ${CROSS_OBJECT_WHERE_MAX_HOPS} relationships away instead, or remove the filter.`; break; case 'negated': why = @@ -304,13 +307,15 @@ function unservedCrossObjectFilterRefused(field: string, leaf: UnservedCrossObje * caller wrote. */ function crossObjectEchoRefused(leaf: ServedCrossObjectLeaf): Error { - const attr = leaf.field.split('.').slice(1).join('.'); + const segments = leaf.field.split('.'); + const nested = segments.reduceRight( + (inner, key, i) => (i === segments.length - 1 ? `{ "${key}": … }` : `{ "${key}": ${inner} }`), '', + ); return invalidFilterError( `[analytics] cannot render display SQL for the cross-object filter "${leaf.member}". The query ` + - `itself is answered by the engine, as the nested-relation condition { "${leaf.relation}": ` + - `{ "${attr}": … } }: it reads "${leaf.object}" as the caller, with that object's row scope and ` + - `field permissions, and matches "${leaf.relation}" against the ids it returns, refusing a match ` + - `past its cap. No statement printed here reproduces that read. Run the query itself ` + + `itself is answered by the engine, as the nested-relation condition ${nested}: it reads "${leaf.object}" as the caller, with that object's row scope and ` + + `field permissions, and keeps the rows whose "${leaf.relation}" is a record that read admits. ` + + `No statement printed here reproduces that read. Run the query itself ` + `(/analytics/query) for its rows.`, ); } @@ -589,6 +594,8 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // nested-relation condition it serves (`cross-object-where.ts`); a leaf this // path cannot serve exactly stays dotted, for `planCrossObject` to refuse. const served = this.servedWhere(cube, query, ctx); + // [#33626] …and the dataset's own `filter` alike. + const servedScope = this.servedScope(cube, query, ctx); this.applyFilterNode(normalizeAnalyticsFilterTree(served.query, lowering), cube, filter, conjuncts); // #3650 — and the time-dimension WINDOWS, through the SAME merge, so a // `dateRange` and a caller `where` bound on one field compose instead of @@ -625,11 +632,11 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // folding a measure filter into THIS whole-call filter instead would // narrow EVERY measure, trading a wrong `won_count` for a wrong // `opp_count` as well. - if (datasetScope?.filter) { + if (servedScope.filter) { // `null` = constrains nothing, which is the AND identity — nothing to add, // and nothing invented for a filter that says nothing. const scopeCondition = this.filterNodeToCondition( - normalizeAnalyticsFilterTree({ where: datasetScope.filter }, lowering), + normalizeAnalyticsFilterTree({ where: servedScope.filter }, lowering), cube, ); if (scopeCondition) conjuncts.push(scopeCondition); @@ -640,7 +647,8 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // #3654 — classify cross-object references. A cross-object DIMENSION within // the supported envelope is served by an FK-expand (`executeCrossObject`); - // a one-hop cross-object `where` leaf already reached `filter` as the + // a cross-object `where` leaf of up to three hops (and the dataset's own + // `filter`'s, #33626) already reached `filter` as the // engine's nested-relation condition (`servedWhere`, above); everything the // engine cannot serve (cross-object measures, a `where` leaf `servedWhere` // left dotted, multi-hop, non-recombinable measures) is REJECTED by `planCrossObject` — @@ -660,7 +668,7 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // with a predicate the engine cannot join and silently mis-bucketed it, // which is the exact outcome #3654's loud refusal exists to prevent. const plan = this.planCrossObject( - cube, query, this.filterMemberView(cube, served.query, ctx), relationshipReferenceOf(ctx), served.lowering.unserved, + cube, query, this.filterMemberView(cube, served.query, ctx, servedScope.filter), relationshipReferenceOf(ctx), served.lowering.unserved, ); if (plan) { return this.executeCrossObject(cube, query, aggregations, filter, plan, ctx); @@ -875,8 +883,9 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // The same respelling of a cross-object `where` leaf `execute()` makes, so // both faces judge one member view. const served = this.servedWhere(cube, query, ctx); + const servedScope = this.servedScope(cube, query, ctx); const plan = this.planCrossObject( - cube, query, this.filterMemberView(cube, served.query, ctx), relationshipReferenceOf(ctx), served.lowering.unserved, + cube, query, this.filterMemberView(cube, served.query, ctx, servedScope.filter), relationshipReferenceOf(ctx), served.lowering.unserved, ); // Read once, reused below for both the per-measure conditional aggregate // (#10413 phase 2) and the dataset-scope WHERE conjunct (#10413 phase 1) — @@ -1048,6 +1057,7 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // has no statement here that reproduces it: refused, as the authored // nested-relation form is below, in words that name the dotted member. if (served.lowering.served.length > 0) throw crossObjectEchoRefused(served.lowering.served[0]); + if (servedScope.served.length > 0) throw crossObjectEchoRefused(servedScope.served[0]); // Recursive, so the echoed statement carries the same disjunctions the // engine filter does — the echo exists to REPRODUCE execution, and an // `$or` rendered as a conjunction (or dropped) is exactly the lie this @@ -1275,17 +1285,43 @@ export class ObjectQLStrategy implements AnalyticsStrategy { query: AnalyticsQuery, ctx: StrategyContext, ): { query: AnalyticsQuery; lowering: CrossObjectWhereLowering } { + const lowering = lowerCrossObjectWhere(lowerAnalyticsWhere(query), this.crossObjectWhereReader(cube, ctx)); + if (lowering.served.length === 0) return { query, lowering }; + return { query: { ...query, where: lowering.where } as AnalyticsQuery, lowering }; + } + + /** + * [#33626] The compiled dataset's OWN definition-level `filter`, with its + * servable cross-object leaves respelled exactly as {@link servedWhere} + * respells the caller's: the engine then serves each as its nested-relation + * condition (a read-scoped subquery on a SQL driver). `filter` is the scope + * as declared when nothing was respelled (or `undefined` when the cube is not + * a compiled dataset or declares none); a leaf left dotted keeps the + * dataset-filter refusal in {@link planCrossObject}. + */ + private servedScope( + cube: Cube, + query: AnalyticsQuery, + ctx: StrategyContext, + ): { filter: unknown; served: readonly ServedCrossObjectLeaf[] } { + const declared = (ctx as DatasetScopedStrategyContext).getDatasetScope?.(query.cube!)?.filter; + if (!declared) return { filter: declared, served: [] }; + const lowering = lowerCrossObjectWhere(lowerAnalyticsWhere({ where: declared }), this.crossObjectWhereReader(cube, ctx)); + if (lowering.served.length === 0) return { filter: declared, served: [] }; + return { filter: lowering.where, served: lowering.served }; + } + + /** What {@link lowerCrossObjectWhere} reads a member through, on this cube. */ + private crossObjectWhereReader(cube: Cube, ctx: StrategyContext): CrossObjectWhereReader { const baseObject = this.extractObjectName(cube); const referenceOf = relationshipReferenceOf(ctx); - const lowering = lowerCrossObjectWhere(lowerAnalyticsWhere(query), { + return { cube, baseObject, referenceOf, resolveField: (member) => this.resolveFieldName(cube, member, 'any'), isCrossObject: (field) => this.isCrossObjectField(cube, field, baseObject, referenceOf), - }); - if (lowering.served.length === 0) return { query, lowering }; - return { query: { ...query, where: lowering.where } as AnalyticsQuery, lowering }; + }; } /** @@ -1395,6 +1431,8 @@ export class ObjectQLStrategy implements AnalyticsStrategy { cube: Cube, query: AnalyticsQuery, ctx: StrategyContext, + // [#33626] The dataset `filter` as the engine receives it ({@link servedScope}). + scopeFilter: unknown, ): Record { // Read from the SAME channel both doors lower the scope from, so the view // and the predicate cannot disagree about what the engine will receive. @@ -1419,8 +1457,8 @@ export class ObjectQLStrategy implements AnalyticsStrategy { }); return Object.fromEntries([ ...measureLeaves, - ...(datasetScope?.filter - ? leaves(normalizeAnalyticsFilterTree({ where: datasetScope.filter }, NO_DATETIME_COLUMNS), { kind: 'dataset-filter' }) + ...(scopeFilter + ? leaves(normalizeAnalyticsFilterTree({ where: scopeFilter }, NO_DATETIME_COLUMNS), { kind: 'dataset-filter' }) : []), ...leaves(normalizeAnalyticsFilterTree(query, NO_DATETIME_COLUMNS), { kind: 'where' }), ]); @@ -2260,16 +2298,16 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // [#20887] The echo DECLINES the nested-relation form, the way it // declines a cross-field comparison (#7598's echo ruling: one consistent, // loud answer, never a half-rendering). What runs is a read of the - // related object as the caller, then a match against the ids it - // returned; no statement this renderer can print reproduces that — a - // JOIN would name rows the caller's field permissions and the engine's - // cap never let through. `execute()` swallows the echo's refusal, so the + // related object as the caller, then a match against what that read + // admits; no statement this renderer can print reproduces that — a + // JOIN would name rows the caller's read restrictions on the related + // object never let through. `execute()` swallows the echo's refusal, so the // query face still answers; only the dry-run face refuses. throw invalidFilterError( `[analytics] cannot render display SQL for the nested-relation condition on "${node.member}" ` + `({ "${node.member}": { … } }). The query itself is answered by the engine: it reads the ` + `related object as the caller, with that object's row scope and field permissions, and ` + - `matches "${node.member}" against the ids it returns, refusing a match past its cap. No ` + + `keeps the rows whose "${node.member}" is a record that read admits. No ` + `statement printed here reproduces that read. Run the query itself (/analytics/query) for ` + `its rows.`, );