Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
f2db463
wip(objectql): serve a single-valued nested-relation condition as an …
claude Nov 15, 2026
878e274
test(objectql): pin the semi-join lowering of a single-valued nested-…
claude Nov 15, 2026
3ef758f
test(rest): semi-join parity, $ne under row scope, and the lifted sin…
claude Nov 15, 2026
aa6187f
docs(objectql): describe the semi-join form of a nested-relation cond…
claude Nov 15, 2026
bc5ef48
test(objectql): the conformance stub driver evaluates a composed Read…
claude Nov 15, 2026
f6ab355
Merge remote-tracking branch 'origin/main' into claude/area-A3-33626
claude Nov 15, 2026
e96278a
feat(objectql): a nested-relation condition reaches up to three relat…
claude Nov 15, 2026
0e78945
test(rest): three-hop nested-relation parity, NULL / missing parent /…
claude Nov 15, 2026
7ea2601
feat(service-analytics): a dotted where leaf up to three relationship…
claude Nov 15, 2026
f4738f5
docs(service-analytics): the served where and dataset filter reach th…
claude Nov 15, 2026
cad68d0
test(service-analytics): name the three-hop fixture's second field so…
claude Nov 15, 2026
035916f
Merge origin/main into claude/area-A3-33626
claude Nov 15, 2026
592ab16
wip(objectql): the relation semi-join is taken only where it is the i…
claude Nov 15, 2026
5391307
fix(objectql): the relation semi-join falls back to the id read where…
claude Nov 15, 2026
cdf3f50
fix(service-analytics,objectql): echo copy, docs and changeset follow…
claude Nov 15, 2026
5d3fa51
test(rest): the two-tenant pins run one hop and three hops as separat…
claude Nov 15, 2026
3194cba
test(objectql): a read whose leaves are all planned spends no securit…
claude Nov 15, 2026
1b832c5
refactor(objectql): the semi-join eligibility reads the engine throug…
claude Nov 15, 2026
96c2312
test(objectql,rest): type the new pins' query options instead of eras…
claude Nov 15, 2026
58cc0d9
Merge origin/main into claude/area-A3-33626
claude Nov 15, 2026
777c4d0
wip(objectql): decide the registry-answered fallbacks before planning
claude Nov 15, 2026
dc2fd16
revert(objectql): withdraw the work-in-progress commit in favour of t…
claude Nov 15, 2026
7f402dc
fix(objectql): decide the federated and tenancy-class fallbacks befor…
claude Nov 15, 2026
302a6bc
docs(objectql): list every case that keeps the id read and its cap
claude Nov 15, 2026
c1b3657
test(rest): pin the executor boundary's driver-options comparison in …
claude Nov 15, 2026
cfe68c6
test(objectql): give the two new federated-object questions their cen…
claude Nov 15, 2026
2d2eaa7
test(objectql,rest): pin the dispatch count of a fallback after plann…
claude Nov 15, 2026
6cf1ce0
docs(objectql): state the form a read rule takes to bound a relation …
claude Nov 15, 2026
6062ec9
Merge origin/main into claude/area-A3-33626
claude Nov 15, 2026
cc52339
Merge origin/main into claude/area-A3-33626
claude Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/33626-relation-semi-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/objectql': patch
'@objectstack/service-analytics': minor
---

feat(objectql): a nested-relation condition on a read verb is an in-database subquery per relationship, up to three relationships, where that is provably the same read as the id read; analytics serves the dataset's own `filter` the same way

