Skip to content

Commit 9a7f8c1

Browse files
feat(objectql): a nested-relation condition on a read verb is one read-scoped in-database subquery per relationship, up to three, where it is provably the same read as the id read (#33652)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DWLrF6ZURGN6BVpSbuDyHTg)_ Part of #33626 — the engine and analytics halves land here; the card stays open until #33876 lands maintainer ruling Q2 (the engine's `INVALID_FILTER` / 400 for MongoDB / OData, with the ADR-0139 capability bit). The other parts are their own follow-up cards citing #33626 and its rulings: #33875 (skills text, Tier H), #33876 (above, Tier H), #33877 (multi-valued relation as a JSON-membership semi-join), #33878 (a dataset measure's own `filter`). 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). Area-lease pilot #33059, area A3. Contract record 6898853007 (PASS on `96c23127`, no must-fix) is answered on this head: S2–S5 and N2 below. The L2 record 6900638852 (PASS on `2d2eaa73`) is answered too: S1 by the seat's option C (the author-facing rule on both docs pages, the planned-leaf docblock), S2 by this body, S3 by the seat's rulings (Acceptance notes), N2 in the pin. ## 维护者速读 - 改了什么:在上一版「只在可证明等同时走库内子查询」的基础上,把注册表能直接判定的回退提前到规划之前:关联对象是联邦对象(external),或在有组织墙的租户姿态下两个对象的租户类别不同,直接走 id 读取,关联读取只执行一次;changeset 与两篇文档列全了所有仍走 id 读取(及 1000 上限)的情形,并写明:在驱动调用之后收窄关联对象行的读规则,只有注册在该对象上(对象级中间件或 afterFind 钩子)才约束关系条件。本轮合并 main,解决与 #33897(View All 读者丢弃必填主表的父链)在 `engine-readable-ids-permission-formula.ts` 的冲突:两者都保留,先执行 View All 丢弃,再只对丢弃后仍保留的关系条件叶子做 id 预读;调用者写在必填主表上的关系条件永不随主表自身的读取范围一起被丢弃。 - 为什么改:合同评审 6898853007 指出联邦关联对象的子查询不能证明等同、回退时关联对象的中间件与 beforeFind 钩子会执行两次、驱动选项比较只钉了一个方向、文档漏列两种回退情形。 - 风险与回滚:所有改动都只把更多情形导向 main 原有的 id 读取(更保守);规划后才能判定的回退(中间件自行应答、只有本次请求决定的驱动选项差异)仍会二次执行,已在文档与 changeset 声明并钉住次数。冲突解决改变了两项改动交汇处的行为,属于已解决的冲突,需补 delta L1 与 L2 评审。回滚即 revert 本 PR。 - 先看:`packages/objectql/src/engine-readable-ids-permission-formula.ts`(`composeReadableIdsChain` 末尾:View All 丢弃与关系条件叶子的交汇)、`packages/objectql/src/relation-semi-join.ts`(`relationSemiJoinServes` 的两条规划前判定)、`packages/rest/src/data-nested-object-door.test.ts`(真实 SQLite / PG 上两个方向的驱动选项与租户类别钉子)。 - 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run src/data-nested-object-door.test.ts`,预期全部通过(PG 单元需 `OS_TEST_POSTGRES_URL`,未设时跳过)。 - 需要你做的:无,席位落地(卡片保持打开,等 #33876;注册时声明的裁决见 #34155)。 ## What changes - **The registry-answered fallbacks are decided before planning** (`relationSemiJoinServes`), so the related read is dispatched once, as the id read: a federated related object (ADR-0015 `external`), and, under a posture that walls organizations, a related object of another tenancy class than the read's object (one tenant-scoped, the other platform-global or federated, `isDriverTenantScopedSchema` in `engine-driver-options.ts`, the one spelling `buildDriverOptions` also reads). - **What is still decided after planning dispatches the related read twice**, declared in the changeset and both docs pages and pinned by count: a related read a middleware answers itself or adds rows to (after planning), and driver options that differ only by what the request records per object (at the executor boundary). Under the `single` posture two tenancy classes read under the same options and still compose (CONTROL). - **The driver-options comparison is pinned in both directions on a real driver** (SQLite, PostgreSQL 16): the outer read unscoped with the related read scoped, and the opposite; and the tenancy-class decision in its other direction (a tenant-scoped read on a related object that is no tenant's), with the related read dispatched once. - **Docs and changeset** list every case that keeps the id read and its 1,000 cap, adding the two missing ones (a related object read under different driver options than the read's own object, most commonly its tenant scope; a related read a middleware answers itself) and the federated related object. - **The author-facing rule for after-driver read rules** is on both docs pages and in the `planRelationSemiJoinLeaf` docblock: 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 (the bound ADR-0139 D5.2 sets for a `ReadableIds` parent). - Behaviour on every other path is unchanged from `96c23127`. ## Tests On head `6062ec9c` (the merge of `origin/main` at `86350e12`, conflict resolved against #33897): `@objectstack/objectql` full suite **598/598 files, 13278/13278 tests**, typecheck exit 0; `@objectstack/rest` full suite with `OS_TEST_POSTGRES_URL` (private PostgreSQL 16) **413/413 files, 8672 passed / 144 skipped**, typecheck exit 0; `@objectstack/service-analytics` full suite **215/215 files, 5229 passed / 335 skipped**, typecheck exit 0; #33897's two `@objectstack/plugin-security` pin files (`security-plugin-cbp-read-filter.test.ts`, `controlled-by-parent-leaf-switch.test.ts`) **35/35**; `engine-readable-ids-nested-composition.test.ts` (#33897's harness, with the new interaction pin) and `engine-nested-relation-lowering.test.ts` **48/48**. ESLint `--no-inline-config` on the two changed TS files exit 0. <details><summary>Ablation of the interaction (one-shot, not kept)</summary> With the merge committed, the line that keeps a planned relation leaf out of the View-All drop was removed with `scripts/ablation-replace.mjs` (anchor 1 to 0, blob `4bf1bd36` to `e2e97ca8`): `engine-readable-ids-nested-composition.test.ts` 1 failed / 17 passed, the one red being the new interaction pin. Restored to the `HEAD` blob `4bf1bd36`, `git diff HEAD` empty. The pin reads `src/`, so no rebuild leg. </details> Earlier heads, below. Counts on head `2d2eaa73` (the merge of `origin/main` at `63db7240` included) unless marked; local box, shared verify lock, private PostgreSQL 16 for the live cells. On `6cf1ce0e` (docs, a docblock and one pin's counter): `data-nested-object-door.test.ts` 30 passed / 15 skipped, `engine-nested-relation-lowering.test.ts` 30/30, objectql and rest typecheck exit 0, ESLint `--no-inline-config` on the two changed TS files exit 0, and every docs family of the derived list exit 0 (`check:skill-examples` NOT MEASURED locally: client SDK `dist` not built in this worktree; it passed on `2d2eaa73`). - `@objectstack/objectql` full suite: **598/598 files, 13258/13258 tests**; typecheck (`tsc --noEmit` plus `check:test-typecheck`) exit 0. - `@objectstack/rest` full suite with `OS_TEST_POSTGRES_URL`: **413/413 files, 8672 passed / 144 skipped**; typecheck exit 0. `data-nested-object-door.test.ts`: 30 passed / 15 skipped (the MySQL cell, no server), SQLite and PostgreSQL cells each running the two-tenant describe (now with the other tenancy direction) and the new executor-boundary describe (both directions). - `@objectstack/service-analytics` full suite: **215/215 files, 5229 passed / 335 skipped**; typecheck exit 0. - `engine-nested-relation-lowering.test.ts`: 30/30 — the federated and the two tenancy-class fallbacks decided before planning with one dispatch, the `single`-posture CONTROL that still composes, the boundary fallback and the middleware-answered fallback with two dispatches each. <details><summary>Ablation (one-shot, not kept)</summary> Each guard of this round was mutated with `scripts/ablation-replace.mjs` (anchor hit, blob checked), the pins run, and the file restored to the `HEAD` blob (`9231631f`, `git diff HEAD` empty) before the next leg; where a pin reads `dist/`, objectql was rebuilt and `ablation-dist-preflight.mjs` confirmed the marker (exit 0), and after the last leg a rebuild with `--absent` confirmed all four markers gone. - The federated check in `relationSemiJoinServes`: objectql 1 red (the federated pin). - The tenancy-class check: objectql 2 red (both directions, dispatch count 2 where 1 is pinned); rest 2 red (the other tenancy direction, SQLite and PostgreSQL, dispatch count). - `sameReadDriverOptions` reading the outer read's keys only: objectql 1 red (the boundary pin); rest 2 red ("the outer read is unscoped, the related read scoped", both cells). - `sameReadDriverOptions` reading the related read's keys only: rest 2 red ("the outer read is scoped, the related read unscoped", both cells); the objectql boundary pin stays green, as that pin's direction predicts. </details> ## Acceptance notes - **S1, by the seat's option C.** The author-facing rule is stated on both docs pages and in the `planRelationSemiJoinLeaf` docblock: a read rule that narrows a related object's rows after its driver call bounds a relation condition only when it is registered for that object (an object-keyed middleware or an `afterFind` hook), as ADR-0139 D5.2 bounds a `ReadableIds` parent. A registration-time declaration that would let the engine know such rules by another fact is #34155 (`needs-user-decision`: it widens the spec contracts surface). - **A second dispatch on a fallback after planning.** A hop whose fallback is decided only after the related read was planned — a middleware answering the related read, or driver options only the request sets — runs the related object's middleware chain and `beforeFind` hooks twice (planned, then the id read), where main ran them once. Declared in the changeset and both docs pages; pinned as two dispatches (`engine-nested-relation-lowering.test.ts`), with one dispatch pinned for every registry-decided fallback. - **Seat 6's commits taken.** Four commits from `claude/project-thread-m4k79t` (tip `39056411`) are cherry-picked with `-x`: `6e35a5e5` and `d599a82e` with their wording on one after-driver boundary left out (that boundary is S1, above), `6c7f6aef` and `39056411` unchanged. An earlier work-in-progress commit of this round (`777c4d06`) duplicated the first and is reverted on the branch (`dc2fd16a`), no history rewritten. - **Where the 1,000 cap stays.** For a federated related object the cap stays, by the seat's ruling (S3 option A, area S2 thread): no driver prepares a remote object that appears only inside a subquery. For a single-valued hop across tenancy classes under an organization wall the cap stays at this head; serving it as a subquery carrying the related read's own driver options is #34157. - **Conflict against #33897, resolved.** `origin/main` (`86350e12`) carried #33897 (`3c2fb325`, card #33696, ruling 6893666857), which conflicted with this branch in `packages/objectql/src/engine-readable-ids-permission-formula.ts` (the imports and `composeReadableIdsChain`'s tail). Both are kept: the View-All drop of a required master's leaf over unrestricted hops runs first; a leaf the nested-relation lowering planned is the caller's own condition on the master, never the master's read scope, so the drop never removes it (without that exclusion it would have dropped the caller's condition, pinned by the new interaction pin and its ablation); the planned-leaf id read runs only for leaves that survive the drop; the composition runs over the pruned tree. Both import sets are kept. `engine.ts` auto-merged, and its change from main is only the `_registry` accessor #33897 adds to the chain host. This is a resolved conflict, so delta L1 and L2 reviews are owed on `6062ec9c`. - **N2 (title).** The title already qualifies the subquery as "where it is provably the same read as the id read" and carries no "no id cap" promise; it is unchanged. - driver-memory serves the form in process (maintainer ruling Q1 on #33626, comment 6889549817). - MongoDB / OData keep main's capped id read (no refusal); the ruled engine `INVALID_FILTER` / 400 and the ADR-0139 capability bit are #33876, which is why this PR is `Part of`. Until that bit exists the engine plans the subquery only for the drivers it names. - `skills/objectstack-query` still teaches "up to 1000 related ids" and one level (governed, #33875). - The echo of a dataset `filter` carrying a served cross-object leaf refuses `INVALID_FILTER` (it refused `INVALID_FIELD` before); both are 400 refusals of a statement that cannot be printed. - The one hop-limit constant for objectql and service-analytics is not in this PR: `@objectstack/objectql` is only a devDependency of `@objectstack/service-analytics`, so sharing it needs a runtime dependency or a `@objectstack/spec` export; the two stay tied by their docblocks. Resume-from: claude/area-A3-33626@6062ec9c411903fa920343fde05537b5c46a4d9a ## Verification <details><summary>Gate families (dispatch-gates --commands / --ran)</summary> On `6062ec9c`: 106 families derived from the merge-base diff; `--ran` with an exit code per family: 106 accounted, 104 run exit 0, 2 NOT MEASURED (derived from a recorded exit 3, PREREQUISITE NOT MET: `check:skill-examples` and `check:dual-build-cjs-loads` read the `dist/` of packages outside this diff's build closure, not built in this worktree; both are CI's, in `Lint & Repo Gates`). `check:nul-bytes` exit 0. On `2d2eaa73`: 106 accounted, 106 run, 0 NOT MEASURED. </details> No CI ran on `6cf1ce0e`: the PR was not mergeable against main (the conflict above). CI on `6062ec9c`: see the PR checks. <details><summary>CI on 2d2eaa7 (an earlier head)</summary> 53 check-runs, all completed: 36 success, 15 skipped, 2 failure. `Lint & Repo Gates`, `TypeScript Type Check`, `Build Core`, `Check Changeset`, `Governed Surface Queue Guard`, `Dogfood Regression Gate` and `Test Core` 1–3 and 5–8 are success. `Test Core (4/8)` (and the `Test Core` roll-up) is red on `@objectstack/scenarios` `test/runner/run-date.test.ts`, two cases "Test timed out in 5000ms"; that package is outside this diff (tracked as #34081). Every other package in that shard passed. </details> <details><summary>Declaration lines and merges</summary> The `Clause-②:` and `Metadata-protocol:` lines are copied byte for byte from `.changeset/33626-relation-semi-join.md`. `git merge-tree --write-tree` of `6062ec9c` against `origin/main` at `0d1443d0`: no conflict. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh <!-- signed: domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent babda9d commit 9a7f8c1

27 files changed

Lines changed: 1623 additions & 223 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/service-analytics': minor
4+
---
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
7+
8+
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.
9+
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.
10+
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).

