Skip to content

Commit eed422e

Browse files
fix(core): drill a relationship path as one nested-relation condition, pushed down by the server (#35423)
Fixes #34990 Part of #35447 Clause-②: yes (narrowing) Metadata-protocol: none Skills-docs: follow-up #35481 ## 维护者速读 1. 用户能看到什么变化:仪表盘和报表里按"关联对象的字段"(例如按客户的负责人)分组时,点开明细抽屉会直接列出对应记录,不再因为关联记录超过两百条而提示"太多,无法列出";但这类明细抽屉里暂不再提供"在列表中打开"按钮。 2. 为什么做:收口上一张"按关联字段钻取明细"修复里由席位批准的临时方案——原来由浏览器先读出关联记录再筛选,现在交给服务器在数据库里一次关联查询完成。 3. 出错会怎样:看板和报表的用户点开按关联字段分组的明细时会看到"记录加载失败"的提示,不会看到错误的数据;直接回滚本次改动即可恢复原来的行为。 4. 要你做什么:无,席位落地。 > **Declaration corrected (L1-a ACCEPT 7005070933):** `convertFiltersToAST` is a published export of `@object-ui/core` and now accepts the nested-relation map it used to refuse, so this PR is `Clause-②: yes (widening)` (was `no`). `Metadata-protocol: none` and the `patch` level stand. The changeset carries the same line from `a7203afa`. > **L2 S1 folded in (seat pick, contract review 7005257036; card #35447, claimed on its thread 7006104820):** from `def1213f`, `ValueDataSource`'s AST matcher refuses a nested-relation comparand (a non-empty object with no `$` key) for every operator that reads it, with the object arm's sentence through one shared builder (`nestedRelationRefusalReason`). Before, `=` matched no row silently and `!=` matched every row. Pin: new top-level describe in `ValueDataSource.astFilterVocabulary.test.ts` (AST and object forms refused alike, `!=` refused, CONTROL scalar `=`). The `data-objectstack` README lowering table gains the node's row (its example runs in `readme-filter-operator-table.test.ts`). > **Declared as a narrowing (delta contract review 7006192304, M1; changeset from `694b6011`):** the refusal turns a no-`$` object comparand under `!=`, `not_contains` and the ordering operators from serving every or some rows into a named refusal on the published `ValueDataSource#find`. The changeset carries the BREAKING paragraph (FROM / TO) and the ADR-0087 marker `not-required (no-migration-prescription)`: the spec's comparand door already refuses that comparand and no saved view filter can hold it. `patch` stays (non-protocol). Full dogfood on `694b6011`: 482 passed, 3 skipped files, 0 failures. `Skills-docs:` follow-up #35481 is the drill drawer's "Open in list" link, which this PR drops for a relationship-path dimension; the narrowing itself is taught by no skill. > **Narrowing contract review S2 folded in (from `b950ae60`):** the AST arm treats a comparand as a nested-relation condition only when it is a PLAIN object (prototype `Object.prototype` or `null`) with no `$` key, so a class instance with its own keys (a moment / luxon date, a decimal) compares through `valueOf` again under the ordering operators. Pins: `not_contains` and `>` refusal legs beside `=` / `!=`; CONTROL legs for a class instance under `>` and `<` and a `Date` under `>` (ablation of the prototype check turns the two class-instance legs red). The changeset now names the exact refused population instead of "refuses anything else". Full dogfood on `b950ae60`: 482 passed / 3 skipped files, 4092 tests, 0 failures (os-dev-report 7011424436). ## What changes - **Client filter grammar: the nested-relation node.** `convertFiltersToAST` (`@object-ui/core`) now lowers the nested-relation form the spec already declares on `FilterCondition` (form 4: `{ account: { owner: 'u1' } }`, a plain object with no `$` key beneath a field) to one equality node, `['account', '=', { owner: 'u1' }]`. The spec's `parseFilterAST` reads that node back as the same nested condition, which the server serves. It used to refuse the shape as an unknown operator. The recognised population is the engine's own `isNoOperatorObject` (no `$` key), so client and server name one shape; a map that mixes `$` operators with plain keys is still refused. Nothing on the client judges the inner condition: whether the field is a relationship is decided by the server, which refuses anything else with `INVALID_FILTER` / 400. The engine-internal semi-join leaf (ADR-0139 / ADR-0155) is never spelled. - **`resolveDatasetDrillFilter`: the two-step is removed.** A relationship-path dimension (`account.owner`, up to ADR-0071's three hops) now drills as one nested condition, one level per hop (`{ account: { parent: { kind: VALUE } } }`), instead of reading up to 200 related ids per hop and filtering on `$in` them. No related record is read and nothing is capped. Unchanged: the per-hop schema read that confirms each hop is a single-valued relationship, the hop limit, the empty-bucket refusal, and the plain-dimension-on-the-relationship-field case (it becomes an `id` key inside the nested condition). - **The PD5 exception docblock is retired** (seat ruling 6961225798, bounded exception (a) whose exit is this node): the "resolved here because the grammar has no nested-relation node yet" paragraph and the "read in two steps" section are replaced by the nested-condition description. - `DATASET_DRILL_RELATED_ID_CAP` and the `too-many` member of `DatasetDrillResolution` are no longer produced. They stay exported, marked `@deprecated`, because removing them is a narrowing of `@object-ui/core`'s published surface and their consumers (the drawer's `too-many` notice and its locale strings) sit outside this claim's file surface (see Acceptance notes). ## Tests At head `0ff1d0ab` (origin/main `0967cbe6` merged; the incoming commits touch none of the packages below). `dba9da83` adds one comment-only commit restoring the objectstack#17469 citation the plugin-detail pin requires; `a7203afa` changes only the changeset's `Clause-②` line. - `pnpm --filter @object-ui/core test`: Test Files 243 passed (243), Tests 4482 passed, 27 skipped. - `pnpm --filter @object-ui/core type-check`: exit 0. `pnpm --filter @object-ui/plugin-dashboard --filter @object-ui/plugin-report type-check`: exit 0. - Focused, verbose: the four touched test files, Test Files 4 passed (4), Tests 168 passed (168). - New pins: `filter-converter.test.ts` gains a top-level `describe('the nested-relation node (objectstack#34990)')` (lowering + spec round trip, a deeper relation with inner operators, beside plain keys and under `$or`, CONTROL mixed map refused with `INVALID_FILTER`/400 naming `owner`/`account`, CONTROL operator map and empty map unchanged). - Flipped legs of the #34968 pins (only those that asserted the two-step): in `dataset-drill-relationship-path-34907.test.ts` the 1-hop/2-hop/id-cap/empty-`$in` legs became 1-, 2- and 3-hop nested-condition legs with zero `find` calls, a drawer-lowering leg (`convertFiltersToAST` + `parseFilterAST` round trip), the shared-hop leg and a plain-dimension `id` leg; in `DatasetWidget.test.tsx` the first leg and the `too-many` notice leg; in `DatasetReportRenderer.test.tsx` the first leg. Hop-limit, unknown/multi-valued relationship, empty bucket, CONTROL single-object drill and builder refusal legs are unchanged. <details><summary>Ablation (one per changed behaviour, each via scripts/ablation-replace.mjs, restored blob == HEAD and git diff HEAD empty)</summary> - Converter node disabled (`if (isNestedRelationCondition(...))` to `if (false && ...)`, anchor 1 to 0, blob 53704b0 to d69c22c6): 5 failed / 23 passed, each failure `Unknown filter operator 'owner'/'owner_id'/'parent'`; restored to 53704b0. - Resolver's nested write replaced with `{ $in: [] }` (blob 8c33515 to 2783b612): 6 failed / 3 passed in the 34907 file; restored to 8c33515. Both suites import the module under test from source by relative path, so no dist leg applies. </details> ## Acceptance notes - **"Open in list" is not offered for a relationship-path drill any more.** `exactRecordListFilter` (app-shell) offers the escape hatch only for a filter the list page's `filter[...]` URL dialect writes exactly; that dialect has no spelling for a nested condition, so it answers `null` and the drill stays in the drawer (code reading of its operator loop, not a browser run). Under the two-step a drill with at most 200 related ids could escalate through `filter[account][in]`. Seat 5 picked A (seat note on #34990): ship as is; the URL spelling is #35438. - **Dead residue left by the fence:** the `too-many` arm in `DatasetWidget.tsx` / `DatasetReportRenderer.tsx`, the `'too-many'` entry of `DrillDownDrawer`'s notice table and its locale strings, plus the deprecated exports above, are now unreachable. Removing them narrows a published export; triage closed that card (#35439) as not planned at first touch (7005794295): the removal rides the next major that narrows `@object-ui/core` exports. - The stale comment in `ui/packages/data-objectstack/src/queryDataset.test.ts` ("resolved through the related ids first") is corrected from `b950ae60`. - Where the server cannot prove the subquery is the related read's own statement (a related object with an object-scoped middleware or an `afterFind` hook, another datasource, a federated object), it reads the related ids itself under its 1,000 cap and refuses past it with `INVALID_FILTER` / 400; the drawer then shows its localized load-failure sentence. That is the server's documented behaviour, not a client bound. ## Verification <details><summary>A1: the server takes the client's wire spelling and pushes it down (SQLite, real engine, throwaway test, not committed)</summary> Real `ObjectQL` + `SqlDriver` (better-sqlite3) + `SecurityPlugin` + `RestServer`, `GET /api/v1/data/:object` with `?filter=` set to the AST JSON the client sends, knex query log captured: - `['owner','=',{region:'NA'}]`: 200, ids d1, d3; 1 statement: select from the ledger where owner in (select id from the owner table where region = ? and the owner's row-scope predicate). - `['ledger','=',{owner:{region:'NA'}}]` (two hops): 200, id n1; 1 statement with two nested in-subqueries, each carrying its object's row scope. - `['and',['id','!=','zz'],['ledger','=',{title:'a',owner:{region:'NA'}}]]`: 200, id n1; 1 statement. - CONTROL the old id form `['owner','in',['u1']]`: 200, ids d1, d3; 1 statement with a bound id list. No statement reads related ids before the main read. A2: before this change `convertFiltersToAST` refused the nested form (the converter ablation above shows the refusal text). A3: 7 files, +207 / -128. </details> <details><summary>Gates</summary> Local families: derived with `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `0ff1d0ab` (39 commands) and run in full; results are in the report comment on the card. `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` before each push. CI-owned families (lint, type-check programs, Test UI) are read from this PR's check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CajiB6BSQKWowy6YLB)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CajiB6BSQKWowy6YLB --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b68f9ae commit eed422e

11 files changed

Lines changed: 383 additions & 137 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@object-ui/core': patch
3+
---
4+
5+
fix(core): a relationship-path dashboard drill is sent as one nested-relation condition, so the server joins it in the database instead of the app reading related ids first
6+
7+
Clause-②: yes (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the narrowed input is the in-memory filter a host hands ValueDataSource at runtime, and the comparand it now refuses, a plain object with no $ key under a scalar operator, is one the spec's own comparand door already refuses and ViewFilterRuleSchema.value cannot hold. No metadata an author can save changes meaning, so there is nothing for objectstack migrate meta to do. -->
11+
12+
**BREAKING** for a host that filters a `ValueDataSource` (the in-memory `provider: 'value'` source) with a comparison whose comparand is a plain object (prototype `Object.prototype` or `null`) with no `$` key, such as `['account', '!=', { owner: 'u1' }]`, under `!=`, `not_contains` or an ordering operator (`>`, `>=`, `<`, `<=`).
13+
14+
- FROM: `!=` and `not_contains` served every row, and an ordering operator compared each value with the text `[object Object]` and served the string values that happened to sort past it.
15+
- TO: the condition is refused by name. It excludes every row and logs the sentence the object form `{ account: { owner: 'u1' } }` already logs. `=` matched no row before and matches none now; it only gains the log line.
16+
- The spec's comparand door already refuses an object comparand under these operators, so the rows served before were a wrong answer. Spell a relation condition only against a server-backed source, whose server joins it; a value source holds flat rows, so filter there on the row's own fields.
17+
18+
`convertFiltersToAST` now lowers the nested-relation form the spec declares on `FilterCondition` (`{ account: { owner: 'u1' } }`, a plain object with no `$` key beneath a field) to one equality node, `['account', '=', { owner: 'u1' }]`, which the spec's `parseFilterAST` reads back as the same nested condition. It used to refuse that shape as an unknown operator. The condition travels as written, deeper relations included; whether the field is a relationship is judged by the server, which answers `INVALID_FILTER` / 400 for such a condition under a field that stores a scalar or a structured-JSON value, and, under a relationship, for a condition key the related object does not declare, a dotted key, or a relation nested past the hop limit. A map that mixes `$` operators with plain keys is still refused.
19+
20+
`ValueDataSource` (the in-memory `provider: 'value'` source) does not descend into relations, and it now says so for the lowered node too: a comparison whose comparand is a plain object with no `$` key, such as `['account', '=', { owner: 'u1' }]`, excludes every row and logs the same sentence the object form `{ account: { owner: 'u1' } }` already logged, for `=`, `!=` and every other operator that reads the comparand. Before this, `=` compared the object by reference and matched no row without a word, and `!=` matched every row. A class instance is not refused, even one with keys of its own such as a moment, luxon or decimal object: it is a value, and an ordering operator still compares it through its `valueOf`.
21+
22+
`resolveDatasetDrillFilter` uses it: a dataset dimension whose field is a relationship path (`account.owner`, up to three hops) drills as `{ account: { owner: VALUE } }`, nested one level per hop, instead of reading up to 200 related ids per hop and filtering on `$in` them. No related record is read, nothing is capped, and the `too-many` answer is no longer produced; `DATASET_DRILL_RELATED_ID_CAP` and the `too-many` member of `DatasetDrillResolution` stay exported, marked deprecated. The schema reads that check each hop is a single-valued relationship, the hop limit and the empty-bucket refusal are unchanged.
23+
24+
One visible consequence: the drawer's "Open in list" escape hatch is not offered for a relationship-path drill, because the list page's `filter[...]` URL dialect has no spelling for a nested condition; the drill drawer itself lists the records.

‎ui/packages/core/src/adapters/ValueDataSource.ts‎

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,39 @@ function comparandEquals(value: unknown, target: unknown): boolean {
472472
return value === target;
473473
}
474474

475+
/**
476+
* The refusal for a nested relation constraint, one sentence for both
477+
* dialects: the object arm meets `{ rel: { field: value } }` as a non-operator
478+
* key in {@link matchesDollarOperator}, and the AST arm meets its lowered
479+
* `['rel', '=', { field: value }]` in {@link matchesComparisonNode}.
480+
*/
481+
function nestedRelationRefusalReason(field: string, key: string): string {
482+
return `filter condition on field '${field}' carries the non-operator key `
483+
+ `'${key}'; the in-memory matcher does not descend into a nested `
484+
+ `relation constraint`;
485+
}
486+
487+
/**
488+
* The first key of an AST comparand that is a nested relation condition, or
489+
* `undefined` when it is not one. The shape is the one `convertFiltersToAST`
490+
* lowers to `[rel, '=', condition]`: a non-empty PLAIN object with no `$` key.
491+
*
492+
* Plain means prototype `Object.prototype` or `null`, the test the spec's
493+
* filter walk uses to tell filter structure from data. A class instance is
494+
* data even when it carries its own non-`$` keys: a moment or luxon date, or a
495+
* decimal object, under `>` / `<` compares through its `valueOf` in the switch
496+
* below and is not refused as a relation.
497+
* A `Date` has no own keys, so it is never one either.
498+
*/
499+
function nestedRelationComparandKey(target: unknown): string | undefined {
500+
if (!target || typeof target !== 'object' || Array.isArray(target)) return undefined;
501+
const proto = Object.getPrototypeOf(target) as object | null;
502+
if (proto !== Object.prototype && proto !== null) return undefined;
503+
const keys = Object.keys(target);
504+
if (keys.length === 0 || keys.some((key) => key.startsWith('$'))) return undefined;
505+
return keys[0];
506+
}
507+
475508
/**
476509
* Evaluate ONE comparison node — `[field, operator]` or `[field, operator, value]`.
477510
*
@@ -522,6 +555,17 @@ function matchesComparisonNode(
522555
return refuseListMemberFieldReference(refusals, field, String(rawOperator));
523556
}
524557

558+
// The nested-relation node `['rel', '=', { field: value }]`, which
559+
// `convertFiltersToAST` lowers `{ rel: { field: value } }` to. This matcher
560+
// does not descend into relations, and without this arm `=` compared the
561+
// condition object by reference: no row matched and nothing was logged, while
562+
// the object form of the same filter is refused by name. Checked for every
563+
// operator that reads the slot, so `!=` cannot answer it as every row.
564+
const nestedKey = nestedRelationComparandKey(rawTarget);
565+
if (nestedKey !== undefined && !AST_NO_COMPARAND_OPERATORS.has(operator)) {
566+
return refuseFilterNode(refusals, nestedRelationRefusalReason(field, nestedKey));
567+
}
568+
525569
// objectui#8515 — a `{ $field }` reference as the WHOLE comparand. Resolved
526570
// against this record so the switch below compares two of its own values,
527571
// exactly as `matchesFilter` (`@objectstack/formula`) and `driver-sql` do.
@@ -924,12 +968,7 @@ function matchesDollarOperator(
924968
);
925969
}
926970
if (!operator.startsWith('$')) {
927-
return refuseFilterNode(
928-
refusals,
929-
`filter condition on field '${field}' carries the non-operator key `
930-
+ `'${operator}'; the in-memory matcher does not descend into a nested `
931-
+ `relation constraint`,
932-
);
971+
return refuseFilterNode(refusals, nestedRelationRefusalReason(field, operator));
933972
}
934973
return refuseFilterNode(
935974
refusals,

‎ui/packages/core/src/adapters/__tests__/ValueDataSource.astFilterVocabulary.test.ts‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,3 +458,120 @@ describe('objectui#7349 — the production chain, end to end', () => {
458458
expect(await selectedIds(filter)).toEqual(['a', 'c']);
459459
});
460460
});
461+
462+
// ---------------------------------------------------------------------------
463+
// The nested-relation node is refused by name in both dialects
464+
// ---------------------------------------------------------------------------
465+
466+
/**
467+
* `convertFiltersToAST` lowers the nested relation condition
468+
* `{ profile: { verified: true } }` to `['profile', '=', { verified: true }]`,
469+
* the node a server data source serves as a subquery. This matcher does not
470+
* descend into relations. The object form was already refused by name; the
471+
* AST form reached the `=` arm, which compared the condition object by
472+
* reference, so no row matched and nothing was logged. Both forms now give
473+
* the same refusal sentence. The `=` answer was the empty set on both trees,
474+
* so the discriminant there is the logged refusal; `!=` answered EVERY row
475+
* before the arm existed, so its row set discriminates on its own.
476+
*/
477+
describe('the nested-relation node is refused by name in both dialects', () => {
478+
const NESTED = { profile: { verified: true } };
479+
const REFUSAL =
480+
"filter condition on field 'profile' carries the non-operator key 'verified'; "
481+
+ 'the in-memory matcher does not descend into a nested relation constraint';
482+
483+
it('the AST form and the object form are refused alike, with one sentence', async () => {
484+
const node = toFilterNode(NESTED);
485+
expect(node).toEqual(['profile', '=', { verified: true }]);
486+
487+
const astWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
488+
expect(await selectedIds(node)).toEqual([]);
489+
expect(astWarn).toHaveBeenCalledTimes(1);
490+
const astLine = String(astWarn.mock.calls[0]?.[0]);
491+
astWarn.mockRestore();
492+
493+
const objectWarn = vi.spyOn(console, 'warn').mockImplementation(() => {});
494+
expect(await selectedIds(NESTED)).toEqual([]);
495+
expect(objectWarn).toHaveBeenCalledTimes(1);
496+
const objectLine = String(objectWarn.mock.calls[0]?.[0]);
497+
498+
expect(astLine).toContain(REFUSAL);
499+
expect(astLine).toBe(objectLine);
500+
});
501+
502+
it('`!=` on the node is refused too, rather than answering every row', async () => {
503+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
504+
expect(await selectedIds(['profile', '!=', { verified: true }])).toEqual([]);
505+
expect(warn).toHaveBeenCalledTimes(1);
506+
expect(String(warn.mock.calls[0]?.[0])).toContain(REFUSAL);
507+
});
508+
509+
/**
510+
* `profile` holds text here, so the operators below answered rows of their
511+
* own without the arm: `not_contains` every row, and `>` the values that sort
512+
* past the text `[object Object]` (`'zeta'`, not `'Alpha'`). The empty set
513+
* plus the logged sentence is the refusal.
514+
*/
515+
const PROFILE_ROWS = [
516+
{ id: 'a', profile: 'zeta' },
517+
{ id: 'b', profile: 'Alpha' },
518+
];
519+
520+
it.each(['not_contains', '>'])(
521+
'`%s` on the node is refused too, rather than reading the object as text',
522+
async (operator) => {
523+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
524+
expect(await selectedIds(['profile', operator, { verified: true }], PROFILE_ROWS))
525+
.toEqual([]);
526+
expect(warn).toHaveBeenCalledTimes(1);
527+
expect(String(warn.mock.calls[0]?.[0])).toContain(REFUSAL);
528+
},
529+
);
530+
531+
it('CONTROL: a scalar `=` still matches, with nothing logged', async () => {
532+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
533+
expect(await selectedIds(['role', '=', 'admin'])).toEqual(['a', 'c']);
534+
expect(warn).not.toHaveBeenCalled();
535+
});
536+
537+
/**
538+
* Only a PLAIN object is a nested condition. A class instance with its own
539+
* non-`$` keys is data, the way a moment or luxon date or a decimal object
540+
* is: an ordering operator compares it through its `valueOf`. `Amount`
541+
* stands in for that population; `age` is 30 / 25 / 20.
542+
*/
543+
class Amount {
544+
readonly units: number;
545+
constructor(units: number) {
546+
this.units = units;
547+
}
548+
valueOf(): number {
549+
return this.units;
550+
}
551+
}
552+
553+
it.each([
554+
['>', 22, ['a', 'b']],
555+
['<', 26, ['b', 'c']],
556+
] as const)(
557+
'CONTROL: a class instance with own keys under `%s` compares through valueOf, with nothing logged',
558+
async (operator, units, expected) => {
559+
const comparand = new Amount(units);
560+
expect(Object.keys(comparand)).toEqual(['units']);
561+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
562+
expect(await selectedIds(['age', operator, comparand])).toEqual(expected);
563+
expect(warn).not.toHaveBeenCalled();
564+
},
565+
);
566+
567+
it('CONTROL: a `Date` comparand under `>` is still accepted, with nothing logged', async () => {
568+
const rows = [
569+
{ id: 'a', created: new Date('2026-03-01T00:00:00Z') },
570+
{ id: 'b', created: new Date('2026-01-01T00:00:00Z') },
571+
];
572+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
573+
expect(await selectedIds(['created', '>', new Date('2026-02-01T00:00:00Z')], rows))
574+
.toEqual(['a']);
575+
expect(warn).not.toHaveBeenCalled();
576+
});
577+
});

0 commit comments

Comments
 (0)