Clause-②: yes (widening) — `{ account: { status: { $ne: 'cancelled' } } }` on `find`, `findOne`, `count` and `aggregate` (and so every analytics face that hands the engine the nested form) is served whatever the number of matching related records on a driver that compiles the subquery (the SQL drivers; the in-memory driver evaluates it in process), where more than 1,000 answered `INVALID_FILTER` / 400. The related read is planned through its whole pipeline as the caller and its final `where` becomes the subquery's scope; related-object read restrictions the planned read observes are carried into the subquery, or the hop falls back to the id read (the related object read as the caller, then `$in`, under the 1,000 cap). A relation key inside the condition may now carry a condition of its own, down to ADR-0071's three relationships (`{ contact: { account: { region: { name: 'NA' } } } }`), where a second level answered `INVALID_FILTER` / 400; each hop is that object's own read, and a fourth relationship is refused by name. On the analytics engine-aggregate path a dotted `where` leaf through up to three relationships (`order.customer.tier`), and a cross-object leaf in a compiled dataset's own definition-level `filter`, reach the engine as that nested condition, where both answered `INVALID_FIELD` / 400. Still the id read, under the 1,000 cap: a related object on another datasource, a federated related object, a driver that compiles no subquery (MongoDB, OData), a related object an object-scoped middleware or an `afterFind` hook shapes, a related object read under different driver options than the outer object (decided before planning where the registry answers it: the two objects' tenancy class under a walled posture), a related read that a middleware answers itself, a multi-valued relation and the `update` / `delete` verbs. A hop that falls back after planning dispatches the related read twice: its middleware chain and `beforeFind` hooks run for the planned read and again for the id read. A per-measure `filter` carrying a cross-object leaf stays refused. The SQL echo of a dataset `filter` carrying a served cross-object leaf refuses `INVALID_FILTER` / 400 where it refused `INVALID_FIELD` / 400; neither printed a statement.
Metadata-protocol: added — a compiled dataset's definition-level `filter` (`@objectstack/service-analytics`) now accepts a cross-object leaf on the engine-aggregate path, where it answered `INVALID_FIELD` / 400: a new accepted value for a dataset author.
Skills-docs: `content/docs/protocol/objectql/query-syntax.mdx` and `content/docs/kernel/contracts/data-engine.mdx` describe the subquery, the three-relationship limit, where the id read and its cap still apply and which drivers compile the subquery. `skills/objectstack-query` still says "up to 1000 related ids" and one level for every relation; that is now stricter than the engine for a single-valued relation on a read verb (a follow-up skills-only change, governed).
42 changes: 35 additions & 7 deletions content/docs/kernel/contracts/data-engine.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,43 @@ multiple). The engine serves it in `where`, the same on every driver: it reads t
related object with the condition **as the caller** — that object's row scope and field
permissions apply, so a condition on a field the caller cannot read is refused
(`PERMISSION_DENIED` / 403), never answered with an empty list — and then matches the
relation field against the ids that read returns: `$in` on a single-valued relation, any
member on a multi-valued one (`multiple: true`). No related record matching selects no
relation field against what that read selects: on a read verb, a single-valued relation is
one subquery inside the read's own statement where that is provably the same read (the
related read is planned, not run: its read scope and the condition become the subquery's
`WHERE`, so no id list is read and none is capped — the related object's read restrictions
the planned read observes are carried into the subquery, or the hop falls back to the id
read); otherwise `$in` on the
ids that read returns, any member on a multi-valued one (`multiple: true`). No related record matching selects no
rows; under `$not`, a record whose relation is empty satisfies the negation.

