From f2db463d99a1161b956a70b9466c34412eb7ffb6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:03:47 +0000 Subject: [PATCH 01/25] wip(objectql): serve a single-valued nested-relation condition as an in-database semi-join Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- packages/objectql/src/engine-find.ts | 13 +- .../objectql/src/engine-query-lowering.ts | 35 ++++- .../engine-readable-ids-permission-formula.ts | 11 ++ packages/objectql/src/engine.ts | 1 + .../objectql/src/relation-filter-lowering.ts | 21 +++ packages/objectql/src/relation-semi-join.ts | 123 ++++++++++++++++++ 6 files changed, 202 insertions(+), 2 deletions(-) create mode 100644 packages/objectql/src/relation-semi-join.ts diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 3ff00370cb8..b01c05517a7 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 RelationScopePlanSink } 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'; @@ -546,6 +547,16 @@ export class FindFacet { // 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); + // [relation semi-join] A PLANNED read (`relation-semi-join.ts`): the + // final `where` is handed to the planner in place of the driver call, + // and the read answers no rows. Only the engine's own nested-relation + // lowering sets this symbol-keyed option. + const planSink = (options as Record | undefined)?.[RELATION_SCOPE_PLAN]; + if (typeof planSink === 'function') { + (planSink as RelationScopePlanSink)(driverAst.where as FilterCondition | undefined); + opCtx.result = []; + return opCtx.result; + } try { let result = await driver.find(object, driverAst, driverOptions); diff --git a/packages/objectql/src/engine-query-lowering.ts b/packages/objectql/src/engine-query-lowering.ts index 9ca33694539..c50e98d5dde 100644 --- a/packages/objectql/src/engine-query-lowering.ts +++ b/packages/objectql/src/engine-query-lowering.ts @@ -69,8 +69,11 @@ import { lowerRelationSite, RELATION_FILTER_ID_CAP, relationFilterCapError, + relationSemiJoinDatasourceError, type RelationReplacement, } from './relation-filter-lowering.js'; +import { planRelationSemiJoinLeaf, RELATION_SCOPE_PLAN } 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 +93,7 @@ export interface QueryLoweringHost { readonly [SECURITY_SERVICE_SOURCE_SLOT]: unknown; resolveRelateThenLowerWhere: ObjectQL['resolveRelateThenLowerWhere']; find: ObjectQL['find']; + resolveDatasourceBinding: ObjectQL['resolveDatasourceBinding']; } /** @@ -181,8 +185,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, @@ -195,6 +207,27 @@ export async function lowerRelationConditions( const context = `${operation}('${object}')`; const replacements: RelationReplacement[] = []; for (const site of sites) { + if (!site.multiple && SEMI_JOIN_READ_VERBS.has(operation)) { + // [relation semi-join] A single-valued relation: the related read is + // 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 (`relation-semi-join.ts`). + const objectDatasource = this.resolveDatasourceBinding(object)?.datasource; + const targetDatasource = this.resolveDatasourceBinding(site.target)?.datasource; + if (objectDatasource !== targetDatasource) { + throw relationSemiJoinDatasourceError(site, context, objectDatasource, targetDatasource); + } + const leaf = await planRelationSemiJoinLeaf(site.target, (sink) => this.find( + site.target, + { where: site.condition as FilterCondition, fields: ['id'], ...(execCtx ? { context: execCtx } : {}) }, + { [RELATION_SCOPE_PLAN]: sink } as EngineReadOptions, + )); + 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: its condition is still matched against the ids + // the related read returns, under the cap. const rows = await this.find(site.target, { where: site.condition as FilterCondition, fields: ['id'], diff --git a/packages/objectql/src/engine-readable-ids-permission-formula.ts b/packages/objectql/src/engine-readable-ids-permission-formula.ts index 34d88be6d08..e8fe10d167d 100644 --- a/packages/objectql/src/engine-readable-ids-permission-formula.ts +++ b/packages/objectql/src/engine-readable-ids-permission-formula.ts @@ -64,6 +64,7 @@ * stays on the class, the contract, and its function keeps the placeholder. */ +import { plannedRelationScopeOf } from './relation-semi-join.js'; import { ReadableIds, RLS_DENY_FILTER, controlledByParentMasterOf, markFilterSubtreeProvenance } from '@objectstack/spec/data'; import type { FilterCondition } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -162,7 +163,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) => plannedRelationScopeOf(s.leaf) === undefined).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]; @@ -203,6 +212,8 @@ export async function composeReadableIdsChain( // A parent with no answer (`null`, or never asked: not registered) is // `$in: []`. return composeReadableIdsLeaves(node, (leaf) => { + const planned = plannedRelationScopeOf(leaf); + if (planned !== undefined) return planned ? 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.ts b/packages/objectql/src/engine.ts index 448cd2035da..5887c41ea31 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4250,6 +4250,7 @@ export class ObjectQL implements IObjectQLEngine { get _registry() { return readRegistry(); }, get relatedSchemaOf() { return readRelatedSchemaOf(); }, find: (...a) => this.find(...a), + resolveDatasourceBinding: (...a) => this.resolveDatasourceBinding(...a), }; return (lowerRelationConditions).call(host, object, operation, where, execCtx); } diff --git a/packages/objectql/src/relation-filter-lowering.ts b/packages/objectql/src/relation-filter-lowering.ts index 2f1d2a495ff..e02d1b32d88 100644 --- a/packages/objectql/src/relation-filter-lowering.ts +++ b/packages/objectql/src/relation-filter-lowering.ts @@ -315,3 +315,24 @@ export function relationFilterCapError(site: RelationFilterSite, context: string + `page by page and match '${site.field}' against its ids: ${idsRoute(site.field, site.multiple)}.`, ); } + +/** + * The cross-datasource refusal for a single-valued relation condition: it is + * served as a subquery inside the read's own statement + * (`relation-semi-join.ts`), and no driver evaluates a subquery across two + * datasources — `INVALID_FILTER` / 400, before anything is read. + */ +export function relationSemiJoinDatasourceError( + site: RelationFilterSite, + context: string, + objectDatasource: string | undefined, + targetDatasource: string | undefined, +): Error { + return invalidFilterError( + `${context}: the nested-relation condition at ${site.path} is on the related object '${site.target}', ` + + `bound to datasource '${String(targetDatasource)}', while this read's object is bound to ` + + `'${String(objectDatasource)}'. The condition is evaluated as a subquery inside this read's own ` + + `statement, and no driver evaluates a subquery across two datasources, so the filter was NOT applied. ` + + `Read '${site.target}' yourself and match '${site.field}' against its ids: ${idsRoute(site.field, site.multiple)}.`, + ); +} diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts new file mode 100644 index 00000000000..dd67672c076 --- /dev/null +++ b/packages/objectql/src/relation-semi-join.ts @@ -0,0 +1,123 @@ +// 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 plannedRelationScopeOf}), never by asking the security service a + * second, narrower question — so a related record is in the subquery exactly + * when a direct read of the related object with this condition would return + * it. The tenant wall is the driver's own, applied to the related table with + * the outer read's options (ADR-0139 D3). + * + * ## 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. + * - **The related read stopped before its driver call** (a middleware that + * answered without asking the driver): nothing was planned, and the leaf is + * answered `$in: []` — FALSE, fail-closed, ⛔ never "no restriction". + * - **The related object lives on another datasource** than the read's + * object: refused by name before anything runs — no driver evaluates a + * subquery across two datasources. + * + * ## Who evaluates the leaf + * + * The composed leaf is ADR-0139's: `driver-sql` (every dialect) and Turso + * compile it into a nested subquery; `driver-memory` evaluates it in + * process; a driver that compiles no such leaf (`driver-mongodb`, + * `driver-odata`) refuses it with its ADR-0139 D3 refusal. There is no + * staged id-read fallback for those drivers. + * + * ## 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'; + +/** + * The key of the internal read option that turns a `find` into a PLAN: when + * `options[RELATION_SCOPE_PLAN]` holds a function, `find` calls it with the + * final driver `where` in place of the driver call and answers `[]`. + * 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'); + +/** The sink a planned read hands its final driver `where` to. */ +export type RelationScopePlanSink = (where: FilterCondition | undefined) => void; + +/** What a planned related read answered for one leaf. */ +interface PlannedRelationScope { + /** `true` once the related read reached its driver call. */ + readonly planned: boolean; + /** The captured `where` (meaningful only when {@link planned}). */ + readonly where: FilterCondition | undefined; +} + +const plannedScopes = new WeakMap(); + +/** + * Build the `ReadableIds` leaf over `target` whose scope is the planned + * related read's `where`. `plan(sink)` runs that read, handing `sink` to it as + * the {@link RELATION_SCOPE_PLAN} option; a refusal from it propagates. + */ +export async function planRelationSemiJoinLeaf( + target: string, + plan: (sink: RelationScopePlanSink) => Promise, +): Promise> { + let planned = false; + let where: FilterCondition | undefined; + await plan((final) => { + planned = true; + where = final; + }); + const leaf = ReadableIds.of(target); + plannedScopes.set(leaf, { planned, where }); + return leaf; +} + +/** + * The scope the executor boundary composes `leaf` with when this module built + * it: `{ scope }` (possibly `undefined`, no restriction beyond the tenant + * wall — never the case for a non-empty condition), or `null` for `$in: []` + * (nothing was planned, or the planned read was the deny sentinel). + * `undefined` when this module did not build `leaf`: an ordinary ADR-0139 + * leaf, composed through the security service. + */ +export function plannedRelationScopeOf( + leaf: unknown, +): { readonly scope: FilterCondition | undefined } | null | undefined { + if (leaf === null || typeof leaf !== 'object') return undefined; + const entry = plannedScopes.get(leaf); + if (entry === undefined) return undefined; + if (!entry.planned || entry.where === (RLS_DENY_FILTER as unknown)) return null; + return { scope: entry.where }; +} From 878e2743b318864f6692b16a68d9b1483aa5d8a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:07:31 +0000 Subject: [PATCH 02/25] test(objectql): pin the semi-join lowering of a single-valued nested-relation condition Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../engine-nested-relation-lowering.test.ts | 100 +++++++++++------- 1 file changed, 62 insertions(+), 38 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index ea6bb834d14..021ed408848 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 } 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'; @@ -103,6 +104,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,19 +149,20 @@ 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 } } }); } }); @@ -163,33 +177,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 +226,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 +247,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,25 +289,24 @@ 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 ──────────────────────────────────── From 3ef758f86d63f4c532ed848714754069d50b8c8e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:13:42 +0000 Subject: [PATCH 03/25] test(rest): semi-join parity, $ne under row scope, and the lifted single-valued cap at the public doors Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../analytics-nested-relation-filter.test.ts | 10 +++++++--- .../rest/src/data-nested-object-door.test.ts | 19 +++++++++++++------ .../data-nested-relation-permission.test.ts | 12 ++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/packages/rest/src/analytics-nested-relation-filter.test.ts b/packages/rest/src/analytics-nested-relation-filter.test.ts index d9016fe8bdd..74be84134b6 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 }], ]; @@ -484,15 +485,18 @@ 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('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..e5f02aca2d0 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -124,6 +124,10 @@ 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 +298,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); diff --git a/packages/rest/src/data-nested-relation-permission.test.ts b/packages/rest/src/data-nested-relation-permission.test.ts index 4d50616dad0..3e79b206edc 100644 --- a/packages/rest/src/data-nested-relation-permission.test.ts +++ b/packages/rest/src/data-nested-relation-permission.test.ts @@ -205,4 +205,16 @@ 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); + }); }); From aa6187f1a452ca68292f1cbdab26b7b1b362bd5b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:21:57 +0000 Subject: [PATCH 04/25] docs(objectql): describe the semi-join form of a nested-relation condition, where the cap still applies, and add the changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .changeset/33626-relation-semi-join.md | 9 +++++++ content/docs/kernel/contracts/data-engine.mdx | 14 +++++++---- .../docs/protocol/objectql/query-syntax.mdx | 24 +++++++++++++++---- .../objectql/src/engine-query-lowering.ts | 13 ++++++---- .../objectql/src/relation-filter-lowering.ts | 7 +++++- 5 files changed, 53 insertions(+), 14 deletions(-) create mode 100644 .changeset/33626-relation-semi-join.md diff --git a/.changeset/33626-relation-semi-join.md b/.changeset/33626-relation-semi-join.md new file mode 100644 index 00000000000..60c6cd3aa3f --- /dev/null +++ b/.changeset/33626-relation-semi-join.md @@ -0,0 +1,9 @@ +--- +'@objectstack/objectql': patch +--- + +feat(objectql): on a read verb, a single-valued nested-relation condition is one in-database subquery, read-scoped on the related object, with no id cap + +Clause-②: yes (widening; narrowing on a related object another datasource holds, and on a driver that compiles no subquery) — 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, where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller (CRUD gate, read middlewares including row scope and the filter-oracle guard on the condition's fields, `beforeFind` hooks, comparand doors) and its final `where` becomes the scope of a `ReadableIds` leaf the driver compiles into `field IN (SELECT id …)` with its tenant wall; a related record the caller cannot read is in no subquery, so it never matches, `$ne` included. Narrowing: a single-valued condition on a related object bound to another datasource than the read's object now answers `INVALID_FILTER` / 400 naming both datasources, where the id read served it; on a driver that compiles no `ReadableIds` leaf (MongoDB, OData) the read is refused with that driver's ADR-0139 refusal, where the id read served it. A multi-valued relation and the `update` / `delete` verbs keep the id read and its cap. +Metadata-protocol: none +Skills-docs: `content/docs/protocol/objectql/query-syntax.mdx` and `content/docs/kernel/contracts/data-engine.mdx` describe the subquery, where the cap still applies and which drivers compile it. `skills/objectstack-query` still says "up to 1000 related ids" for every relation; that holds for a multi-valued one and is now stricter than the engine for a single-valued one on a read verb (left for a skills-only change). diff --git a/content/docs/kernel/contracts/data-engine.mdx b/content/docs/kernel/contracts/data-engine.mdx index 2ae51b1765d..242f38a810d 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -193,14 +193,20 @@ 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 (the related read is planned, not run: its +read scope, the condition and the tenant wall become the subquery's `WHERE`, so no id list +is read and none is capped); 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 +are refused), and 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 subquery needs the related object on the read's +datasource and a driver that compiles it (the SQL drivers; the in-memory driver evaluates it +in process; MongoDB and OData refuse it). For either, run the two steps yourself — filter the related object, then match its ids: ```typescript diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index 45e05ca391b..257967f04c2 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -688,23 +688,37 @@ 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`). +related object with it **as the caller**. On a read verb (`find`, `findOne`, +`count`, `aggregate`) a single-valued relation is matched in the database: the +related read is planned, not run, and the driver receives one statement with a +subquery, `account IN (SELECT id FROM account WHERE AND +)`, with the tenant wall on both tables — no id list, no cap. +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 — 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` 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 needs the related +object on the same datasource (refused `INVALID_FILTER` / 400 otherwise) and a +driver that compiles it — the SQL drivers (every `driver-sql` dialect, Turso) +compile it, the in-memory driver evaluates it in process, and a driver that +compiles no subquery (MongoDB, OData) refuses the read; 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. - **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 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 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. - **A second level is refused.** `{ account: { owner: { region: 'NA' } } }` and `{ account: { 'owner.region': 'NA' } }` answer `INVALID_FILTER` / 400. - **The reverse direction is not served.** A parent filtered by its children is not diff --git a/packages/objectql/src/engine-query-lowering.ts b/packages/objectql/src/engine-query-lowering.ts index c50e98d5dde..ff93bb16878 100644 --- a/packages/objectql/src/engine-query-lowering.ts +++ b/packages/objectql/src/engine-query-lowering.ts @@ -177,10 +177,15 @@ 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 - * {@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. + * **A subquery where it can be, bounded where it cannot.** On a read verb a + * single-valued relation's related read is 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 (`relation-semi-join.ts`; a + * related object on another datasource is refused by name). A multi-valued + * relation, or a write verb's `where`, reads the ids: 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. * * Returns `where` by reference when it holds no condition — the common path * reads nothing and allocates nothing beyond one walk. diff --git a/packages/objectql/src/relation-filter-lowering.ts b/packages/objectql/src/relation-filter-lowering.ts index e02d1b32d88..c0b0be42cd0 100644 --- a/packages/objectql/src/relation-filter-lowering.ts +++ b/packages/objectql/src/relation-filter-lowering.ts @@ -27,7 +27,12 @@ * 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.** 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 + * (`relation-semi-join.ts`): no id list, so none of the bound below. + * - **Bounded, loudly, where ids are read** (a multi-valued relation, a write + * verb). 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. From bc5ef48640785272dc6804b27ef992cdd20234a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:50:14 +0000 Subject: [PATCH 05/25] test(objectql): the conformance stub driver evaluates a composed ReadableIds leaf in process Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../src/query-expression-conformance.test.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) 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(); From e96278a6b2d9442f46856ce1e687cf770568b1d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:57:08 +0000 Subject: [PATCH 06/25] feat(objectql): a nested-relation condition reaches up to three relationships, each hop its related object's planned read Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../engine-nested-relation-lowering.test.ts | 51 ++++++++++++++++-- ...elation-condition-prescription-cap.test.ts | 13 +++-- .../objectql/src/relation-filter-lowering.ts | 54 +++++++++++++------ 3 files changed, 92 insertions(+), 26 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 021ed408848..16e865ba1ce 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -166,6 +166,48 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se } }); + 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' } } } } }, + { owner: { $in: owner({ region: 'NA', account: { $in: ledger({ owner: { $in: owner({ 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({ @@ -311,11 +353,12 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se // ── 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, which a condition does not follow"], [{ 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"], 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 c0b0be42cd0..6b78a600a25 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 @@ -88,6 +92,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. */ @@ -110,7 +122,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 { @@ -123,9 +135,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; } @@ -160,9 +172,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, @@ -170,6 +185,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); @@ -199,7 +215,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 } }; @@ -288,14 +308,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, which a condition does not follow: 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}.` ); } From 0e78945b6a4ae9602354f4e577eabeb47e5574a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:03:05 +0000 Subject: [PATCH 07/25] test(rest): three-hop nested-relation parity, NULL / missing parent / $ne, and the second hop's read scope Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- content/docs/kernel/contracts/data-engine.mdx | 8 +- .../docs/protocol/objectql/query-syntax.mdx | 13 +- .../engine-nested-relation-lowering.test.ts | 5 +- .../number-comparand-declared-type-door.ts | 4 +- .../objectql/src/relation-filter-lowering.ts | 2 +- .../rest/src/data-nested-object-door.test.ts | 128 +++++++++++++++++- .../data-nested-relation-permission.test.ts | 25 ++++ 7 files changed, 171 insertions(+), 14 deletions(-) diff --git a/content/docs/kernel/contracts/data-engine.mdx b/content/docs/kernel/contracts/data-engine.mdx index 242f38a810d..140431d69fb 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -200,9 +200,11 @@ is read and none is capped); otherwise `$in` on the ids that read returns, any m 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 where ids are read (a multi-valued relation, `update`, `delete`) a +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 subquery needs the related object on the read's datasource and a driver that compiles it (the SQL drivers; the in-memory driver evaluates it diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index 257967f04c2..ba5fab8cc8e 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -697,8 +697,10 @@ 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 — 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` +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; where ids are read, at most 1000 of them, refused past that, `INVALID_FILTER` / 400, never truncated; the subquery form needs the related @@ -719,8 +721,11 @@ never an empty result. - **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. -- **A second level is refused.** `{ account: { owner: { region: 'NA' } } }` and - `{ account: { 'owner.region': 'NA' } }` answer `INVALID_FILTER` / 400. +- **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-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 16e865ba1ce..de15f37385a 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -175,7 +175,8 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se // 3 hops, a sibling key beside the inner relation at the middle hop [ { owner: { region: 'NA', account: { owner: { region: { $ne: 'EU' } } } } }, - { owner: { $in: owner({ region: 'NA', account: { $in: ledger({ owner: { $in: 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 [ @@ -358,7 +359,7 @@ describe('[#20802] the nested-relation form is lowered at the engine\'s where se [{ 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, which a condition does not follow"], + [{ 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"], 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/relation-filter-lowering.ts b/packages/objectql/src/relation-filter-lowering.ts index 6b78a600a25..005a6d1e5a0 100644 --- a/packages/objectql/src/relation-filter-lowering.ts +++ b/packages/objectql/src/relation-filter-lowering.ts @@ -308,7 +308,7 @@ export function relationConditionRefusalMessage(refusal: RelationConditionRefusa ); case 'dotted-key': return ( - `${head}, and '${key}' is a dotted path, which a condition does not follow: nest each relation ` + `${head}, and '${key}' is a dotted path: nest each relation ` + `instead, or read ${named} with that condition, ${twoStep} ${verdict}` ); case 'hop-limit': diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index e5f02aca2d0..eb917c4c88f 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 @@ -128,6 +128,10 @@ const SERVED: 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); + }); + }, + ); +} diff --git a/packages/rest/src/data-nested-relation-permission.test.ts b/packages/rest/src/data-nested-relation-permission.test.ts index 3e79b206edc..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); @@ -217,4 +227,19 @@ describe('[#20802] the nested-relation form reads the related object as the call // 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(); + }); }); From 7ea2601425f85b676b8fc9feed044c8a5fc372a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:08:23 +0000 Subject: [PATCH 08/25] feat(service-analytics): a dotted where leaf up to three relationships, and the dataset's own filter, reach the engine as its nested-relation condition Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../crossobject-conjunct-refusal.test.ts | 116 ++++++++++-------- .../src/strategies/cross-object-where.ts | 60 ++++++--- .../src/strategies/objectql-strategy.ts | 67 +++++++--- 3 files changed, 160 insertions(+), 83 deletions(-) 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..7753b695924 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.code': 'x', 'cb_order.status': 'open', + })); + expect(three.calls[0]?.filter).toEqual({ + $and: [{ cb_order: { customer: { region: { name: { $ne: 'EU' }, code: '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/strategies/cross-object-where.ts b/packages/services/service-analytics/src/strategies/cross-object-where.ts index 6af890024d2..77c0762685b 100644 --- a/packages/services/service-analytics/src/strategies/cross-object-where.ts +++ b/packages/services/service-analytics/src/strategies/cross-object-where.ts @@ -49,10 +49,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 +86,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 +104,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 +202,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 +215,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..fc7e696c7a4 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,11 +307,13 @@ 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 ` + + `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 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 ` + `(/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); @@ -660,7 +667,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 +882,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 +1056,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 +1284,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 +1430,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 +1456,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' }), ]); From f4738f57efaed134a8dde89f1a146d91b12ece2e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:11:34 +0000 Subject: [PATCH 09/25] docs(service-analytics): the served where and dataset filter reach three relationships; changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .changeset/33626-relation-semi-join.md | 7 +++-- .../analytics-nested-relation-filter.test.ts | 31 ++++++++++++++++--- .../src/strategies/objectql-strategy.ts | 3 +- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/.changeset/33626-relation-semi-join.md b/.changeset/33626-relation-semi-join.md index 60c6cd3aa3f..8d36fc60745 100644 --- a/.changeset/33626-relation-semi-join.md +++ b/.changeset/33626-relation-semi-join.md @@ -1,9 +1,10 @@ --- '@objectstack/objectql': patch +'@objectstack/service-analytics': patch --- -feat(objectql): on a read verb, a single-valued nested-relation condition is one in-database subquery, read-scoped on the related object, with no id cap +feat(objectql): a nested-relation condition on a read verb is an in-database subquery per relationship, up to three relationships, each read-scoped on its own object, with no id cap; analytics serves the dataset's own `filter` the same way -Clause-②: yes (widening; narrowing on a related object another datasource holds, and on a driver that compiles no subquery) — 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, where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller (CRUD gate, read middlewares including row scope and the filter-oracle guard on the condition's fields, `beforeFind` hooks, comparand doors) and its final `where` becomes the scope of a `ReadableIds` leaf the driver compiles into `field IN (SELECT id …)` with its tenant wall; a related record the caller cannot read is in no subquery, so it never matches, `$ne` included. Narrowing: a single-valued condition on a related object bound to another datasource than the read's object now answers `INVALID_FILTER` / 400 naming both datasources, where the id read served it; on a driver that compiles no `ReadableIds` leaf (MongoDB, OData) the read is refused with that driver's ADR-0139 refusal, where the id read served it. A multi-valued relation and the `update` / `delete` verbs keep the id read and its cap. +Clause-②: yes (widening; narrowing on a related object another datasource holds, and on a driver that compiles no subquery) — 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, where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller (CRUD gate, read middlewares including row scope and the filter-oracle guard on the condition's fields, `beforeFind` hooks, comparand doors) and its final `where` becomes the scope of a `ReadableIds` leaf the driver compiles into `field IN (SELECT id …)` with its tenant wall; a related record the caller cannot read is in no subquery, so it never matches, `$ne` included. 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 planned read, so each carries its read scope and field check, 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; the SQL echo of such a dataset `filter` now refuses `INVALID_FILTER` / 400 (it printed no statement before either, refusing `INVALID_FIELD`). Narrowing: a single-valued condition on a related object bound to another datasource than the read's object now answers `INVALID_FILTER` / 400 naming both datasources, where the id read served it; on a driver that compiles no `ReadableIds` leaf (MongoDB, OData) the read is refused with that driver's ADR-0139 refusal, where the id read served it. A multi-valued relation and the `update` / `delete` verbs keep the id read and its cap; a per-measure `filter` carrying a cross-object leaf stays refused. Metadata-protocol: none -Skills-docs: `content/docs/protocol/objectql/query-syntax.mdx` and `content/docs/kernel/contracts/data-engine.mdx` describe the subquery, where the cap still applies and which drivers compile it. `skills/objectstack-query` still says "up to 1000 related ids" for every relation; that holds for a multi-valued one and is now stricter than the engine for a single-valued one on a read verb (left for a skills-only change). +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 cap still applies and which drivers compile it. `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/packages/rest/src/analytics-nested-relation-filter.test.ts b/packages/rest/src/analytics-nested-relation-filter.test.ts index 74be84134b6..5e41be79516 100644 --- a/packages/rest/src/analytics-nested-relation-filter.test.ts +++ b/packages/rest/src/analytics-nested-relation-filter.test.ts @@ -156,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 }>; } /** @@ -251,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 }; }; @@ -406,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 @@ -419,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', () => { @@ -499,6 +499,27 @@ describe('[#33335] a dotted cross-object where on the engine-aggregate path answ 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 () => { // The engine answers the AUTHORED nested form under `$not` with d4 and d5 // among its rows (the NULL-safe negation of a relation match); the dotted diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index fc7e696c7a4..c7eceea4711 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -647,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` — From cad68d0754beee8adf7ded1e4b6842238ba0a0a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:28:48 +0000 Subject: [PATCH 10/25] test(service-analytics): name the three-hop fixture's second field so no error-code reader mistakes it Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../src/__tests__/crossobject-conjunct-refusal.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 7753b695924..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 @@ -855,10 +855,10 @@ describe('[#33335] a one-hop cross-object where leaf reaches the engine as its n 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.code': 'x', 'cb_order.status': 'open', + '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' }, code: 'x' } } } }, { cb_order: { status: 'open' } }], + $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 }); From 592ab16bedc491cdf40144cb991a6498f2d259b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:03:15 +0000 Subject: [PATCH 11/25] wip(objectql): the relation semi-join is taken only where it is the id read's own statement Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- .../objectql/src/engine-count-aggregate.ts | 2 +- .../src/engine-delete-and-aggregate.ts | 10 +- packages/objectql/src/engine-find.ts | 21 +- .../objectql/src/engine-query-lowering.ts | 91 ++++---- .../engine-readable-ids-permission-formula.ts | 18 +- .../objectql/src/engine-security-resolvers.ts | 11 +- packages/objectql/src/engine-top-level.ts | 6 + packages/objectql/src/engine.ts | 10 +- packages/objectql/src/relation-semi-join.ts | 205 ++++++++++++++---- 9 files changed, 265 insertions(+), 109 deletions(-) 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 9e62210aa02..32538add4c5 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` @@ -1345,7 +1349,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 + @@ -1389,7 +1393,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-find.ts b/packages/objectql/src/engine-find.ts index b01c05517a7..75d7a3483d3 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -32,7 +32,7 @@ import { SortNodeSchema, lowerFilterCondition, resolveSearchFieldResolution } 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 RelationScopePlanSink } from './relation-semi-join.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'; @@ -546,15 +546,16 @@ 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` is handed to the planner in place of the driver call, - // and the read answers no rows. Only the engine's own nested-relation - // lowering sets this symbol-keyed option. - const planSink = (options as Record | undefined)?.[RELATION_SCOPE_PLAN]; - if (typeof planSink === 'function') { - (planSink as RelationScopePlanSink)(driverAst.where as FilterCondition | undefined); - opCtx.result = []; + // 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; } @@ -848,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-query-lowering.ts b/packages/objectql/src/engine-query-lowering.ts index ff93bb16878..89113c3f199 100644 --- a/packages/objectql/src/engine-query-lowering.ts +++ b/packages/objectql/src/engine-query-lowering.ts @@ -69,10 +69,9 @@ import { lowerRelationSite, RELATION_FILTER_ID_CAP, relationFilterCapError, - relationSemiJoinDatasourceError, type RelationReplacement, } from './relation-filter-lowering.js'; -import { planRelationSemiJoinLeaf, RELATION_SCOPE_PLAN } from './relation-semi-join.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'; @@ -93,7 +92,8 @@ export interface QueryLoweringHost { readonly [SECURITY_SERVICE_SOURCE_SLOT]: unknown; resolveRelateThenLowerWhere: ObjectQL['resolveRelateThenLowerWhere']; find: ObjectQL['find']; - resolveDatasourceBinding: ObjectQL['resolveDatasourceBinding']; + /** `relation-semi-join.ts`'s `relationSemiJoinServes`, bound to the engine. */ + relationSemiJoinServes: (object: string, target: string) => boolean; } /** @@ -177,15 +177,17 @@ 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. * - * **A subquery where it can be, bounded where it cannot.** On a read verb a - * single-valued relation's related read is 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 (`relation-semi-join.ts`; a - * related object on another datasource is refused by name). A multi-valued - * relation, or a write verb's `where`, reads the ids: 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. + * **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. * * Returns `where` by reference when it holds no condition — the common path * reads nothing and allocates nothing beyond one walk. @@ -199,7 +201,7 @@ export async function resolveWhereTokens( 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, @@ -211,28 +213,9 @@ export async function lowerRelationConditions( if (sites.length === 0) return where; const context = `${operation}('${object}')`; const replacements: RelationReplacement[] = []; - for (const site of sites) { - if (!site.multiple && SEMI_JOIN_READ_VERBS.has(operation)) { - // [relation semi-join] A single-valued relation: the related read is - // 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 (`relation-semi-join.ts`). - const objectDatasource = this.resolveDatasourceBinding(object)?.datasource; - const targetDatasource = this.resolveDatasourceBinding(site.target)?.datasource; - if (objectDatasource !== targetDatasource) { - throw relationSemiJoinDatasourceError(site, context, objectDatasource, targetDatasource); - } - const leaf = await planRelationSemiJoinLeaf(site.target, (sink) => this.find( - site.target, - { where: site.condition as FilterCondition, fields: ['id'], ...(execCtx ? { context: execCtx } : {}) }, - { [RELATION_SCOPE_PLAN]: sink } as EngineReadOptions, - )); - 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: its condition is still matched against the ids - // the related read returns, under the cap. + // 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'], @@ -243,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-permission-formula.ts b/packages/objectql/src/engine-readable-ids-permission-formula.ts index e8fe10d167d..2f7ab3d8bd6 100644 --- a/packages/objectql/src/engine-readable-ids-permission-formula.ts +++ b/packages/objectql/src/engine-readable-ids-permission-formula.ts @@ -64,7 +64,7 @@ * stays on the class, the contract, and its function keeps the placeholder. */ -import { plannedRelationScopeOf } from './relation-semi-join.js'; +import { isPlannedRelationLeaf, plannedRelationLeafVerdict } from './relation-semi-join.js'; import { ReadableIds, RLS_DENY_FILTER, controlledByParentMasterOf, markFilterSubtreeProvenance } from '@objectstack/spec/data'; import type { FilterCondition } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -168,7 +168,7 @@ export async function composeReadableIdsChain( // 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) => plannedRelationScopeOf(s.leaf) === undefined).map((s) => s.leaf.object), + sites.filter((s) => !isPlannedRelationLeaf(s.leaf)).map((s) => s.leaf.object), ); for (const parent of parents) { if (!askedParents.has(parent)) continue; @@ -209,11 +209,21 @@ export async function composeReadableIdsChain( ? answer : { scope: await this.composeReadableIdsChain(chain, answer.scope, nested, [...ancestors, parent]) }); } + // [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, before the synchronous rewrite. + const readIdsFor = new Map(); + for (const s of sites) { + 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(node, (leaf) => { - const planned = plannedRelationScopeOf(leaf); - if (planned !== undefined) return planned ? ReadableIds.compose(leaf, planned.scope) : []; + 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 004072ea9c7..bf897f9379e 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'; @@ -1543,9 +1544,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( @@ -4262,7 +4264,11 @@ export class ObjectQL implements IObjectQLEngine { get _registry() { return readRegistry(); }, get relatedSchemaOf() { return readRelatedSchemaOf(); }, find: (...a) => this.find(...a), - resolveDatasourceBinding: (...a) => this.resolveDatasourceBinding(...a), + relationSemiJoinServes: (o, t) => relationSemiJoinServes.call({ + uncomposableReadableIdsParent: (x, y) => this.uncomposableReadableIdsParent(x, y), + hasHooksFor: (e, x) => this.hasHooksFor(e, x), + getDriver: (x) => this.getDriver(x), + }, o, t), }; return (lowerRelationConditions).call(host, object, operation, where, execCtx); } diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index dd67672c076..ae4510d5cce 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -24,32 +24,52 @@ * 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 plannedRelationScopeOf}), never by asking the security service a - * second, narrower question — so a related record is in the subquery exactly - * when a direct read of the related object with this condition would return - * it. The tenant wall is the driver's own, applied to the related table with - * the outer read's options (ADR-0139 D3). + * ({@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 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, or a driver outside {@link SEMI_JOIN_COMPILING_DRIVERS}. + * - **After planning** — the related read did not end at exactly one driver + * call with nothing changing its answer afterwards (a middleware answered + * without the driver, or replaced or filled the answer). + * - **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}): 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. * * ## 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. - * - **The related read stopped before its driver call** (a middleware that - * answered without asking the driver): nothing was planned, and the leaf is - * answered `$in: []` — FALSE, fail-closed, ⛔ never "no restriction". - * - **The related object lives on another datasource** than the read's - * object: refused by name before anything runs — no driver evaluates a - * subquery across two datasources. + * 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) and Turso - * compile it into a nested subquery; `driver-memory` evaluates it in - * process; a driver that compiles no such leaf (`driver-mongodb`, - * `driver-odata`) refuses it with its ADR-0139 D3 refusal. There is no - * staged id-read fallback for those drivers. + * 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 * @@ -64,60 +84,151 @@ import { ReadableIds, RLS_DENY_FILTER, type FilterCondition } from '@objectstack /** * The key of the internal read option that turns a `find` into a PLAN: when - * `options[RELATION_SCOPE_PLAN]` holds a function, `find` calls it with the - * final driver `where` in place of the driver call and answers `[]`. + * `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'); -/** The sink a planned read hands its final driver `where` to. */ -export type RelationScopePlanSink = (where: FilterCondition | undefined) => void; +/** 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: empty, and only this plan's. */ + 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; +} + +/** + * 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); + * - `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 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 { - /** `true` once the related read reached its driver call. */ - readonly planned: boolean; - /** The captured `where` (meaningful only when {@link planned}). */ + /** 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(); /** - * Build the `ReadableIds` leaf over `target` whose scope is the planned - * related read's `where`. `plan(sink)` runs that read, handing `sink` to it as - * the {@link RELATION_SCOPE_PLAN} option; a refusal from it propagates. + * 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 ended at exactly one + * driver call and its answer came back untouched: the plan's own `rows` + * object, still empty. A middleware that answered without the driver, or + * that replaced or filled the answer after it, is a read the planned `where` + * does not describe. */ export async function planRelationSemiJoinLeaf( target: string, - plan: (sink: RelationScopePlanSink) => Promise, -): Promise> { - let planned = false; - let where: FilterCondition | undefined; - await plan((final) => { - planned = true; - where = final; - }); + 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 || answer !== rows || rows.length !== 0) return null; const leaf = ReadableIds.of(target); - plannedScopes.set(leaf, { planned, where }); + 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 scope the executor boundary composes `leaf` with when this module built - * it: `{ scope }` (possibly `undefined`, no restriction beyond the tenant - * wall — never the case for a non-empty condition), or `null` for `$in: []` - * (nothing was planned, or the planned read was the deny sentinel). - * `undefined` when this module did not build `leaf`: an ordinary ADR-0139 - * leaf, composed through the security service. + * 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 plannedRelationScopeOf( - leaf: unknown, -): { readonly scope: FilterCondition | undefined } | null | undefined { +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.planned || entry.where === (RLS_DENY_FILTER as unknown)) return null; - return { scope: entry.where }; + 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 }; } From 53913071b5c9c8479fe48d73aae21603a103bfbe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:11:28 +0000 Subject: [PATCH 12/25] fix(objectql): the relation semi-join falls back to the id read wherever it is not provably that read Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- .../engine-nested-relation-lowering.test.ts | 156 +++++++++++++++++- packages/objectql/src/relation-semi-join.ts | 23 +-- .../rest/src/data-nested-object-door.test.ts | 123 ++++++++++++++ 3 files changed, 289 insertions(+), 13 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index de15f37385a..9386cba2e8e 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -72,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; }, @@ -439,3 +441,151 @@ 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('the outer read\'s driver options differ from the related read\'s own (its tenant wall): the ids are read at the boundary, under the related read\'s own wall', async () => { + const { engine, rec } = await makeEngine(); + // 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 — so a subquery + // compiled with the ledger's options would lack the owner's wall. + engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); + engine.setTenancyPostureProvider(() => 'isolated'); + 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); }; + rec.answers.set(OWNER, idRows('u1')); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expectIdRead(r, ['u1'], 'differing options'); + expect(seen).toEqual([{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]); + }); + + 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/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index ae4510d5cce..8af07e04851 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -43,9 +43,9 @@ * object-scoped middleware or an `afterFind` hook on the related object * (both act after its driver call), another datasource than the read's * object, or a driver outside {@link SEMI_JOIN_COMPILING_DRIVERS}. - * - **After planning** — the related read did not end at exactly one driver - * call with nothing changing its answer afterwards (a middleware answered - * without the driver, or replaced or filled the answer). + * - **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}): the subquery is compiled with the outer @@ -96,7 +96,7 @@ export const RELATION_SCOPE_PLAN: unique symbol = Symbol('objectql.relationScope 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: empty, and only this plan's. */ + /** The answer the planned read gives in place of the driver's: an empty array of this plan's own. */ readonly rows: unknown[]; } @@ -152,11 +152,14 @@ const plannedScopes = new WeakMap(); * 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 ended at exactly one - * driver call and its answer came back untouched: the plan's own `rows` - * object, still empty. A middleware that answered without the driver, or - * that replaced or filled the answer after it, is a read the planned `where` - * does not describe. + * 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 middleware that removes rows after the driver call is an + * object-scoped read middleware, and ADR-0139 D5.2 knows one by the object it + * is registered for ({@link relationSemiJoinServes} keeps the id read for it). */ export async function planRelationSemiJoinLeaf( target: string, @@ -166,7 +169,7 @@ export async function planRelationSemiJoinLeaf( 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 || answer !== rows || rows.length !== 0) return null; + 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; diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index eb917c4c88f..e0b6f52c373 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -462,3 +462,126 @@ for (const cell of CELLS) { }, ); } + +// ── [#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 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 } } }, + { + 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' }]], +]; + +/** 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 } as any)).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 } as any); + expect(regions.map((r: any) => r.id)).toEqual(['tr_b']); + }); + + it('through one hop and through three: only tenant B\'s case, exactly the two-step route\'s answer — on find and count', async () => { + for (const [name, where] of TEN_HOPS) { + const got = (await engine.find(TEN_CASE, { where, context: CALLER_B } as any)).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 } as any), `count, ${name}`).toBe(1); + } + }); + + 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 } as any)).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'); + } + }); + }, + ); +} From cdf3f50c19dfc28d9945cc7d06900a7211328d71 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:14:37 +0000 Subject: [PATCH 13/25] fix(service-analytics,objectql): echo copy, docs and changeset follow the fallbacks; widening only Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- .changeset/33626-relation-semi-join.md | 10 +++--- content/docs/kernel/contracts/data-engine.mdx | 16 +++++---- .../docs/protocol/objectql/query-syntax.mdx | 27 ++++++++------- .../objectql/src/relation-filter-lowering.ts | 33 ++++--------------- .../service-analytics/src/read-scope-sql.ts | 2 +- .../src/strategies/cross-object-where.ts | 11 ++++--- .../src/strategies/objectql-strategy.ts | 14 ++++---- 7 files changed, 50 insertions(+), 63 deletions(-) diff --git a/.changeset/33626-relation-semi-join.md b/.changeset/33626-relation-semi-join.md index 8d36fc60745..f3afe07ea73 100644 --- a/.changeset/33626-relation-semi-join.md +++ b/.changeset/33626-relation-semi-join.md @@ -1,10 +1,10 @@ --- '@objectstack/objectql': patch -'@objectstack/service-analytics': 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, each read-scoped on its own object, with no id cap; analytics serves the dataset's own `filter` the same way +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; narrowing on a related object another datasource holds, and on a driver that compiles no subquery) — 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, where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller (CRUD gate, read middlewares including row scope and the filter-oracle guard on the condition's fields, `beforeFind` hooks, comparand doors) and its final `where` becomes the scope of a `ReadableIds` leaf the driver compiles into `field IN (SELECT id …)` with its tenant wall; a related record the caller cannot read is in no subquery, so it never matches, `$ne` included. 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 planned read, so each carries its read scope and field check, 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; the SQL echo of such a dataset `filter` now refuses `INVALID_FILTER` / 400 (it printed no statement before either, refusing `INVALID_FIELD`). Narrowing: a single-valued condition on a related object bound to another datasource than the read's object now answers `INVALID_FILTER` / 400 naming both datasources, where the id read served it; on a driver that compiles no `ReadableIds` leaf (MongoDB, OData) the read is refused with that driver's ADR-0139 refusal, where the id read served it. A multi-valued relation and the `update` / `delete` verbs keep the id read and its cap; a per-measure `filter` carrying a cross-object leaf stays refused. -Metadata-protocol: none -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 cap still applies and which drivers compile it. `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). +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 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), unchanged. 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. Unchanged, still the id read: a related object on another datasource, a driver that compiles no subquery (MongoDB, OData), a related object an object-scoped middleware or an `afterFind` hook shapes, a multi-valued relation and the `update` / `delete` verbs. 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 140431d69fb..a24b3e68b11 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -194,10 +194,11 @@ related object with the condition **as the caller** — that object's row scope 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 what that read selects: on a read verb, a single-valued relation is -one subquery inside the read's own statement (the related read is planned, not run: its -read scope, the condition and the tenant wall become the subquery's `WHERE`, so no id list -is read and none is capped); otherwise `$in` on the ids that read returns, any member on a -multi-valued one (`multiple: true`). No related record matching selects no +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 +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 **up to three relationships** (ADR-0071's hop limit): every key must be a field @@ -206,9 +207,10 @@ the related object declares, and a relation key may carry a condition of its own 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 subquery needs the related object on the read's -datasource and a driver that compiles it (the SQL drivers; the in-memory driver evaluates it -in process; MongoDB and OData refuse it). For either, run the two steps +rather than run over a cut-off list, and the id read is also what serves a related object on +another datasource, a driver that compiles no subquery (MongoDB, OData — the SQL drivers +compile it, the in-memory driver evaluates it in process), and a related object whose reads +an object-scoped middleware or an `afterFind` hook shapes. Past the cap, run the two steps yourself — filter the related object, then match its ids: ```typescript diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index ba5fab8cc8e..5650b8ada3f 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -689,13 +689,15 @@ 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**. On a read verb (`find`, `findOne`, -`count`, `aggregate`) a single-valued relation is matched in the database: the -related read is planned, not run, and the driver receives one statement with a -subquery, `account IN (SELECT id FROM account WHERE AND -)`, with the tenant wall on both tables — no id list, no cap. -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`). +`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 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 @@ -703,11 +705,12 @@ its related object (`{ account: { owner: { region: 'NA' } } }`), each hop read a 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; where ids are read, at most 1000 of them, refused past that, -`INVALID_FILTER` / 400, never truncated; the subquery form needs the related -object on the same datasource (refused `INVALID_FILTER` / 400 otherwise) and a -driver that compiles it — the SQL drivers (every `driver-sql` dialect, Turso) -compile it, the in-memory driver evaluates it in process, and a driver that -compiles no subquery (MongoDB, OData) refuses the read; as the caller: the related object's row scope and field permissions +`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; a related object on another datasource, a driver that +compiles no subquery (MongoDB, OData), and a related object whose reads an +object-scoped middleware or an `afterFind` hook shapes keep the id read; 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. diff --git a/packages/objectql/src/relation-filter-lowering.ts b/packages/objectql/src/relation-filter-lowering.ts index 005a6d1e5a0..417badb8672 100644 --- a/packages/objectql/src/relation-filter-lowering.ts +++ b/packages/objectql/src/relation-filter-lowering.ts @@ -31,12 +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. - * - **A subquery on a read verb.** 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 - * (`relation-semi-join.ts`): no id list, so none of the bound below. + * - **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). At most {@link RELATION_FILTER_ID_CAP} related ids + * 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. @@ -340,24 +342,3 @@ export function relationFilterCapError(site: RelationFilterSite, context: string + `page by page and match '${site.field}' against its ids: ${idsRoute(site.field, site.multiple)}.`, ); } - -/** - * The cross-datasource refusal for a single-valued relation condition: it is - * served as a subquery inside the read's own statement - * (`relation-semi-join.ts`), and no driver evaluates a subquery across two - * datasources — `INVALID_FILTER` / 400, before anything is read. - */ -export function relationSemiJoinDatasourceError( - site: RelationFilterSite, - context: string, - objectDatasource: string | undefined, - targetDatasource: string | undefined, -): Error { - return invalidFilterError( - `${context}: the nested-relation condition at ${site.path} is on the related object '${site.target}', ` - + `bound to datasource '${String(targetDatasource)}', while this read's object is bound to ` - + `'${String(objectDatasource)}'. The condition is evaluated as a subquery inside this read's own ` - + `statement, and no driver evaluates a subquery across two datasources, so the filter was NOT applied. ` - + `Read '${site.target}' yourself and match '${site.field}' against its ids: ${idsRoute(site.field, site.multiple)}.`, - ); -} 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 77c0762685b..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 diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index c7eceea4711..eeae9e160c9 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -314,8 +314,8 @@ function crossObjectEchoRefused(leaf: ServedCrossObjectLeaf): Error { 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 ${nested}: 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 ` + + `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.`, ); } @@ -2298,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.`, ); From 5d3fa51ce51afdf1d2fbb8e0e9ba56ffca516ce4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:16:55 +0000 Subject: [PATCH 14/25] test(rest): the two-tenant pins run one hop and three hops as separate cases Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- packages/rest/src/data-nested-object-door.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index e0b6f52c373..5c2aa4b2c9d 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -560,14 +560,14 @@ for (const cell of CELLS) { expect(regions.map((r: any) => r.id)).toEqual(['tr_b']); }); - it('through one hop and through three: only tenant B\'s case, exactly the two-step route\'s answer — on find and count', async () => { - for (const [name, where] of TEN_HOPS) { + 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 } as any)).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 } as any), `count, ${name}`).toBe(1); - } - }); + }); + } 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'); }; From 3194cbaefd3982377e286b0e0b51f3010b720ea4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:27:55 +0000 Subject: [PATCH 15/25] test(objectql): a read whose leaves are all planned spends no security-service warning Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- .../src/engine-nested-relation-lowering.test.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 9386cba2e8e..1e1bbd3e562 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -21,7 +21,7 @@ */ import { describe, it, expect, beforeEach } from 'vitest'; -import { isComposedReadableIds } from '@objectstack/spec/data'; +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'; @@ -580,6 +580,21 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr expect(seen).toEqual([{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]); }); + 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) } } } as any); + await engine.find(OBJECT, { where: { owner: { $in: ReadableIds.of(OWNER) } } } as any); + 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'); From 1b832c582f538c8a521aab7a700b5ee7572bf575 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:51:39 +0000 Subject: [PATCH 16/25] refactor(objectql): the semi-join eligibility reads the engine through a host-literal stub Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq Co-authored-by: Claude --- packages/objectql/src/engine.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index bf897f9379e..f424c44a172 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4264,15 +4264,21 @@ export class ObjectQL implements IObjectQLEngine { get _registry() { return readRegistry(); }, get relatedSchemaOf() { return readRelatedSchemaOf(); }, find: (...a) => this.find(...a), - relationSemiJoinServes: (o, t) => relationSemiJoinServes.call({ - uncomposableReadableIdsParent: (x, y) => this.uncomposableReadableIdsParent(x, y), - hasHooksFor: (e, x) => this.hasHooksFor(e, x), - getDriver: (x) => this.getDriver(x), - }, o, t), + 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), + }; + return relationSemiJoinServes.call(host, object, target); + } + private withResolvedWhere( object: string, operation: string, From 96c23127d89f4f2b8b26ddbff7e152ec8f9f8979 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:55:59 +0000 Subject: [PATCH 17/25] test(objectql,rest): type the new pins' query options instead of erasing them The seven option bags the semi-join fallback and two-tenant pins pass to engine.find / engine.count were cast to any; they type-check as written, so the casts only grew the query-options erasure test surface (236 -> 243). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq --- .../src/engine-nested-relation-lowering.test.ts | 4 ++-- packages/rest/src/data-nested-object-door.test.ts | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 1e1bbd3e562..922664eedbb 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -590,8 +590,8 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr 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) } } } as any); - await engine.find(OBJECT, { where: { owner: { $in: ReadableIds.of(OWNER) } } } as any); + 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); }); diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index 5c2aa4b2c9d..bdd0e86b5a4 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -547,7 +547,7 @@ for (const cell of CELLS) { /** 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 } as any)).map((r: any) => r.id); + (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 } }); @@ -556,16 +556,16 @@ for (const cell of CELLS) { }; 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 } as any); + 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 } as any)).map((r: any) => r.id).sort(); + 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 } as any), `count, ${name}`).toBe(1); + expect(await engine.count(TEN_CASE, { where, context: CALLER_B }), `count, ${name}`).toBe(1); }); } @@ -574,7 +574,7 @@ for (const cell of CELLS) { 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 } as any)).map((r: any) => r.id).sort(); + 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)); } From 777c4d063c7bb2a523d03ffbd9750342a95c573d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:15:10 +0000 Subject: [PATCH 18/25] wip(objectql): decide the registry-answered fallbacks before planning Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../engine-nested-relation-lowering.test.ts | 102 ++++++++++++++++-- packages/objectql/src/engine.ts | 3 + packages/objectql/src/relation-semi-join.ts | 52 +++++++-- 3 files changed, 139 insertions(+), 18 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 922664eedbb..cbdecb2944c 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -564,20 +564,102 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr expect(normalized(rec.reads[rec.reads.length - 1].ast.where)).toEqual(OUTER_REF); }); - it('the outer read\'s driver options differ from the related read\'s own (its tenant wall): the ids are read at the boundary, under the related read\'s own wall', async () => { - const { engine, rec } = await makeEngine(); - // 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 — so a subquery - // compiled with the ledger's options would lack the owner's wall. - engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); - engine.setTenancyPostureProvider(() => 'isolated'); + /** + * How many times the related read was dispatched through its pipeline: + * a global middleware and a `beforeFind` hook, each counting reads of the + * owner object only. + */ + 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; + } + + /** The tenant scope each driver call was handed, by object. */ + function recordTenantScope(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); }; - rec.answers.set(OWNER, idRows('u1')); + return seen; + } + + it('under a wall, a related object of another tenancy class keeps the id read, decided before planning: dispatched once, under its own wall — in either direction', async () => { + // Direction 1: the ledger is no tenant's, the owner is tenant-scoped. + // Direction 2: the ledger is tenant-scoped, the owner is no tenant's. + // Either way a subquery compiled with the ledger's options would carry + // the wrong wall for the owner, so the registry answers before planning. + for (const direction of ['related walled', 'outer walled'] as const) { + const { engine, rec } = await makeEngine(); + if (direction === 'related walled') engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); + else engine.registry.registerObject({ ...OWNER_OBJECT, tenancy: { enabled: false } } as any, 'test'); + engine.setTenancyPostureProvider(() => 'isolated'); + const n = countRelatedDispatch(engine); + const seen = recordTenantScope(rec); + 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(direction === 'related walled' + ? [{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }] + : [{ object: OWNER, tenantId: undefined }, { object: OBJECT, tenantId: 'org_b' }]); + expect(n, direction).toEqual({ middleware: 1, beforeFind: 1 }); + } + }); + + it('CONTROL without a wall (the single posture) the 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 n = countRelatedDispatch(engine); const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); - expectIdRead(r, ['u1'], 'differing options'); - expect(seen).toEqual([{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]); + expect(r.related).toHaveLength(0); + expect(normalized(r.outerWhere)).toEqual({ owner: { $in: { SEMI_JOIN: OWNER, scope: { region: 'NA' } } } }); + expect(n).toEqual({ middleware: 1, beforeFind: 1 }); + }); + + it('a federated related object keeps the id read, decided before planning: dispatched once', async () => { + const { engine, rec } = await makeEngine(); + engine.registry.registerObject({ ...OWNER_OBJECT, external: { remoteName: 'remote_owner' } } as any, 'test'); + const n = countRelatedDispatch(engine); + rec.answers.set(OWNER, idRows('u1')); + expectIdRead(await readsOf(engine, rec), ['u1'], 'federated'); + expect(n).toEqual({ middleware: 1, beforeFind: 1 }); + }); + + it('the outer read\'s driver options differ from the related read\'s own, in either direction: the ids are read at the boundary under the related read\'s own options — a second dispatch of the related read', async () => { + // Both objects are tenant-scoped, so the registry cannot answer: a + // `beforeFind` hook hands one of the two reads a tenant scope of its own. + for (const direction of ['related narrowed', 'outer narrowed'] as const) { + const { engine, rec } = await makeEngine(); + engine.setTenancyPostureProvider(() => 'isolated'); + const n = countRelatedDispatch(engine); + engine.registerHook('beforeFind', async (ctx: any) => { ctx.input.options.tenantId = 'org_x'; }, { object: direction === 'related narrowed' ? OWNER : OBJECT }); + const seen = recordTenantScope(rec); + 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(direction === 'related narrowed' + ? [{ object: OWNER, tenantId: 'org_x' }, { object: OBJECT, tenantId: 'org_b' }] + : [{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: 'org_x' }]); + // Planned, then read: the related object's middleware chain and + // `beforeFind` hooks run twice for this hop. + expect(n, direction).toEqual({ middleware: 2, beforeFind: 2 }); + } + }); + + it('a related read a middleware answers itself falls back after planning — a second dispatch of the related read', async () => { + const { engine, rec } = await makeEngine(); + const n = 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'] } }); + expect(n).toEqual({ middleware: 2, beforeFind: 0 }); }); it('a read whose leaves are all planned does not report, nor spend, the once-only "no usable security service" warning', async () => { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index f424c44a172..98990ef8124 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -192,6 +192,7 @@ import { import { type TenancyPosture, type TenantLayer0Verdict, + postureEnforcesWall, postureUsesUnionScope, } from '@objectstack/spec/security'; @@ -4275,6 +4276,8 @@ export class ObjectQL implements IObjectQLEngine { uncomposableReadableIdsParent: (...a) => this.uncomposableReadableIdsParent(...a), hasHooksFor: (...a) => this.hasHooksFor(...a), getDriver: (...a) => this.getDriver(...a), + getSchema: (name) => this._registry.getObject(name), + wallInForce: () => postureEnforcesWall(this.resolveEnginePosture()), }; return relationSemiJoinServes.call(host, object, target); } diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index 8af07e04851..d5f5c63eae7 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -38,11 +38,17 @@ * ({@link relationSemiJoinServes}, then the planned read's own outcome, then * the executor boundary's comparison): * - * - **Before planning** — 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, or a driver outside {@link SEMI_JOIN_COMPILING_DRIVERS}. + * - **Before planning** — what the registry already answers, so the related + * read is dispatched once, as the id read: the related object has a + * restriction no planned `where` can carry (an object-scoped middleware or + * an `afterFind` hook on it, both acting after its driver call); it is + * federated (ADR-0015 `external`: the driver prepares a federated object + * for the object a read names, which a subquery is not); it is bound to + * another datasource than the read's object; the read's driver is outside + * {@link SEMI_JOIN_COMPILING_DRIVERS}; or, under a posture that walls + * organizations, the two objects are of different tenancy classes (one + * tenant-scoped, the other platform-global or federated), so the driver + * would scope the two reads differently. * - **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). @@ -52,6 +58,13 @@ * 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 or at the boundary has dispatched the + * related read twice — once planned, once as the id read — so the related + * object's middleware chain and `beforeFind` hooks run twice for it. Only + * what the registry cannot answer reaches those two points: a middleware's + * answer, and driver options a `beforeFind` hook or the security layer's + * per-object verdict set differently on the two objects. + * * ## What the semi-join means at its edges * * - **No related record matches** (or none the caller can read): the @@ -80,7 +93,8 @@ * object the map does not hold. */ -import { ReadableIds, RLS_DENY_FILTER, type FilterCondition } from '@objectstack/spec/data'; +import { ReadableIds, RLS_DENY_FILTER, isTenancyDisabled, type FilterCondition } from '@objectstack/spec/data'; +import { isFederatedObject } from './federated-object.js'; /** * The key of the internal read option that turns a `find` into a PLAN: when @@ -113,23 +127,45 @@ 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` (the registry's own lookup). */ + getSchema(object: string): unknown; + /** Whether the posture in force walls organizations (`postureEnforcesWall`). */ + wallInForce(): boolean; } +/** + * Whether the driver scopes a read of `schema` by organization at all: the + * engine hands it a tenant scope only for an object that is neither + * tenancy-disabled nor federated (`buildDriverOptions`). + */ +const tenantScopedAtDriver = (schema: unknown): boolean => !isTenancyDisabled(schema) && !isFederatedObject(schema); + /** * 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: + * semi-join at all. `false` keeps the id read, and the related read is then + * dispatched once. 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: the driver prepares a federated object's + * remote facts for the object a read names, and a subquery's object is + * not one it names; + * - under a posture that walls organizations, `object` and `target` are both + * scoped by organization at the driver or both not: otherwise their reads' + * driver options differ for every walled caller, and the boundary would + * only answer the planned read with a second dispatch, the id read; * - `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.getSchema(target); + if (isFederatedObject(targetSchema)) return false; + if (this.wallInForce() && tenantScopedAtDriver(this.getSchema(object)) !== tenantScopedAtDriver(targetSchema)) return false; const name = this.getDriver(object)?.name; return typeof name === 'string' && SEMI_JOIN_COMPILING_DRIVERS.has(name); } From dc2fd16a7441ac9b0f7eb5ded5f8215f464e8973 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:31:01 +0000 Subject: [PATCH 19/25] revert(objectql): withdraw the work-in-progress commit in favour of the earlier holder's equivalent commits Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../engine-nested-relation-lowering.test.ts | 102 ++---------------- packages/objectql/src/engine.ts | 3 - packages/objectql/src/relation-semi-join.ts | 52 ++------- 3 files changed, 18 insertions(+), 139 deletions(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index cbdecb2944c..922664eedbb 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -564,102 +564,20 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr expect(normalized(rec.reads[rec.reads.length - 1].ast.where)).toEqual(OUTER_REF); }); - /** - * How many times the related read was dispatched through its pipeline: - * a global middleware and a `beforeFind` hook, each counting reads of the - * owner object only. - */ - 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; - } - - /** The tenant scope each driver call was handed, by object. */ - function recordTenantScope(rec: ReturnType) { + it('the outer read\'s driver options differ from the related read\'s own (its tenant wall): the ids are read at the boundary, under the related read\'s own wall', async () => { + const { engine, rec } = await makeEngine(); + // 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 — so a subquery + // compiled with the ledger's options would lack the owner's wall. + engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); + engine.setTenancyPostureProvider(() => 'isolated'); 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; - } - - it('under a wall, a related object of another tenancy class keeps the id read, decided before planning: dispatched once, under its own wall — in either direction', async () => { - // Direction 1: the ledger is no tenant's, the owner is tenant-scoped. - // Direction 2: the ledger is tenant-scoped, the owner is no tenant's. - // Either way a subquery compiled with the ledger's options would carry - // the wrong wall for the owner, so the registry answers before planning. - for (const direction of ['related walled', 'outer walled'] as const) { - const { engine, rec } = await makeEngine(); - if (direction === 'related walled') engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); - else engine.registry.registerObject({ ...OWNER_OBJECT, tenancy: { enabled: false } } as any, 'test'); - engine.setTenancyPostureProvider(() => 'isolated'); - const n = countRelatedDispatch(engine); - const seen = recordTenantScope(rec); - 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(direction === 'related walled' - ? [{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }] - : [{ object: OWNER, tenantId: undefined }, { object: OBJECT, tenantId: 'org_b' }]); - expect(n, direction).toEqual({ middleware: 1, beforeFind: 1 }); - } - }); - - it('CONTROL without a wall (the single posture) the 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 n = 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(n).toEqual({ middleware: 1, beforeFind: 1 }); - }); - - it('a federated related object keeps the id read, decided before planning: dispatched once', async () => { - const { engine, rec } = await makeEngine(); - engine.registry.registerObject({ ...OWNER_OBJECT, external: { remoteName: 'remote_owner' } } as any, 'test'); - const n = countRelatedDispatch(engine); rec.answers.set(OWNER, idRows('u1')); - expectIdRead(await readsOf(engine, rec), ['u1'], 'federated'); - expect(n).toEqual({ middleware: 1, beforeFind: 1 }); - }); - - it('the outer read\'s driver options differ from the related read\'s own, in either direction: the ids are read at the boundary under the related read\'s own options — a second dispatch of the related read', async () => { - // Both objects are tenant-scoped, so the registry cannot answer: a - // `beforeFind` hook hands one of the two reads a tenant scope of its own. - for (const direction of ['related narrowed', 'outer narrowed'] as const) { - const { engine, rec } = await makeEngine(); - engine.setTenancyPostureProvider(() => 'isolated'); - const n = countRelatedDispatch(engine); - engine.registerHook('beforeFind', async (ctx: any) => { ctx.input.options.tenantId = 'org_x'; }, { object: direction === 'related narrowed' ? OWNER : OBJECT }); - const seen = recordTenantScope(rec); - 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(direction === 'related narrowed' - ? [{ object: OWNER, tenantId: 'org_x' }, { object: OBJECT, tenantId: 'org_b' }] - : [{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: 'org_x' }]); - // Planned, then read: the related object's middleware chain and - // `beforeFind` hooks run twice for this hop. - expect(n, direction).toEqual({ middleware: 2, beforeFind: 2 }); - } - }); - - it('a related read a middleware answers itself falls back after planning — a second dispatch of the related read', async () => { - const { engine, rec } = await makeEngine(); - const n = 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'] } }); - expect(n).toEqual({ middleware: 2, beforeFind: 0 }); + const r = await readsOf(engine, rec, { userId: 'u_b', tenantId: 'org_b' }); + expectIdRead(r, ['u1'], 'differing options'); + expect(seen).toEqual([{ object: OWNER, tenantId: 'org_b' }, { object: OBJECT, tenantId: undefined }]); }); it('a read whose leaves are all planned does not report, nor spend, the once-only "no usable security service" warning', async () => { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 98990ef8124..f424c44a172 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -192,7 +192,6 @@ import { import { type TenancyPosture, type TenantLayer0Verdict, - postureEnforcesWall, postureUsesUnionScope, } from '@objectstack/spec/security'; @@ -4276,8 +4275,6 @@ export class ObjectQL implements IObjectQLEngine { uncomposableReadableIdsParent: (...a) => this.uncomposableReadableIdsParent(...a), hasHooksFor: (...a) => this.hasHooksFor(...a), getDriver: (...a) => this.getDriver(...a), - getSchema: (name) => this._registry.getObject(name), - wallInForce: () => postureEnforcesWall(this.resolveEnginePosture()), }; return relationSemiJoinServes.call(host, object, target); } diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index d5f5c63eae7..8af07e04851 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -38,17 +38,11 @@ * ({@link relationSemiJoinServes}, then the planned read's own outcome, then * the executor boundary's comparison): * - * - **Before planning** — what the registry already answers, so the related - * read is dispatched once, as the id read: the related object has a - * restriction no planned `where` can carry (an object-scoped middleware or - * an `afterFind` hook on it, both acting after its driver call); it is - * federated (ADR-0015 `external`: the driver prepares a federated object - * for the object a read names, which a subquery is not); it is bound to - * another datasource than the read's object; the read's driver is outside - * {@link SEMI_JOIN_COMPILING_DRIVERS}; or, under a posture that walls - * organizations, the two objects are of different tenancy classes (one - * tenant-scoped, the other platform-global or federated), so the driver - * would scope the two reads differently. + * - **Before planning** — 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, or a driver outside {@link SEMI_JOIN_COMPILING_DRIVERS}. * - **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). @@ -58,13 +52,6 @@ * 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 or at the boundary has dispatched the - * related read twice — once planned, once as the id read — so the related - * object's middleware chain and `beforeFind` hooks run twice for it. Only - * what the registry cannot answer reaches those two points: a middleware's - * answer, and driver options a `beforeFind` hook or the security layer's - * per-object verdict set differently on the two objects. - * * ## What the semi-join means at its edges * * - **No related record matches** (or none the caller can read): the @@ -93,8 +80,7 @@ * object the map does not hold. */ -import { ReadableIds, RLS_DENY_FILTER, isTenancyDisabled, type FilterCondition } from '@objectstack/spec/data'; -import { isFederatedObject } from './federated-object.js'; +import { ReadableIds, RLS_DENY_FILTER, type FilterCondition } from '@objectstack/spec/data'; /** * The key of the internal read option that turns a `find` into a PLAN: when @@ -127,45 +113,23 @@ 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` (the registry's own lookup). */ - getSchema(object: string): unknown; - /** Whether the posture in force walls organizations (`postureEnforcesWall`). */ - wallInForce(): boolean; } -/** - * Whether the driver scopes a read of `schema` by organization at all: the - * engine hands it a tenant scope only for an object that is neither - * tenancy-disabled nor federated (`buildDriverOptions`). - */ -const tenantScopedAtDriver = (schema: unknown): boolean => !isTenancyDisabled(schema) && !isFederatedObject(schema); - /** * Whether a read of `object` may PLAN its relation condition on `target` as a - * semi-join at all. `false` keeps the id read, and the related read is then - * dispatched once. Registry facts only — nothing is read and the caller's - * context is not consulted: + * 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: the driver prepares a federated object's - * remote facts for the object a read names, and a subquery's object is - * not one it names; - * - under a posture that walls organizations, `object` and `target` are both - * scoped by organization at the driver or both not: otherwise their reads' - * driver options differ for every walled caller, and the boundary would - * only answer the planned read with a second dispatch, the id read; * - `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.getSchema(target); - if (isFederatedObject(targetSchema)) return false; - if (this.wallInForce() && tenantScopedAtDriver(this.getSchema(object)) !== tenantScopedAtDriver(targetSchema)) return false; const name = this.getDriver(object)?.name; return typeof name === 'string' && SEMI_JOIN_COMPILING_DRIVERS.has(name); } From 7f402dccb72539dd7489b5d6856aff359e0e0a6d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:31:22 +0000 Subject: [PATCH 20/25] fix(objectql): decide the federated and tenancy-class fallbacks before planning the related read A federated related object keeps the id read, and under a walled posture a related object of another tenancy class than the read's object keeps it too, decided from the registry before the related read is planned, so that read is dispatched once. The fallback pins assert the related driver read, its where and limit, the outer $in and the dispatch counts. (cherry picked from commit 6e35a5e5caa7b8473983bba4eb62698d3c3329e2; one module-header paragraph left out) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../objectql/src/engine-driver-options.ts | 13 ++- .../engine-nested-relation-lowering.test.ts | 79 +++++++++++++++++-- packages/objectql/src/engine.ts | 2 + packages/objectql/src/relation-semi-join.ts | 46 +++++++++-- 4 files changed, 124 insertions(+), 16 deletions(-) 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-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index 922664eedbb..b1c28726b46 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -564,20 +564,85 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr expect(normalized(rec.reads[rec.reads.length - 1].ast.where)).toEqual(OUTER_REF); }); - it('the outer read\'s driver options differ from the related read\'s own (its tenant wall): the ids are read at the boundary, under the related read\'s own wall', async () => { + it('a federated related object keeps the id read', async () => { const { engine, rec } = await makeEngine(); - // 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 — so a subquery - // compiled with the ledger's options would lack the owner's wall. - engine.registry.registerObject({ ...LEDGER, tenancy: { enabled: false } } as any, 'test'); - engine.setTenancyPostureProvider(() => 'isolated'); + // ADR-0015 `external`, on the read's own datasource and driver. + engine.registry.registerObject({ ...OWNER_OBJECT, external: { remoteName: 'owners' } } as any, 'test'); + rec.answers.set(OWNER, idRows('u1')); + expectIdRead(await readsOf(engine, rec), ['u1'], 'federated related object'); + }); + + /** + * 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'], 'differing options'); + 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 read whose leaves are all planned does not report, nor spend, the once-only "no usable security service" warning', async () => { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index f424c44a172..f4aa01a27f6 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4275,6 +4275,8 @@ export class ObjectQL implements IObjectQLEngine { 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); } diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index 8af07e04851..9231631ffbd 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -38,19 +38,28 @@ * ({@link relationSemiJoinServes}, then the planned read's own outcome, then * the executor boundary's comparison): * - * - **Before planning** — 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, or a driver outside {@link SEMI_JOIN_COMPILING_DRIVERS}. + * - **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}): 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. + * ({@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 * @@ -81,6 +90,9 @@ */ 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 @@ -113,6 +125,10 @@ 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; } /** @@ -125,11 +141,25 @@ export interface RelationSemiJoinServesHost { * 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); } From 302a6bc991e550a4e9bb59719c6663b76dd09eb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:31:38 +0000 Subject: [PATCH 21/25] docs(objectql): list every case that keeps the id read and its cap The changeset and both docs pages name the federated related object, a related object read under different driver options than the outer object, and a related read that a middleware answers itself; a hop that falls back after planning dispatches the related read twice. (cherry picked from commit d599a82e6a023cf78aaf5d10f90ecc6fcdbaa8e4; the sentence on one after-driver boundary left out) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .changeset/33626-relation-semi-join.md | 2 +- content/docs/kernel/contracts/data-engine.mdx | 26 +++++++++++---- .../docs/protocol/objectql/query-syntax.mdx | 33 ++++++++++++++----- 3 files changed, 46 insertions(+), 15 deletions(-) diff --git a/.changeset/33626-relation-semi-join.md b/.changeset/33626-relation-semi-join.md index f3afe07ea73..2573be6c768 100644 --- a/.changeset/33626-relation-semi-join.md +++ b/.changeset/33626-relation-semi-join.md @@ -5,6 +5,6 @@ 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 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), unchanged. 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. Unchanged, still the id read: a related object on another datasource, a driver that compiles no subquery (MongoDB, OData), a related object an object-scoped middleware or an `afterFind` hook shapes, a multi-valued relation and the `update` / `delete` verbs. 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. +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 a24b3e68b11..caa9106e0ce 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -197,7 +197,8 @@ relation field against what that read selects: on a read verb, a single-valued r 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 -are carried into the subquery, or the hop falls back to the id read); otherwise `$in` on the +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. @@ -207,11 +208,24 @@ the related object declares, and a relation key may carry a condition of its own 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, and the id read is also what serves a related object on -another datasource, a driver that compiles no subquery (MongoDB, OData — the SQL drivers -compile it, the in-memory driver evaluates it in process), and a related object whose reads -an object-scoped middleware or an `afterFind` hook shapes. Past the cap, run the two steps -yourself — filter the related object, then match its ids: +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 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 4954e82dac1..1e6683c3587 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -692,9 +692,10 @@ related object with it **as the caller**. On a read verb (`find`, `findOne`, 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 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 +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`). @@ -707,17 +708,33 @@ 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; a related object on another datasource, a driver that -compiles no subquery (MongoDB, OData), and a related object whose reads an -object-scoped middleware or an `afterFind` hook shapes keep the id read; as the caller: the related object's row scope and field permissions +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. + - **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 a subquery on a read verb and with `$in` on the - related ids on `update` / `delete`; 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 related record the caller cannot read never matches**, whatever the operator: From c1b3657d585309e34261fa6dd6e226399cf7af50 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:14:33 +0000 Subject: [PATCH 22/25] test(rest): pin the executor boundary's driver-options comparison in both directions on a real driver Both objects tenant-scoped, a per-object verdict recorded for the request: the outer read unscoped with the related read scoped, and the opposite. Each answers the two-step route's rows on find and count. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq (cherry picked from commit 6c7f6aef573782a2511721e32dd81bc8d6874bac) --- .../rest/src/data-nested-object-door.test.ts | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index bdd0e86b5a4..cfb4851de78 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -585,3 +585,105 @@ for (const cell of CELLS) { }, ); } + +// ── [#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; + } + }); + } + }, + ); +} From cfe68c68671189e3893fd3eb9aa43e2bde03dd73 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:23:09 +0000 Subject: [PATCH 23/25] test(objectql): give the two new federated-object questions their census rows Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4d1QwJJ5KGZTThP4fnq (cherry picked from commit 39056411d1b531856ca8dfbe9b3ee44dc2e608c7) --- .../src/federated-injected-column-readers.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) 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. From 2d2eaa736f3aac2c82e6f4c508b7325b6f2497fc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:32:16 +0000 Subject: [PATCH 24/25] test(objectql,rest): pin the dispatch count of a fallback after planning, and the other tenancy direction on a real driver A related read a middleware answers itself falls back after planning and is dispatched twice; without a wall two tenancy classes still compose; and a tenant-scoped read on a related object that is no tenant's answers the two-step route's rows with the related read dispatched once, on SQLite and PostgreSQL. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../engine-nested-relation-lowering.test.ts | 28 ++++++++++++++++++- .../rest/src/data-nested-object-door.test.ts | 23 +++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-nested-relation-lowering.test.ts b/packages/objectql/src/engine-nested-relation-lowering.test.ts index b1c28726b46..c0faff56c92 100644 --- a/packages/objectql/src/engine-nested-relation-lowering.test.ts +++ b/packages/objectql/src/engine-nested-relation-lowering.test.ts @@ -564,12 +564,14 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr expect(normalized(rec.reads[rec.reads.length - 1].ast.where)).toEqual(OUTER_REF); }); - it('a federated related object keeps the id read', async () => { + 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 }); }); /** @@ -645,6 +647,30 @@ describe('[#33626] the semi-join falls back to the id read wherever it is not pr 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[] = []; diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index cfb4851de78..24715c91543 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -469,6 +469,8 @@ 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'; @@ -480,6 +482,9 @@ const ORG_B = 'org_ten_b'; */ 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 } }, @@ -502,6 +507,8 @@ const TEN_SEED: ReadonlyArray { + const grids = { n: 0 }; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object === TEN_GRID && opCtx.operation === 'find') grids.n += 1; + return next(); + }); + 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); + }); + 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' }); From 6cf1ce0e2cd0e77109124a517126fb0fe6a5509b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:08:05 +0000 Subject: [PATCH 25/25] docs(objectql): state the form a read rule takes to bound a relation condition 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 (ADR-0139 D5.2); both docs pages and the planned-leaf docblock say so. The other-direction pin counts the related read with a hook it unregisters afterwards. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- content/docs/kernel/contracts/data-engine.mdx | 4 +++ .../docs/protocol/objectql/query-syntax.mdx | 4 +++ packages/objectql/src/relation-semi-join.ts | 8 +++--- .../rest/src/data-nested-object-door.test.ts | 26 ++++++++++--------- 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/content/docs/kernel/contracts/data-engine.mdx b/content/docs/kernel/contracts/data-engine.mdx index caa9106e0ce..fdfd6b1389c 100644 --- a/content/docs/kernel/contracts/data-engine.mdx +++ b/content/docs/kernel/contracts/data-engine.mdx @@ -222,6 +222,10 @@ single-valued relation on a read verb in each of these cases: 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 diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index 1e6683c3587..795d7297bbf 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -729,6 +729,10 @@ A hop that falls back after planning (a middleware answering the related read, o 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 diff --git a/packages/objectql/src/relation-semi-join.ts b/packages/objectql/src/relation-semi-join.ts index 9231631ffbd..20c004e45f9 100644 --- a/packages/objectql/src/relation-semi-join.ts +++ b/packages/objectql/src/relation-semi-join.ts @@ -187,9 +187,11 @@ const plannedScopes = new WeakMap(); * 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 middleware that removes rows after the driver call is an - * object-scoped read middleware, and ADR-0139 D5.2 knows one by the object it - * is registered for ({@link relationSemiJoinServes} keeps the id read for it). + * 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, diff --git a/packages/rest/src/data-nested-object-door.test.ts b/packages/rest/src/data-nested-object-door.test.ts index 24715c91543..76765f4e78c 100644 --- a/packages/rest/src/data-nested-object-door.test.ts +++ b/packages/rest/src/data-nested-object-door.test.ts @@ -578,18 +578,20 @@ for (const cell of CELLS) { 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 }; - engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { - if (opCtx.object === TEN_GRID && opCtx.operation === 'find') grids.n += 1; - return next(); - }); - 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); + 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 () => {