Skip to content

Commit 498c967

Browse files
feat(service-analytics): serve a one-hop cross-object where on the engine-aggregate path (#33512)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DFWmDYdUPFhME7Z7Ky3ySCZ)_ Fixes #33335 Area-lease pilot #33059, area A3. Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:分析服务的引擎聚合路径(ObjectQLStrategy)现在支持按关联记录字段过滤(`'cb_order.status'`,一跳)。以前这种过滤直接报 400。 - 为什么改:明细行仪表盘没办法排除"父订单已取消"的行。只有原生 SQL 路径能做,而带按月分桶或 controlled_by_parent 的仪表盘恰好走不到原生 SQL。 - 风险与回滚:点号过滤被改写成引擎已有的嵌套关联条件。父对象以调用者身份读取,RLS 与字段权限照常生效。没有父记录或读不到父记录的行一律不选中(`$ne` 也一样),这一点与原生 SQL 在无行级范围时的 LEFT JOIN 语义不同,已写进文档。回滚只需 revert 本 PR,仍不支持的形状照旧报 400。 - 先看:`packages/services/service-analytics/src/strategies/cross-object-where.ts`(改写与拒绝分类,重点是 `negated` 与 `join-target` 两个分支),`objectql-strategy.ts` 的 `servedWhere` 与 `planCrossObject`,以及 `packages/rest/src/analytics-nested-relation-filter.test.ts` 的 #33335 段(真实安全层下的端到端)。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/crossobject-conjunct-refusal.test.ts`,预期全绿,第 ⑨ 节能看到卡上的过滤被改写成 `{ cb_order: { status: { $ne: 'cancelled' } } }`。 - 需要你做的:无,席位落地。 ## What changes `ObjectQLStrategy` (the engine-aggregate path, which cannot join) used to refuse every cross-object `where` leaf with `400 INVALID_FIELD`. It now serves a **one-hop** dotted leaf in the caller's `where`, which covers a dataset query's `runtimeFilter`, a dashboard global filter and a widget filter. The leaf is respelled as the engine's own nested-relation condition: `{ 'cb_order.status': { $ne: 'cancelled' } }` becomes `{ cb_order: { status: { $ne: 'cancelled' } } }`. The engine already serves that form in `where` on every verb (`relation-filter-lowering.ts`). It works like this: - It reads the related object through its own `find`, as the caller. CRUD, row scope and field permissions all apply. - It then filters the base object with `IN` over the returned ids. That is the card's "resolve the parent ids first, then `IN`", and the security rule stays in the one place that owns it. - It refuses more than 1,000 matching parents (`400 INVALID_FILTER`) instead of truncating. - It lowers an empty match to FALSE. This PR reads no data and judges no permission itself. - **New:** `packages/services/service-analytics/src/strategies/cross-object-where.ts`, the copy-on-write `lowerCrossObjectWhere`. - It recurses `$and` and `$or`, and it recurses `$not` with the negated flag set. - It merges leaves on one relationship in one conjunction into one condition. The same parent field named twice gives two conditions. - A base-only `where` comes back as the same object, so it reaches the engine byte-identical. - **`objectql-strategy.ts`:** `servedWhere()` runs before the filter tree is built in both `execute()` and `generateSql()`. - `planCrossObject` takes the unserved map and refuses each unserved leaf with a reason-specific message plus the native-SQL route. - The `/analytics/sql` echo refuses a served leaf `400 INVALID_FILTER`, as it already does for the authored nested form. **Semantics, pinned:** a dotted leaf `rel.f OP v` means "the row's `rel` points at a record the caller can read, and that record satisfies `OP v`". - **Orphan or unreadable parent:** never matches, whatever the operator, `$ne` included. To keep those rows, OR in `{ rel: { $null: true } }`. - **Inside `$or`:** served. - **Under `$not`:** refused. Negating the existential test would let the children of an unreadable parent through. Put the negation inside the leaf instead. **Stays refused** (`400 INVALID_FIELD`, `param: 'where'`, each with its reason and the native route): - two or more hops (the hop limit is ONE relationship, because the engine's nested form is one level deep) - a leaf under `$not` - a `{ $field }` comparand - a relationship the cube joins onto a different object than the field declares - unchanged: a cross-object **measure**, and a related field in a dataset's own `filter` or a measure's own `filter` **Docs:** `content/docs/ui/dashboards.mdx` gets a new "Filtering on a Related Record's Field" section with the path table, the orphan rule and its remedy, and what stays refused. The card's ask 1 (which deployments evaluate the dotted form natively, and whether multi-hop is in scope there) is answered on the card: #33335 (comment) ## Why A dashboard over detail rows could not leave out the rows of a cancelled parent on every deployment. The native-SQL strategy declines a bucketed time dimension, a federated object, an engine-middleware object and a `controlled_by_parent` read scope, and every one of those routes to the engine-aggregate path, which refused the filter. ## Tests - **`crossobject-conjunct-refusal.test.ts`**: - The nested `$or` cases are served and reach the engine with the relation form. `$not` and `$not`-inside-`$or` stay refused at both doors. - Dataset-scope and measure-filter refusals are kept, with a new pin that a served `where` does not lift the measure filter's refusal. - New section 9 runs the card's own shape on a `cb_plan` cube: `{ plan_kind: 'recommended', 'cb_order.status': { $ne: 'cancelled' } }`. It covers the member alias, merge versus two conditions, the FK-expand dimension beside it, the echo refusal and a base-only control. A REFUSED table covers two hops, `$not`, `$field`, join-target and a cross-object measure. - **Pins repinned from refusal to support:** `infer-cube-relation-traversal.test.ts`, `dotted-dimension-unbacked-join-parity.test.ts` and `where-source-field-gate.test.ts`. - **Pins that keep their refusal through the `$not` spelling:** `objectql-read-scope.test.ts`, `unlisted-refusal-envelope.test.ts`, and in rest `analytics-dataset-unlisted-refusal-envelope.test.ts`. - **Other rest pins:** `analytics-hop-object-reference.test.ts` now answers on the engine-aggregate path what the declared join and the nested form answer. `analytics-masked-field-gate.test.ts` now gets rows for the joined filter on both compositions. - **End to end, real security layer** (`packages/rest/src/analytics-nested-relation-filter.test.ts`, new #33335 block: `SecurityPlugin`, real `ObjectQL`, SQLite, plus an orphan row). Each answer equals the engine's own nested-form answer: - equality - `$ne` (the orphan is not selected) - `$ne` OR `{ owner: { $null: true } }` (the orphan is selected) - inside `$or` - a hidden parent gives `[]` for the member and its rows for the system caller - an empty parent match gives `[]` - a multi-valued relation - the dataset door - an unreadable parent field gives `403 PERMISSION_DENIED` - more than the cap gives `400 INVALID_FILTER` - `$not` is refused `400 INVALID_FIELD` ## Acceptance notes - **The two strategies differ on orphans.** With no row-level scope on the parent, the native strategy's `LEFT JOIN` evaluates `$ne` over a NULL parent as unknown, so an orphan is not selected there either. Under `$ne` the two strategies agree, but for different reasons. Under `$not` they could differ, which is why `$not` is refused here. - **Large parent sets** are bounded by the engine's 1,000-id cap and refused past it (`400 INVALID_FILTER`), never truncated. - **Still native-only:** the dataset's own `filter` and a measure's own `filter`. Those are author-time and were not in the card's ask. - **Read-only observation, not filed (no reach measured):** `AnalyticsServicePlugin`'s auto-bridged `executeRawSql` maps a non-array, non-`{rows}` answer from `engine.execute` to `[]`. Only `null` is typed as `RAW_SQL_UNSUPPORTED`. I did not reproduce this against a real driver. ## Verification Final head `689c18223e` (it includes the merge of `origin/main`). Each block names the tree it read. No `service-analytics` file changed after `3f40448624`; after that commit only rest tests changed. <details><summary>service-analytics: test + typecheck (on 3f40448, the merge of origin/main)</summary> `bash scripts/pm/os-verify-lock.sh -c "pnpm --filter @objectstack/service-analytics test && pnpm --filter @objectstack/service-analytics typecheck && …"` → `Test Files 215 passed (215)` · `Tests 5213 passed | 332 skipped (5545)` · `tsc --noEmit` clean · `VERDICT command-exit 0`. </details> <details><summary>rest: full suite (a dependent that pins analytics answers)</summary> The first full run (`pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2`) reported `Test Files 1 failed | 415 passed (416)` · `Tests 1 failed | 8690 passed | 355 skipped`. The one red was `analytics-hop-object-reference.test.ts` expecting the old ObjectQL refusal. It now answers `[2]`, equal to the declared-join reference. I repinned it. Re-run of the four touched rest files: `Test Files 4 passed (4)` · `Tests 50 passed (50)` · `VERDICT command-exit 0`. The other dependents of service-analytics (`runtime`, `cli`, `client`, `verify`, `dogfood`) are declared to CI. A repo-wide grep finds no pin of the old refusal text outside `service-analytics` and `rest`. </details> <details><summary>Ablations (the tested behaviour changed)</summary> The `service-analytics` suites import `../strategies/*.js` from source, so there is no `dist/` step. Each mutation was written with `scripts/ablation-replace.mjs`, and each restore was proven by the path's blob hash equalling HEAD's. - **Respelling disabled** (`servedWhere`'s served-count guard changed to `>= 0`): 14 reds across `crossobject-conjunct-refusal` and `infer-cube-relation-traversal`. Restored blob = HEAD `78f2126f`. - **`$not` refusal disabled** (`if (negated && false)` in `cross-object-where.ts`): 13 reds across `crossobject-conjunct-refusal`, `objectql-read-scope` and `unlisted-refusal-envelope`. Restored blob = HEAD `6af89002`. </details> <details><summary>Gates (final head 689c182)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 95 commands, the same list on the final head as before. - **Final run on `689c18223e`:** all 95 commands exit 0. `--ran` reconciliation: "95 derived, 95 run, 0 NOT-MEASURED, 0 UNRUN … a DERIVED zero — all 95 recorded an exit code and none of them is 3". - **Earlier run, before the last two commits:** - `check:skill-examples` exit 3 (`client-react` unbuilt) until it was built. - `check:dts-closure` was red because it read `packages/spec/dist` mid-rebuild by my own concurrent build. Green on the re-run. - `check:test-source-alias` exit 1 on the edited `analytics-dataset-unlisted-refusal-envelope.test.ts`. Fixed with a module-top `import '@objectstack/objectql'`. - `check:dual-build-cjs-loads` exit 3 (tree unbuilt). Green on the final run: "123 published require entry point(s) across 72 package(s) load". - `pnpm check:nul-bytes` exit 0. - `eslint --no-inline-config` over the 12 changed `.ts` files: exit 0. Repo-wide `pnpm lint` is CI's. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` is untouched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (eslint passes over the changed files; the repo-wide run is CI's.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwotoQMyrtSr5EqqAF)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 489ef5f commit 498c967

15 files changed

Lines changed: 842 additions & 118 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
feat(service-analytics): the engine-aggregate path filters on a related record's field — a one-hop dotted `where` leaf (`'order.status'`) is served as the engine's nested-relation condition instead of refused (#33335)
6+
7+
Clause-②: yes (widening) — `ObjectQLStrategy` serves a query shape it refused with `400 INVALID_FIELD` ("cannot evaluate a cross-object filter … the engine cannot join in an aggregate"): a one-hop dotted member in the caller's `where` (a dataset query's `runtimeFilter`, a dashboard global filter, a widget filter). No authorable schema, export or wire shape changes, and every other answer is unchanged.
8+
Metadata-protocol: none
9+
10+
A dashboard over detail rows can now leave out the rows of a cancelled parent on every deployment, where before only a query the native-SQL strategy served could (a SQL datasource, with no bucketed date dimension, no federated object, and no engine-enforced read gate on any object it reads).
11+
12+
**What a served leaf means.** `{ 'order.status': { $ne: 'cancelled' } }` reaches the engine as `{ order: { status: { $ne: 'cancelled' } } }`, the nested-relation condition the engine already serves in `where`: it reads the related object as the caller (its row-level security and field permissions apply) and keeps the base rows whose relationship points at a record that read returned.
13+
14+
- A row with no related record, or one the caller cannot read, is not selected, whatever the operator (`$ne` and `$nin` included). To keep such rows, OR in the relationship itself: `{ $or: [{ 'order.status': { $ne: 'cancelled' } }, { order: { $null: true } }] }`.
15+
- No matching related record selects no row, never the unfiltered set.
16+
- A related field the caller cannot read is refused `403 PERMISSION_DENIED`; more than 1,000 matching related records are refused `400 INVALID_FILTER`, never truncated.
17+
- Leaves on one relationship in one conjunction are one condition (one related record satisfies all of them).
18+
- The `/analytics/sql` echo refuses such a query `400 INVALID_FILTER`, as it does the authored nested-relation form; `/analytics/query` returns its rows.
19+
20+
**Still refused (`400 INVALID_FIELD`, `param: 'where'`)**, each with its reason and the native-SQL route in the message: a path of two or more relationships, a related-field leaf under `$not` (write `$ne` / `$nin` inside the leaf), a related field compared with a `{ $field }` reference, and a relationship the cube joins onto a different object than the field declares. A cross-object measure, and a related field in a dataset's own `filter` or a measure's own `filter`, stay refused as before.

‎content/docs/ui/dashboards.mdx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,42 @@ which does accept an object's own field as an ad-hoc dimension without the datas
500500
declaring it; `widget-dimension-unknown` is what holds the line for authored
501501
dashboards.
502502

503+
### Filtering on a Related Record's Field
504+
505+
A dotted `relationship.field` filter — a global filter's `field`, a widget's
506+
`filter`, or a dataset query's `runtimeFilter` — filters the base rows by a field
507+
of the record they point at, such as leaving out the plan lines of cancelled
508+
orders with `{ 'order.status': { $ne: 'cancelled' } }`. The analytics service
509+
evaluates it on one of two paths, and the path decides how deep it may reach:
510+
511+
| Path | When it serves the query | Depth |
512+
| :--- | :--- | :--- |
513+
| Native SQL | A SQL datasource (SQLite, PostgreSQL, MySQL, SQL Server, Turso), unless the query buckets a date by granularity, reads a federated object, or reads an object with an engine-enforced read gate (an engine middleware, or a `controlled_by_parent` read scope) | Every hop, as a `LEFT JOIN` per relationship |
514+
| Engine aggregate | Every query the native SQL path does not serve | One relationship |
515+
516+
On the engine-aggregate path the filter reads the related object **as the
517+
caller**, with that object's row-level security and field permissions, and keeps
518+
the base rows whose relationship points at a record it returned:
519+
520+
- A row with no related record, or one the caller cannot read, is **not
521+
selected**, whatever the operator, `$ne` and `$nin` included. To keep such
522+
rows, add the relationship itself as another branch:
523+
`{ $or: [{ 'order.status': { $ne: 'cancelled' } }, { order: { $null: true } }] }`.
524+
- When no related record matches, the widget shows **no rows**, never the
525+
unfiltered set.
526+
- A related field the caller cannot read is refused (`403 PERMISSION_DENIED`), as
527+
filtering on it directly would be.
528+
- More than 1,000 matching related records are refused (`400 INVALID_FILTER`),
529+
never truncated. Narrow the related condition.
530+
- These are refused (`400 INVALID_FIELD`) rather than answered differently: a
531+
path of two or more relationships (`line.plan.order.status`), a related-field
532+
condition under `$not` (write `$ne` / `$nin` inside the condition instead), and
533+
a related field compared with another field (`$field`).
534+
535+
A related field in a **dataset's own** `filter`, or in a **measure's** own
536+
`filter`, is still evaluated only on the native SQL path; the engine-aggregate
537+
path refuses it (`400 INVALID_FIELD`) rather than count rows it cannot join.
538+
503539
### Date Filter Defaults
504540

505541
A `type: 'date'` filter's `defaultValue` must be a value the dashboard can

‎packages/client/src/envelope-caller-census.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ const LEDGER: readonly LedgerRow[] = [
504504
// ── the nested-relation pin in `@objectstack/rest`: producer reads only ──
505505
{
506506
file: 'packages/rest/src/analytics-nested-relation-filter.test.ts',
507-
method: 'analytics.query', receiver: 'service', count: 5, verdict: 'NOT_SDK',
507+
method: 'analytics.query', receiver: 'service', count: 7, verdict: 'NOT_SDK',
508508
why: 'the real AnalyticsService (the cube read), called to compare its answer for the nested-relation filter with the engine\'s',
509509
},
510510
// ── a producer face outside the SDK: driver-memory's cube service ────────
@@ -790,7 +790,9 @@ describe('#13079 §2 — positive controls on the matcher itself', () => {
790790
// [#29304] Two more sites in that file: the route pin calls the same
791791
// plugin-registered AnalyticsService to read which strategy serves a
792792
// stored dimension and which refuses a formula one.
793-
expect(service.length, literalNote()).toBe(19);
793+
// [#33335] Two more in the nested-relation pin: the dotted cross-object
794+
// filter the ObjectQL strategy now serves, compared with the engine's.
795+
expect(service.length, literalNote()).toBe(21);
794796
expect([...new Set(service.map((s) => s.file))].sort()).toEqual([
795797
'packages/client/src/analytics-automation-json-erasure.test.ts',
796798
'packages/drivers/driver-memory/src/memory-exists-non-boolean-refusal.test.ts',
@@ -855,7 +857,8 @@ describe('#13079 §3 — every call site is classified', () => {
855857
// [#28852] 14 -> 15: its dateRange-precedence call.
856858
// [#28977] 15 -> 17: the non-date bucket dry-run parity pin's two producer calls (§2).
857859
// [#29304] 17 -> 19: the same file's route pin, two producer calls (§2).
858-
expect(verdictTotal('NOT_SDK')).toBe(19);
860+
// [#33335] 19 -> 21: the nested-relation pin's two dotted-filter producer calls (§2).
861+
expect(verdictTotal('NOT_SDK')).toBe(21);
859862
// The three above are LEDGER sums and cannot move on a census reading;
860863
// this one is census-derived, so it carries the note. [#13874]
861864
// [#31695] 28 -> 31: the package-address pins' three trigger calls.

‎packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { describe, it, expect, vi } from 'vitest';
4040
import type { Logger } from '@objectstack/spec/contracts';
4141
import { AnalyticsService } from '@objectstack/service-analytics';
4242
import { RestServer } from './rest-server';
43+
import '@objectstack/objectql';
4344

4445
// ── harness (the shape `analytics-dataset-refusal-envelope.test.ts` uses) ─────
4546

@@ -256,15 +257,18 @@ describe('[#5716] a refusal nobody listed still answers 4xx, from its own envelo
256257
},
257258
{
258259
// A dashboard's own filter on a joined column — `runtimeFilter` is where a
259-
// widget's date/segment picker lands.
260-
name: 'objectql-strategy: a cross-object FILTER',
260+
// widget's date/segment picker lands. [#33335] A one-hop leaf is served
261+
// now (the engine's nested-relation condition); under `$not` it stays
262+
// refused, since negating "a readable parent matches" admits the rows of
263+
// an absent or unreadable parent.
264+
name: 'objectql-strategy: a cross-object FILTER under $not',
261265
analytics: aggregateAnalytics,
262266
body: {
263267
dataset: joinedDataset,
264-
selection: { dimensions: ['stage'], measures: ['revenue'], runtimeFilter: { region: 'NA' } },
268+
selection: { dimensions: ['stage'], measures: ['revenue'], runtimeFilter: { $not: { region: 'NA' } } },
265269
},
266270
code: 'INVALID_FIELD',
267-
message: /cannot evaluate a cross-object filter \("account\.region"\)/,
271+
message: /cannot evaluate the cross-object filter \("account\.region"\) under a \$not/,
268272
},
269273
{
270274
name: 'objectql-strategy: a non-recombinable measure over a cross-object dimension',

‎packages/rest/src/analytics-hop-object-reference.test.ts‎

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
* target — by the same caller, on the same strategy, in the same test: a
2121
* declared join was always resolved to its target. Each reference is also
2222
* checked absolutely, so an equality between two wrong answers cannot pass.
23-
* On the native strategy the dotted filter also answers what the engine's
23+
* On both strategies the dotted filter also answers what the engine's
2424
* nested form `{ owner: { region: … } }` answers, the form the dotted
2525
* spelling maps onto. A lookup named after its target is the control.
2626
*
@@ -229,17 +229,13 @@ for (const strategy of ['native', 'objectql'] as const) {
229229
const reference = await answerOf(() => h.service.query({ cube: VIA_PERSON.name, measures: ['count'], where: { owner_region: 'NA' } } as never, MEMBER_CTX as never));
230230
const answer = await answerOf(() => h.service.query({ cube: LEDGER, measures: ['count'], where: { 'owner.region': 'NA' } } as never, MEMBER_CTX as never));
231231
expect(answer).toEqual(reference);
232-
if (strategy === 'native') {
233-
// Served: the two rows whose owner is in region NA — what the engine's
234-
// nested form answers for the same condition.
235-
expect(answer).toEqual({ answered: [JSON.stringify([2])] });
236-
const nested = await answerOf(() => h.service.query({ cube: LEDGER, measures: ['count'], where: { owner: { region: 'NA' } } } as never, MEMBER_CTX as never));
237-
expect(answer).toEqual(nested);
238-
} else {
239-
// The engine-aggregate strategy filters on no related value, through a
240-
// declared join or not: its own capability refusal, never the door's.
241-
expect(answer).toEqual({ refused: { code: 'INVALID_FIELD', status: 400, object: undefined } });
242-
}
232+
// Served on both strategies: the two rows whose owner is in region NA —
233+
// what the engine's nested form answers for the same condition. On the
234+
// engine-aggregate strategy the dotted leaf IS that nested form (#33335),
235+
// read on the lookup's declared target, as the declared join reads it.
236+
expect(answer).toEqual({ answered: [JSON.stringify([2])] });
237+
const nested = await answerOf(() => h.service.query({ cube: LEDGER, measures: ['count'], where: { owner: { region: 'NA' } } } as never, MEMBER_CTX as never));
238+
expect(answer).toEqual(nested);
243239
});
244240

245241
it.each([

‎packages/rest/src/analytics-masked-field-gate.test.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -347,12 +347,10 @@ for (const strategy of ['native', 'objectql'] as const) {
347347
const unmasker = await answerOf(() => h.service.query(query, UNMASKER_CTX as never));
348348
const system = await answerOf(() => h.service.query(query, SYS_CTX as never));
349349
expect(normalized(unmasker), `${label}: the unmasker`).toEqual(normalized(system));
350-
// The ObjectQL strategy serves no cross-object filter to anyone — the
351-
// engine cannot join in an aggregate — so that one case is answered by
352-
// the strategy's own refusal, for the system caller too. Every other
353-
// case is served rows.
354-
const joinedFilter = strategy === 'objectql' && label === 'a joined masked field as a filter member';
355-
if (!joinedFilter) expect((unmasker as { answered?: { rows: unknown[] } }).answered?.rows.length, `${label}: rows`).toBeGreaterThan(0);
350+
// Every case is served rows on both compositions: on the ObjectQL one
351+
// the joined filter is the engine's nested-relation condition, read as
352+
// the caller (#33335), where it used to be the strategy's own refusal.
353+
expect((unmasker as { answered?: { rows: unknown[] } }).answered?.rows.length, `${label}: rows`).toBeGreaterThan(0);
356354
}
357355
const ds = await h.dataset(UNMASKER_CTX, { measures: ['row_count'], dimensions: ['code_dim'] });
358356
expect(ds.status, JSON.stringify(ds.body)).toBe(200);

‎packages/rest/src/analytics-nested-relation-filter.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,3 +399,109 @@ describe('[#20887] a read scope carrying the nested-relation form', () => {
399399
}
400400
}, 60_000);
401401
});
402+
403+
/**
404+
* [#33335] The DOTTED cross-object member (`'owner.region'`) on the
405+
* engine-aggregate path. `engine.aggregate` cannot join, so `ObjectQLStrategy`
406+
* refused every such `where` leaf (`400 INVALID_FIELD`, "cannot join in an
407+
* aggregate"), and a dashboard over detail rows could not leave out the rows of
408+
* a cancelled parent. It now hands a one-hop leaf to the engine as the
409+
* nested-relation condition above (`cross-object-where.ts`), so its answer is
410+
* the engine's for that condition, computed here as the reference: the related
411+
* object read as the caller, its row scope and field permissions applied, an
412+
* empty match selecting no row, a match past the cap refused.
413+
*
414+
* Measured on the base (`ba35dfd7`), this composition, every row below:
415+
* `400 INVALID_FIELD`, "cannot evaluate a cross-object filter".
416+
*
417+
* Two readings are pinned beyond the reference, because they are the card's
418+
* questions: what a child with NO parent gets under a negative operator (it is
419+
* not selected — a cross-object leaf requires a related record the caller can
420+
* read; OR in `{ owner: { $null: true } }` to keep such rows), and that the
421+
* shapes this path cannot serve exactly (under `$not`, two hops) stay refused
422+
* rather than answered differently.
423+
*/
424+
describe('[#33335] a dotted cross-object where on the engine-aggregate path answers the engine\'s nested-relation condition', () => {
425+
let h: Harness;
426+
/** A ledger row with no owner at all — the orphan the negative operators are pinned on. */
427+
const ORPHAN = { id: 'd5', title: 'e', owner: null, owners: [] };
428+
const TITLES = new Map([...TITLE_OF, [ORPHAN.id, ORPHAN.title]]);
429+
430+
beforeAll(async () => {
431+
h = await boot({ caps: 'objectql' });
432+
await h.engine.insert(OBJECT, [{ ...ORPHAN }], { context: SYS_CTX } as never);
433+
}, 60_000);
434+
435+
afterAll(async () => {
436+
try { await h?.engine.destroy(); } catch { /* noop */ }
437+
});
438+
439+
const reference = (where: FilterCondition) =>
440+
h.engine.find(OBJECT, { where, context: MEMBER_CTX } as never).then(
441+
(rows: any[]) => ({ titles: rows.map((r) => TITLES.get(r.id) as string).sort() }),
442+
(e: Thrown) => ({ refused: envelopeOf(e) }),
443+
);
444+
const cubeRead = (where: FilterCondition) =>
445+
h.analytics.query(cubeQuery(where), MEMBER_CTX as never).then(
446+
(r) => ({ titles: titlesOf(r.rows, 'title') }),
447+
(e: Thrown) => ({ refused: envelopeOf(e) }),
448+
);
449+
450+
/** One owner id list keeps the `$ne` read under the cap: the 1001 `CAP` owners are not in it. */
451+
const LISTED = { $in: ['u1', 'u2', 'u3'] };
452+
const SERVED: ReadonlyArray<readonly [string, FilterCondition, FilterCondition, string[]]> = [
453+
['equality', { 'owner.region': 'NA' }, { owner: { region: 'NA' } }, ['a', 'c']],
454+
// u2 is the one readable owner outside NA: u3 is hidden by the owner row
455+
// scope, and d5 has no owner — neither is selected by a `$ne`.
456+
['$ne, beside a second leaf on the same relation',
457+
{ 'owner.region': { $ne: 'NA' }, 'owner.id': LISTED }, { owner: { region: { $ne: 'NA' }, id: LISTED } }, ['b']],
458+
['$ne, with the orphan kept by its own branch',
459+
{ $or: [{ 'owner.region': { $ne: 'NA' }, 'owner.id': LISTED }, { owner: { $null: true } }] },
460+
{ $or: [{ owner: { region: { $ne: 'NA' }, id: LISTED } }, { owner: { $null: true } }] }, ['b', 'e']],
461+
['inside $or', { $or: [{ 'owner.region': 'NA' }, { title: 'b' }] }, { $or: [{ owner: { region: 'NA' } }, { title: 'b' }] }, ['a', 'b', 'c']],
462+
['a related record the caller cannot read', { 'owner.region': 'HIDDEN' }, { owner: { region: 'HIDDEN' } }, []],
463+
['no related record matches', { 'owner.region': 'NOWHERE' }, { owner: { region: 'NOWHERE' } }, []],
464+
['a multi-valued relation', { 'owners.region': 'NA' }, { owners: { region: 'NA' } }, ['a', 'c']],
465+
];
466+
467+
it('the cube read answers the engine\'s rows for the nested-relation condition the leaf stands for', async () => {
468+
for (const [label, dotted, nested, titles] of SERVED) {
469+
const expected = await reference(nested);
470+
expect(expected, `${label}: the engine's own answer`).toEqual({ titles });
471+
expect(await cubeRead(dotted), `${label}: the cube read`).toEqual(expected);
472+
}
473+
// The empty answers above are the scope and the condition, not an empty
474+
// table: a system caller reads the hidden owner's row.
475+
const system = await h.analytics.query(cubeQuery({ 'owner.region': 'HIDDEN' }), SYS_CTX as never);
476+
expect(titlesOf(system.rows, 'title')).toEqual(['d']);
477+
});
478+
479+
it('the dataset door answers the same rows for the leaf in selection.runtimeFilter', async () => {
480+
for (const [label, dotted, , titles] of SERVED.filter(([, d]) => !JSON.stringify(d).includes('owners'))) {
481+
const ds = await h.dataset({ measures: ['row_count'], dimensions: ['title_dim'], runtimeFilter: dotted });
482+
expect(ds.status, `${label}: ${JSON.stringify(ds.body)}`).toBe(200);
483+
expect(titlesOf(ds.body.rows, 'title_dim'), label).toEqual(titles);
484+
}
485+
});
486+
487+
it('a related field the caller cannot read, and a match past the cap, are refused as the engine refuses them', async () => {
488+
const cases: ReadonlyArray<readonly [FilterCondition, FilterCondition, { code: string; status: number }]> = [
489+
[{ 'owner.secret': 's1' }, { owner: { secret: 's1' } }, { code: 'PERMISSION_DENIED', status: 403 }],
490+
[{ 'owner.region': 'CAP' }, { owner: { region: 'CAP' } }, { code: 'INVALID_FILTER', status: 400 }],
491+
];
492+
for (const [dotted, nested, expected] of cases) {
493+
expect(await reference(nested), JSON.stringify(nested)).toEqual({ refused: expected });
494+
expect(await cubeRead(dotted), JSON.stringify(dotted)).toEqual({ refused: expected });
495+
}
496+
});
497+
498+
it('a leaf under $not stays refused, never answered from a negated match that admits the hidden owner\'s row', async () => {
499+
// The engine answers the AUTHORED nested form under `$not` with d4 and d5
500+
// among its rows (the NULL-safe negation of a relation match); the dotted
501+
// leaf is refused instead. The two-hop refusal is pinned at the strategy
502+
// (`service-analytics`'s `crossobject-conjunct-refusal.test.ts`, ⑨).
503+
expect(await reference({ $not: { owner: { region: 'NA' } } })).toEqual({ titles: ['b', 'd', 'e'] });
504+
expect(await cubeRead({ $not: { 'owner.region': 'NA' } } as FilterCondition))
505+
.toEqual({ refused: { code: 'INVALID_FIELD', status: 400 } });
506+
});
507+
});

0 commit comments

Comments
 (0)