It reaches **one level**: every key must be a field the related object declares
(`{ account: { owner: { region: 'NA' } } }` and the dotted `{ account: { 'owner.region': 'NA' } }`
are refused), and a condition matching more than 1,000 related records is refused with
`INVALID_FILTER` / 400 rather than run over a cut-off list. For either, run the two steps
yourself — filter the related object, then match its ids:
It reaches **up to three relationships** (ADR-0071's hop limit): every key must be a field
the related object declares, and a relation key may carry a condition of its own
(`{ account: { owner: { region: 'NA' } } }`), each hop read as the caller with its own read
scope; a fourth relationship and the dotted `{ account: { 'owner.region': 'NA' } }` are
refused. Where ids are read (a multi-valued relation, `update`, `delete`) a
condition matching more than 1,000 related records is refused with `INVALID_FILTER` / 400
rather than run over a cut-off list. The id read, with that cap, is also what serves a
single-valued relation on a read verb in each of these cases:

- a related object on another datasource;
- a federated related object;
- a driver that compiles no subquery (MongoDB, OData — the SQL drivers compile it, the
in-memory driver evaluates it in process);
- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes;
- a related object read under different driver options than the outer object (its tenant
scope, most commonly) — decided before the related read is planned where the registry
answers it (the two objects' tenancy class under a walled posture), at the executor
boundary otherwise;
- a related read that a middleware answers itself (or adds rows to after the driver call).

A read rule that narrows a related object's rows after its driver call bounds a relation
condition on that object only when it is registered for that object — as an object-keyed
middleware or an `afterFind` hook; registered that way, the hop keeps the id read.

A hop that falls back after planning (a middleware answering the related read, or driver
options only the request decides) dispatches the related read twice: its middleware chain and `beforeFind` hooks run for the
planned read and again for the id read. Past the cap, run the two steps yourself — filter
the related object, then match its ids:

```typescript
const tech = await engine.find('account', { where: { industry: 'tech' }, fields: ['id'] });
Expand Down
63 changes: 53 additions & 10 deletions content/docs/protocol/objectql/query-syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -687,25 +687,68 @@ const opportunities = await engine.find('opportunity', {

A condition on a related record's fields beneath a relation field (`lookup`,
`master_detail`, `user`, `tree`) is served in `where`: the engine reads the
related object with it **as the caller**, then matches the field against the
ids it returns (`$in`; any member when `multiple: true`).

Limits — one level: every key a field the related object declares, no relation
or dotted key inside; forward only: never a parent by its children; `where`
related object with it **as the caller**. On a read verb (`find`, `findOne`,
`count`, `aggregate`) a single-valued relation is matched in the database
where that is provably the same read: the related read is planned, not run,
and the driver receives one statement with a subquery,
`account IN (SELECT id FROM account WHERE <its read scope> AND <condition>)` —
no id list, no cap. The related object's read restrictions the planned read
observes are carried into the subquery, or the hop falls back to reading the
related ids as the caller and matching them with `$in`, under the cap below.
Otherwise (a multi-valued
relation, or `update` / `delete`) the field is matched against the ids the
related read returns (`$in`; any member when `multiple: true`).

Limits — up to three relationships (ADR-0071's hop limit): every key a field the
related object declares, and a relation key may hold a condition of its own on
its related object (`{ account: { owner: { region: 'NA' } } }`), each hop read as
the caller and nested as a subquery; no dotted key; forward only: never a parent by its children; `where`
only: an aggregation's `filter` and `having` refuse it, `INVALID_FILTER` / 400;
at most 1000 related ids, refused past that, `INVALID_FILTER` / 400, never
truncated; as the caller: the related object's row scope and field permissions
where ids are read, at most 1000 of them, refused past that,
`INVALID_FILTER` / 400, never truncated; the subquery form is taken only on
the related object's own datasource and on a driver that compiles it — the SQL
drivers (every `driver-sql` dialect, Turso) compile it and the in-memory driver
evaluates it in process; as the caller: the related object's row scope and field permissions
apply, so a field the caller cannot read is refused, `PERMISSION_DENIED` / 403,
never an empty result.

A single-valued relation on a read verb keeps the id read, and its 1000-id cap, in each
of these cases:

- a related object on another datasource;
- a federated related object;
- a driver that compiles no subquery (MongoDB, OData);
- a related object whose reads an object-scoped middleware or an `afterFind` hook shapes;
- a related object read under different driver options than the outer object (its tenant
scope, most commonly) — decided before the related read is planned where the registry
answers it (the two objects' tenancy class under a walled posture), at the executor
boundary otherwise;
- a related read that a middleware answers itself (or adds rows to after the driver call).

A hop that falls back after planning (a middleware answering the related read, or driver
options only the request decides) dispatches the related read twice: its middleware chain
and `beforeFind` hooks run for the planned read and again for the id read.

A read rule that narrows a related object's rows after its driver call bounds a relation
condition on that object only when it is registered for that object — as an object-keyed
middleware or an `afterFind` hook; registered that way, the hop keeps the id read.

- **Every verb that takes a `where`** serves it — `find`, `findOne`, `count`,
`aggregate`, `update` and `delete` — and so do the REST `GET /data/:object` and
`POST /data/:object/query` doors, which read through the same engine calls. A
single-valued relation matches with `$in` on the related ids; a multi-valued one
single-valued relation matches with a subquery on a read verb (or with `$in` on the
related ids in the cases listed above) and with `$in` on the related ids on
`update` / `delete`; a multi-valued one
(`multiple: true`) matches a record when **any** member qualifies, written as one
`$contains` per id under an `$or`.
- **A second level is refused.** `{ account: { owner: { region: 'NA' } } }` and
`{ account: { 'owner.region': 'NA' } }` answer `INVALID_FILTER` / 400.
- **A related record the caller cannot read never matches**, whatever the operator:
`{ account: { status: { $ne: 'cancelled' } } }` leaves out a row whose account is
absent or hidden from the caller, as well as one whose account is cancelled.
- **Up to three relationships.** `{ account: { owner: { region: 'NA' } } }` reads
`user` as the caller, then `account` as the caller with the owner subquery inside,
and every hop carries its own object's row scope and field check; a related record
the caller cannot read at any hop excludes the row. A fourth relationship, and the
dotted `{ account: { 'owner.region': 'NA' } }`, answer `INVALID_FILTER` / 400.
- **The reverse direction is not served.** A parent filtered by its children is not
written as `{ opportunities: { stage: 'won' } }`: the parent has no such field, so the
REST doors answer `INVALID_FIELD` / 400.
Expand Down
2 changes: 1 addition & 1 deletion packages/objectql/src/engine-count-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
Expand Down
10 changes: 7 additions & 3 deletions packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -1353,7 +1357,7 @@ export class DeleteAndAggregateFacet {
// natively today; one that grows native support must advertise a
// capability flag, at which point this post-filter becomes the
// fallback tier — the dateGranularity two-tier pattern.
const aggregated = await drv.aggregate(object, ast, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }));
const aggregated = await drv.aggregate(object, ast, aggregateOptions);
return applyHaving(aggregated, ast.having, havingColumnClasses);
}
// In-memory fallback path: ask the driver for raw rows, then bucket +
Expand Down Expand Up @@ -1396,7 +1400,7 @@ export class DeleteAndAggregateFacet {
delete rowsAst.groupBy;
delete rowsAst.aggregations;
delete rowsAst.having;
const raw = await driver.find(object, rowsAst, this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }));
const raw = await driver.find(object, rowsAst, aggregateOptions);
return applyHaving(applyInMemoryAggregation(raw, ast, tz, declaredFields), ast.having, havingColumnClasses);
});

Expand Down
13 changes: 12 additions & 1 deletion packages/objectql/src/engine-driver-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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}).
Expand Down
18 changes: 15 additions & 3 deletions packages/objectql/src/engine-find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
*/

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

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

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

Expand Down
Loading
Loading