‎content/docs/kernel/contracts/data-engine.mdx‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -193,15 +193,43 @@ multiple). The engine serves it in `where`, the same on every driver: it reads t
193193
related object with the condition **as the caller** — that object's row scope and field
194194
permissions apply, so a condition on a field the caller cannot read is refused
195195
(`PERMISSION_DENIED` / 403), never answered with an empty list — and then matches the
196-
relation field against the ids that read returns: `$in` on a single-valued relation, any
197-
member on a multi-valued one (`multiple: true`). No related record matching selects no
196+
relation field against what that read selects: on a read verb, a single-valued relation is
197+
one subquery inside the read's own statement where that is provably the same read (the
198+
related read is planned, not run: its read scope and the condition become the subquery's
199+
`WHERE`, so no id list is read and none is capped — the related object's read restrictions
200+
the planned read observes are carried into the subquery, or the hop falls back to the id
201+
read); otherwise `$in` on the
202+
ids that read returns, any member on a multi-valued one (`multiple: true`). No related record matching selects no
198203
rows; under `$not`, a record whose relation is empty satisfies the negation.
199204

200-
It reaches **one level**: every key must be a field the related object declares
201-
(`{ account: { owner: { region: 'NA' } } }` and the dotted `{ account: { 'owner.region': 'NA' } }`
202-
are refused), and a condition matching more than 1,000 related records is refused with
203-
`INVALID_FILTER` / 400 rather than run over a cut-off list. For either, run the two steps
204-
yourself — filter the related object, then match its ids:
205+
It reaches **up to three relationships** (ADR-0071's hop limit): every key must be a field
206+
the related object declares, and a relation key may carry a condition of its own
207+
(`{ account: { owner: { region: 'NA' } } }`), each hop read as the caller with its own read
208+
scope; a fourth relationship and the dotted `{ account: { 'owner.region': 'NA' } }` are
209+
refused. Where ids are read (a multi-valued relation, `update`, `delete`) a
210+
condition matching more than 1,000 related records is refused with `INVALID_FILTER` / 400
211+
rather than run over a cut-off list. The id read, with that cap, is also what serves a
212+
single-valued relation on a read verb in each of these cases:
213+
214+
- a related object on another datasource;
215+
- a federated related object;
216+
- a driver that compiles no subquery (MongoDB, OData — the SQL drivers compile it, the
217+
in-memory driver evaluates it in process);
218+
- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes;
219+
- a related object read under different driver options than the outer object (its tenant
220+
scope, most commonly) — decided before the related read is planned where the registry
221+
answers it (the two objects' tenancy class under a walled posture), at the executor
222+
boundary otherwise;
223+
- a related read that a middleware answers itself (or adds rows to after the driver call).
224+
225+
A read rule that narrows a related object's rows after its driver call bounds a relation
226+
condition on that object only when it is registered for that object — as an object-keyed
227+
middleware or an `afterFind` hook; registered that way, the hop keeps the id read.
228+
229+
A hop that falls back after planning (a middleware answering the related read, or driver
230+
options only the request decides) dispatches the related read twice: its middleware chain and `beforeFind` hooks run for the
231+
planned read and again for the id read. Past the cap, run the two steps yourself — filter
232+
the related object, then match its ids:
205233

206234
```typescript
207235
const tech = await engine.find('account', { where: { industry: 'tech' }, fields: ['id'] });

‎content/docs/protocol/objectql/query-syntax.mdx‎

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -687,25 +687,68 @@ const opportunities = await engine.find('opportunity', {
687687

688688
A condition on a related record's fields beneath a relation field (`lookup`,
689689
`master_detail`, `user`, `tree`) is served in `where`: the engine reads the
690-
related object with it **as the caller**, then matches the field against the
691-
ids it returns (`$in`; any member when `multiple: true`).
692-
693-
Limits — one level: every key a field the related object declares, no relation
694-
or dotted key inside; forward only: never a parent by its children; `where`
690+
related object with it **as the caller**. On a read verb (`find`, `findOne`,
691+
`count`, `aggregate`) a single-valued relation is matched in the database
692+
where that is provably the same read: the related read is planned, not run,
693+
and the driver receives one statement with a subquery,
694+
`account IN (SELECT id FROM account WHERE <its read scope> AND <condition>)` —
695+
no id list, no cap. The related object's read restrictions the planned read
696+
observes are carried into the subquery, or the hop falls back to reading the
697+
related ids as the caller and matching them with `$in`, under the cap below.
698+
Otherwise (a multi-valued
699+
relation, or `update` / `delete`) the field is matched against the ids the
700+
related read returns (`$in`; any member when `multiple: true`).
701+
702+
Limits — up to three relationships (ADR-0071's hop limit): every key a field the
703+
related object declares, and a relation key may hold a condition of its own on
704+
its related object (`{ account: { owner: { region: 'NA' } } }`), each hop read as
705+
the caller and nested as a subquery; no dotted key; forward only: never a parent by its children; `where`
695706
only: an aggregation's `filter` and `having` refuse it, `INVALID_FILTER` / 400;
696-
at most 1000 related ids, refused past that, `INVALID_FILTER` / 400, never
697-
truncated; as the caller: the related object's row scope and field permissions
707+
where ids are read, at most 1000 of them, refused past that,
708+
`INVALID_FILTER` / 400, never truncated; the subquery form is taken only on
709+
the related object's own datasource and on a driver that compiles it — the SQL
710+
drivers (every `driver-sql` dialect, Turso) compile it and the in-memory driver
711+
evaluates it in process; as the caller: the related object's row scope and field permissions
698712
apply, so a field the caller cannot read is refused, `PERMISSION_DENIED` / 403,
699713
never an empty result.
700714

715+
A single-valued relation on a read verb keeps the id read, and its 1000-id cap, in each
716+
of these cases:
717+
718+
- a related object on another datasource;
719+
- a federated related object;
720+
- a driver that compiles no subquery (MongoDB, OData);
721+
- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes;
722+
- a related object read under different driver options than the outer object (its tenant
723+
scope, most commonly) — decided before the related read is planned where the registry
724+
answers it (the two objects' tenancy class under a walled posture), at the executor
725+
boundary otherwise;
726+
- a related read that a middleware answers itself (or adds rows to after the driver call).
727+
728+
A hop that falls back after planning (a middleware answering the related read, or driver
729+
options only the request decides) dispatches the related read twice: its middleware chain
730+
and `beforeFind` hooks run for the planned read and again for the id read.
731+
732+
A read rule that narrows a related object's rows after its driver call bounds a relation
733+
condition on that object only when it is registered for that object — as an object-keyed
734+
middleware or an `afterFind` hook; registered that way, the hop keeps the id read.
735+
701736
- **Every verb that takes a `where`** serves it — `find`, `findOne`, `count`,
702737
`aggregate`, `update` and `delete` — and so do the REST `GET /data/:object` and
703738
`POST /data/:object/query` doors, which read through the same engine calls. A
704-
single-valued relation matches with `$in` on the related ids; a multi-valued one
739+
single-valued relation matches with a subquery on a read verb (or with `$in` on the
740+
related ids in the cases listed above) and with `$in` on the related ids on
741+
`update` / `delete`; a multi-valued one
705742
(`multiple: true`) matches a record when **any** member qualifies, written as one
706743
`$contains` per id under an `$or`.
707-
- **A second level is refused.** `{ account: { owner: { region: 'NA' } } }` and
708-
`{ account: { 'owner.region': 'NA' } }` answer `INVALID_FILTER` / 400.
744+
- **A related record the caller cannot read never matches**, whatever the operator:
745+
`{ account: { status: { $ne: 'cancelled' } } }` leaves out a row whose account is
746+
absent or hidden from the caller, as well as one whose account is cancelled.
747+
- **Up to three relationships.** `{ account: { owner: { region: 'NA' } } }` reads
748+
`user` as the caller, then `account` as the caller with the owner subquery inside,
749+
and every hop carries its own object's row scope and field check; a related record
750+
the caller cannot read at any hop excludes the row. A fourth relationship, and the
751+
dotted `{ account: { 'owner.region': 'NA' } }`, answer `INVALID_FILTER` / 400.
709752
- **The reverse direction is not served.** A parent filtered by its children is not
710753
written as `{ opportunities: { stage: 'won' } }`: the parent has no such field, so the
711754
REST doors answer `INVALID_FIELD` / 400.

‎packages/objectql/src/engine-count-aggregate.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ export async function count(
154154
// `find()` fallback below composes at its own boundary.
155155
return driver.count(
156156
object,
157-
await this.composeReadableIdsAtBoundary(object, 'count', opCtx.ast as QueryAST, opCtx.context),
157+
await this.composeReadableIdsAtBoundary(object, 'count', opCtx.ast as QueryAST, opCtx.context, countOpts),
158158
countOpts,
159159
);
160160
}

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,7 +1289,11 @@ export class DeleteAndAggregateFacet {
12891289
// [ADR-0139 D2] The executor boundary, once for BOTH driver paths below
12901290
// (they are exclusive, and the rows path keeps this `where` by
12911291
// reference): the AST is final once the chain has run.
1292-
const ast = await this.composeReadableIdsAtBoundary(object, 'aggregate', opCtx.ast as QueryAST, opCtx.context);
1292+
// One driver-options bag for the boundary and whichever driver call
1293+
// below runs: a planned relation leaf is composed only when these
1294+
// are the related read's own (`relation-semi-join.ts`).
1295+
const aggregateOptions = this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict });
1296+
const ast = await this.composeReadableIdsAtBoundary(object, 'aggregate', opCtx.ast as QueryAST, opCtx.context, aggregateOptions);
12931297

12941298
// Prefer driver.aggregate() when available — driver.find() in many
12951299
// drivers (e.g. driver-sql) does not honor `groupBy` / `aggregations`
@@ -1353,7 +1357,7 @@ export class DeleteAndAggregateFacet {
13531357
// natively today; one that grows native support must advertise a
13541358
// capability flag, at which point this post-filter becomes the
13551359
// fallback tier — the dateGranularity two-tier pattern.
1356-
const aggregated = await drv.aggregate(object, ast, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }));
1360+
const aggregated = await drv.aggregate(object, ast, aggregateOptions);
13571361
return applyHaving(aggregated, ast.having, havingColumnClasses);
13581362
}
13591363
// In-memory fallback path: ask the driver for raw rows, then bucket +
@@ -1396,7 +1400,7 @@ export class DeleteAndAggregateFacet {
13961400
delete rowsAst.groupBy;
13971401
delete rowsAst.aggregations;
13981402
delete rowsAst.having;
1399-
const raw = await driver.find(object, rowsAst, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }));
1403+
const raw = await driver.find(object, rowsAst, aggregateOptions);
14001404
return applyHaving(applyInMemoryAggregation(raw, ast, tz, declaredFields), ast.having, havingColumnClasses);
14011405
});
14021406

‎packages/objectql/src/engine-driver-options.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ export function buildDriverOptions(
318318
// federated object by — one spelling of "this schema is the remote's",
319319
// not a second reading of it.
320320
const isFederated = isFederatedObject(objectSchema);
321-
const tenantObject = !isTenancyDisabled(objectSchema) && !isFederated;
321+
const tenantObject = isDriverTenantScopedSchema(objectSchema);
322322
const tenantScope = tenantObject
323323
? scope.writeTarget
324324
? this.driverWriteTarget(execCtx)
@@ -411,6 +411,17 @@ export function buildDriverOptions(
411411
return opts;
412412
}
413413

414+
/**
415+
* Whether a read of an object with this schema can hand its driver a tenant
416+
* scope at all — the object's tenancy class: neither tenancy-disabled
417+
* (ADR-0066 platform-global posture) nor federated (ADR-0015 `external`).
418+
* The one spelling {@link buildDriverOptions} and the relation semi-join
419+
* (`relation-semi-join.ts`) both ask.
420+
*/
421+
export function isDriverTenantScopedSchema(objectSchema: unknown): boolean {
422+
return !isTenancyDisabled(objectSchema) && !isFederatedObject(objectSchema);
423+
}
424+
414425
/**
415426
* [ADR-0131 D8] The driver's native read scope for one operation — the Layer
416427
* 0 verdict projected onto `DriverOptions` (see {@link buildDriverOptions}).

‎packages/objectql/src/engine-find.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@
3030
*/
3131

3232
import { SortNodeSchema, lowerFilterCondition, resolveSearchFieldResolution } from '@objectstack/spec/data';
33-
import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data';
33+
import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data';
3434
import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js';
35+
import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js';
3536
import type { ExecutionContext } from '@objectstack/spec/kernel';
3637
import { isMissingTableError } from '@objectstack/metadata/errors';
3738
import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js';
@@ -545,7 +546,18 @@ export class FindFacet {
545546
// [ADR-0139 D2] The executor boundary: the AST is final here — after the
546547
// doors, the middleware chain and `beforeFind` — so every `ReadableIds`
547548
// leaf is composed (or refused) on it, immediately before the driver.
548-
const driverAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context);
549+
const driverAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context, driverOptions);
550+
// [relation semi-join] A PLANNED read (`relation-semi-join.ts`): the
551+
// final `where` and the driver options are handed to the planner in
552+
// place of the driver call, and the read answers the plan's own empty
553+
// rows. Only the engine's own nested-relation lowering sets this
554+
// symbol-keyed option.
555+
const plan = (options as Record<symbol, unknown> | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined;
556+
if (plan !== undefined) {
557+
plan.capture(driverAst.where as FilterCondition | undefined, driverOptions);
558+
opCtx.result = plan.rows;
559+
return opCtx.result;
560+
}
549561

550562
try {
551563
let result = await driver.find(object, driverAst, driverOptions);
@@ -837,7 +849,7 @@ export class FindFacet {
837849
const driverOptions = this.buildDriverOptions(objectName, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict });
838850
hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions);
839851
// [ADR-0139 D2] The executor boundary, as in `find`.
840-
const driverAst = await this.composeReadableIdsAtBoundary(objectName, 'findOne', hookContext.input.ast as QueryAST, opCtx.context);
852+
const driverAst = await this.composeReadableIdsAtBoundary(objectName, 'findOne', hookContext.input.ast as QueryAST, opCtx.context, driverOptions);
841853

842854
let result = await driver.findOne(objectName, driverAst, driverOptions);
843855

0 commit comments

Comments
 (0)