Skip to content

Commit d01f399

Browse files
fix(service-analytics)!: the native SQL strategy leaves a detail row with no parent out of a cross-object filter, as the engine path does (#34335)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbGfxE9QQTsFJp457cGiCViY)_ Fixes #33792 Clause-②: no (narrowing) — on the native SQL strategy, a cross-object `where` leaf that a NULL satisfies (`$ne`, `$nin`, `$notContains` through the lowering's NULL escape, `$null: true`, `$eq: null`, `$exists: false`, `$empty: true`) no longer selects a detail row with no parent (an empty relation, or one naming a record that no longer exists), in each of the three filter positions one compile serves: the query's `where`, a measure's own `filter` and the dataset's own `filter`. `$exists: false` lowers to the same `notSet` leaf and moves with `$null: true`. The engine path and `/data` already left such rows out. BREAKING banner, FROM → TO and ADR-0087 disposition (`not-required (no-migration-prescription)`) are in the changeset. Metadata-protocol: none Skills-docs: none — no `skills/**` file teaches what a related-field analytics filter does with a row that has no parent (`git grep` of `orphan`, `no related record` and `relationship.field` over `skills/`: no analytics hit; `objectstack-ui/rules/dashboards.md` says only "filter by a parent's attribute → a dimension", which stays true). `content/docs/ui/dashboards.mdx` now states the rule for the native path too. ## 维护者速读 - **改了什么**:分析服务的原生 SQL 路径在按关联对象字段过滤(如 `order.status $ne 'open'`)时,不再把"没有父记录"的明细行算进去;引擎路径和 `/data` 本来就不算。 - **为什么改**:同一个仪表盘组件,加不加时间分桶会走不同路径,原生路径多算孤儿明细,合计数随分桶而变(卡片实测 6/1500 对 5/500)。 - **风险与回滚**:只影响原生路径上"NULL 也能满足"的关联叶子(`$ne`/`$nin`/`$notContains` 的 NULL 兜底分支、`$null: true`、`$eq: null`、`$exists: false`、`$empty: true`),查询 `where`、度量自带 `filter`、数据集自带 `filter` 三处同变,这些叶子多一个 `父表.id = 父表.id` 条件(父记录存在为真、孤儿为未知,所以外层 `$not` 翻不成真);正向比较的 SQL 一字不变,`$not` 下的结果与改动前相同。依赖旧行为(把孤儿算进去)的看板合计会变小;回滚 = revert 本 PR。 - **先看**:`packages/services/service-analytics/src/strategies/native-sql-strategy.ts`(`compileFilterNode` 的 leaf 分支与 `NULL_SATISFIED_LEAF_OPERATORS`、`joinedParentKey`)、`src/__tests__/cross-object-negative-orphan.test.ts`、changeset 的 FROM → TO 段。 - **两分钟验证**:`pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/cross-object-negative-orphan.test.ts`,预期 `Tests 24 passed (24)`。 - **需要你做的**:无,席位落地。 ## What changes - `native-sql-strategy.ts` `compileFilterNode`, leaf arm: when the leaf's member is read through a relationship path (it registered a `LEFT JOIN`) and its operator is one whose compiled clause a NULL column can satisfy, the clause becomes `(CLAUSE AND "HOP"."id" = "HOP"."id")` (round 1; it was `("HOP"."id" IS NOT NULL AND CLAUSE)` at `6509c8617c`), where `HOP` is the last hop's join alias from `resolvePathHops`, the one resolver the join itself reads (`order`, `order__customer`). Added only around a clause that bound, so `params` stays aligned. - `NULL_SATISFIED_LEAF_OPERATORS` = `notSet` (the lowering's `col IS NULL` escape arm, `$null: true`, `$eq: null`), `empty` (`col IS NULL OR …`), `notContains` (the constant TRUE on a non-text column, `NOT EXISTS (… json_each(col) …)` on a JSON-stored one). Every other operator compiles to a comparison that is UNKNOWN on a NULL, or to `IS NOT NULL`, so it never selected an orphan; its statement is byte-unchanged (the existing SQL pins in `infer-cube-relation-traversal`, `infer-cube-where-spelling-parity`, `dataset-filter-object-field-binding` and `filter-normalizer-not-null-safe` stay green untouched). - `joinedParentKey` (new private helper): the last hop's `"ALIAS"."id"`, or `null` for a base column or an SQL expression. - `content/docs/ui/dashboards.mdx`: the no-parent rule, stated before for the engine path only, now covers the native path. Premise re-measured: #33652 (relation semi-joins on find verbs) did not reach this compile. On `origin/main` `5a755791a9` the native face still selected both orphans while the engine face and `/data` did not (table below). ## Tests New file `src/__tests__/cross-object-negative-orphan.test.ts`, on `driver-sql` / better-sqlite3 in process, through the plugin's own composition: one native-face service and one engine-face service (`nativeSql: false`) over the same engine, and the engine's own nested-relation `find` as the `/data` control. Fixture: two orphans, `l7` (empty relation) and `l8` (its parent deleted behind the engine), and a parent `o3` that exists with no `status` and no customer. Red first, on `origin/main`'s strategy source (`git restore --source=5a755791a9`) with the new test, at `count / sum(amount)`: | `where` | native, before | engine and `/data` (and native, after) | |:--|:--|:--| | `order.status` `$ne 'open'` / `$nin ['open']` / `$notContains 'pe'` | 6 / 6600 | 4 / 600 | | `order.status` `$null: true` / `$eq: null` / `$empty: true` | 3 / 6300 | 1 / 300 | | `order.status` `$ne 'cancelled'` | 5 / 6302 | 3 / 302 | | `order.customer.tier` `$ne 'gold'` (two hops) | 6 / 6600 | 3 / 300 | | `order.customer.tier` `$null: true` (two hops) | 3 / 6300 | 0 / 0 | | `order.status` `$eq 'cancelled'` (positive control) | 3 / 300 | 3 / 300 | Before: `Tests 11 failed | 1 passed (12)` (the positive control passes). Only the native face failed: zero `objectql:` or `/data` assertion failures in the red log. After: `Tests 12 passed (12)`. Ablation (one-shot, not committed): `notSet` taken out of `NULL_SATISFIED_LEAF_OPERATORS` through `scripts/ablation-replace.mjs` (anchor 1 → 0, injected marker 0 → 1, blob `4ccddcfd54a3` → `ddc23e5a6448`) gives `Tests 10 failed | 2 passed (12)`: every case the escape arm carries goes red, and the two that stay green are `$empty: true` (its own `empty` entry) and the positive control. Restored by the same tool: blob back to `4ccddcfd54a3` = HEAD, `git diff HEAD` empty; re-run `12 passed (12)`. The test imports the strategy by a relative path into `src/`, so no `dist/` sits between the mutation and the run. <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2`: `Test Files 216 passed (216)`, `Tests 5245 passed | 335 skipped (5580)`, exit 0. - `pnpm --filter @objectstack/service-analytics typecheck`: exit 0. </details> ## Acceptance notes - `$not` over a cross-object leaf: a `$not` operand reaches the leaf arm with `notSet`, `empty` and `notContains` leaves too (the lowering leaves `$null`, `$empty` and a null `$eq` alone under `$not`, and escapes `$ne` / `$nin` / `$notContains`). At `6509c8617c` the conjunct was FALSE for an orphan, so `NOT` selected it, a widening caught in review. From round 1 the conjunct is `id = id`, which is UNKNOWN for an orphan; under Kleene logic that never turns a row the compile left out into a selected one, so the `$not` answer is main's. A positive comparison under `$not` (`{ $not: { 'order.status': 'open' } }`) still selects an orphan, as on main; the engine path refuses the shape (`negated`). - Two native answers still select an orphan. Both are unchanged by this PR, stated in the docs and the changeset, and not closed here. One is a positive comparison under `$not`: native `6 / 6600` on main and at this head, and the engine refuses the shape. The other is `$nin: []`, which folds to the constant TRUE: native `8 / 6602` (every line) on main and at this head, where the engine face answers `6 / 602` and `/data` answers `l1`-`l6`. That second one is a native-versus-engine disagreement of its own, reported to the seat. - An unreadable parent is outside this change. On the native path a joined object's read scope is its own `WHERE` conjunct, unchanged here. - `content/docs/ui/dashboards.mdx`'s path table still says the engine path reaches "one relationship" and that a path of two or more relationships is refused. The #33626 changeset says the engine now serves up to three. That sentence is outside this card's surface, so it is noted here and not edited. A second stale sentence is on the same page, in the same family. The paragraph after the orphan rule says the engine path refuses a related field in a dataset's own `filter` (`400 INVALID_FIELD`). Measured here through `queryDataset` on the engine face (`nativeSql: false`), a dataset `filter` of `{ 'order.status': { $null: true } }` is answered (`1 / 300`), not refused. A measure's own `filter` is refused as stated. Not edited; reported to the seat with the depth text. ## Fix round 1 Review M1 (comment 6911858976): under `$not` the `IS NOT NULL` conjunct selected orphans main left out. - `native-sql-strategy.ts` L2245-2271: the conjunct is now `(CLAUSE AND "HOP"."id" = "HOP"."id")`. That is TRUE for an existing parent and UNKNOWN for an orphan, so a `NOT` cannot flip it. Replacing TRUE with UNKNOWN is monotone in Kleene logic, so no row the compile left out before is selected at any depth of `NOT`, `AND` or `OR`. Outside `NOT`, UNKNOWN selects exactly what FALSE selects, so the un-negated answers are unchanged. `x = x` on a primary-key column is standard SQL, NULL on NULL in SQLite, PostgreSQL, MySQL and SQL Server. I chose it over a `negated` flag through `compileFilterNode` because the flag would have to decide a meaning per depth, while the UNKNOWN conjunct gives main's `$not` answer by construction. - New pins (native face only): `$not` over `$null: true`, `$eq: null`, `$empty: true`, `$notContains 'pe'`, `$ne 'open'`, inside `$or` and `$and` under the `NOT`, and over two hops. Each is held to main's answer, and `$not {$null: true}` must equal `$null: false`. The two SQL pins now read the new conjunct. - `content/docs/ui/dashboards.mdx` and the changeset now say "outside `$not`", and that a positive comparison under `$not` still selects such a row. Measured in round 2 (below). Every hand-derived `$not` value held; no pin value changed. ## Fix round 2 Takeover round: round 1 measured, and the review's S1, S2, N1 and N2 applied. Head `b779b7f25e`. No change to `native-sql-strategy.ts` this round. - **S1:** the changeset's BREAKING notice names the three filter positions one compile serves: the query's `where`, a measure's own `filter` (its conditional aggregate) and the dataset's own `filter`. The docs sentence names them too. New pins: a measure `filter` of `$ne 'open'` (native only, because the engine refuses that position) and a dataset `filter` of `$null: true` (native and engine). On main's strategy the native face answered `6 / 6600` and `3 / 6300`. At this head it answers `4 / 600` and `1 / 300`. - **S2:** "whatever the operator" is gone from the docs sentence, the changeset and the test header. Both exceptions are now stated, measured and not closed in code. A positive comparison under `$not` still selects an orphan: native `6 / 6600` on main and here, and its statement is byte-identical. `$nin: []` lowers to `(("order"."status" IS NULL AND "order"."id" = "order"."id") OR 1 = 1)`, which is TRUE for every row: native `8 / 6602` on main and here. The engine face answers `6 / 602` and `/data` `l1`-`l6`. - **N1:** the docs and the changeset now say the `$or` with `{ order: { $null: true } }` brings back rows with an **empty** relation. A row naming a record that no longer exists is not brought back. The existing pin's expected set (`l3`-`l7`, no `l8`) already said so. - **N2:** `$exists: false` is in the operator lists. Measured: it lowers to `"order"."status" IS NULL AND "order"."id" = "order"."id"` (the `notSet` leaf). On main it answered `3 / 6300`; at this head it answers `1 / 300`, equal to the engine. It is pinned on all three faces. <details><summary>Round-1 measurement: the test file against three strategy sources</summary> The test file was the same each time (round 1's 21 cases). Only `native-sql-strategy.ts` was swapped, tree-only (`git restore --source=REF`), then restored with `git checkout HEAD --`. Restore was proven each time by blob = HEAD `37ce29eca260` and an empty `git diff HEAD`. - At `f2b0b56f3f` (round-1 head): `Tests 21 passed (21)`. - Main's source `5a755791a9` (blob `854df5b5f4f2`): `Tests 11 failed | 10 passed (21)`. The 11 red are the un-negated narrowing cases. The 10 green are all 8 `$not` pins, the `$not {$null: true}` = `$null: false` pin and the positive control. So every hand-derived `$not` value equals main's measured answer, and no pin value changed. - Round-0 source `6509c8617c` (blob `4ccddcfd54a3`): `Tests 9 failed | 12 passed (21)`. Red: 7 of the 8 `$not` pins, the equality pin and the SQL-text pin. `$not $ne 'open'` stays green there, as the review predicted, because the escape arm under `NOT` is UNKNOWN either way. With round 2's pins (24 cases), main's source gives `Tests 14 failed | 10 passed (24)`: the three new pins are red there too. At this head: `Tests 24 passed (24)`. </details> <details><summary>Ablation on the negation guard (one-shot, not committed)</summary> `node scripts/ablation-replace.mjs` replaced the anchor `` `(${clause} AND ${parentKey} = ${parentKey})` `` with `` `(${clause} AND ${parentKey} IS NOT NULL)` ``. The tool's on-disk evidence: anchor 1 → 0, replacement 0 → 1, blob `37ce29eca260` → `2f756be31b88`. Result: `Tests 9 failed | 12 passed (21)`, the same nine as at `6509c8617c` (every `$not` pin but `$not $ne 'open'`, the equality pin and the SQL-text pin). The tool then restored the file: blob back to `37ce29eca260` = HEAD, `git diff HEAD` empty. The test imports the strategy by a relative path into `src/`, so no `dist/` sits between the mutation and the run. </details> <details><summary>Package suite, typecheck and gates at b779b7f</summary> - `pnpm --filter @objectstack/service-analytics test`: `Test Files 216 passed (216)`, `Tests 5257 passed | 335 skipped (5592)`. `typecheck` (`tsc --noEmit`, `include: ["src"]`, so it compiles the test file): exit 0. Lock verdict `command-exit 0`. - Local subset of the derived families, each exit 0: `check:test-source-alias`, `check:nul-bytes`, `check:doc-authoring`, `check:issue-citations`, `check-adr-0087-registration --base origin/main` (exemption `no-migration-prescription` read), `check-empty-changeset`, `check-changeset-no-major`, `check-affected-docs`, `check-closing-keyword-parity`, `check:cross-package-test-inputs`, `check:docs-single-h1`, `check:doc-anchors`. `dispatch-gates --ran`: 12 of 97 derived families run locally. The other 85 are declared to CI, which runs the farm. - `check-governed-merges.mjs --pr 34335`: 0 of 4 paths governed, +405 / -1 at the time of reading. Ordinary queue landing applies. - `Lint & Repo Gates` and `TypeScript Type Check` on `85d43a40` concluded `failure` only because their aggregators read 16 lanes `cancelled`. Actions run 43847650486 concluded `cancelled` when `b779b7f25e` was pushed. No lane concluded `failure` on that head. - Dogfood battery (title `!` with a `(narrowing)` arm): closure `pnpm --filter '@objectstack/dogfood^...' build` `command-exit 0`, then `pnpm --filter @objectstack/dogfood test` under the lock at `b779b7f25`, with no shard and no path: `Test Files 473 passed | 3 skipped (476)`, `Tests 4003 passed | 42 skipped (4045)`, lock verdict `command-exit 0` (40m07s, shared box). No failures. </details> ## Verification Before push: no open pull request touches `native-sql-strategy.ts`. All 61 open pull requests were read through the REST files listing, so there was nothing to `merge-tree` against. Round-2 gate readings are in Fix round 2 above and in the report comment on the card. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pHNFS9mn8hS13iGyL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 23a18fd commit d01f399

4 files changed

Lines changed: 405 additions & 1 deletion

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(service-analytics)!: the native SQL strategy evaluates a cross-object `where` leaf on an existing parent, so a detail row with no parent is not selected, as on the engine path and `/data`
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. The moved answer is an aggregate over a cross-object filter, which now leaves out the detail rows with no parent, as the engine path and the /data nested-relation filter already did: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** for a reader of an analytics answer served by the native SQL strategy (a cube or dataset query with no bucketed time dimension, on a SQL datasource) that reads a related object's field through a relationship path (`'order.status'`) in any of the three filter positions one compile serves: the query's `where`, a measure's own `filter` (its conditional aggregate) and the dataset's own `filter`:
13+
14+
- FROM: a detail row whose relation field is empty, or names no existing record, was selected by `$ne`, `$nin`, `$notContains`, `$null: true`, `$eq: null`, `$exists: false` and `$empty: true` on the related field, because the `LEFT JOIN` read every related column of such a row as NULL. So the same widget answered a different total once a time bucket sent it to the engine path. TO: such a leaf is evaluated on an existing parent (the last hop's `id = id` is conjoined to it, through every hop of the path: TRUE for an existing parent, UNKNOWN for none, so a `$not` cannot flip it), and outside `$not` no such row is selected by those operators. Under `$not` the native answer is the one it gave before. The native, engine and `/data` answers agree on those operators.
15+
16+
**Not moved.** A parent that exists with no value in the field still satisfies `$ne`, `$nin`, `$notContains` and `$null: true`. A positive operator (`$eq` a value, `$in`, `$gt`, `$contains`, …) selected no such row before either, and its statement is unchanged. A leaf on the base relation field itself (`{ order: { $null: true } }`) reads no join and is unchanged. Two native-path answers still select such a row, unchanged by this release: a positive comparison under `$not` (`{ $not: { 'order.status': 'open' } }`, a shape the engine path refuses; write `$ne` / `$nin` inside the condition instead), and `$nin: []`, which folds to the constant TRUE and selects every row, where the engine path leaves such rows out.
17+
18+
The fix for an author who wants the rows with an empty relation: OR the base relation field in, `{ $or: [{ 'order.status': { $ne: 'open' } }, { order: { $null: true } }] }`. A row naming a record that no longer exists is not brought back by it, on either path.

‎content/docs/ui/dashboards.mdx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,21 @@ the base rows whose relationship points at a record it returned:
532532
condition under `$not` (write `$ne` / `$nin` inside the condition instead), and
533533
a related field compared with another field (`$field`).
534534

535+
On the native SQL path, too, a related-field condition that is not under
536+
`$not` never selects a row with no related record (an empty relationship, or
537+
one naming a record that no longer exists), whether it sits in the query's
538+
filter, a measure's own `filter` or the dataset's own `filter`: `$ne`, `$nin`,
539+
`$notContains`, `$null: true`, `$eq: null`, `$exists: false` and `$empty: true`
540+
included, so the two paths agree on such rows. The same `$or` brings back the
541+
rows with an empty relationship on both paths; a row naming a record that no
542+
longer exists is not brought back by it. A related record that exists with no
543+
value in the field still satisfies `$ne` and `$nin`. Two native-path exceptions
544+
remain: under `$not`, which the engine path refuses, the native path still
545+
selects such a row when the negated condition is a comparison with a value
546+
(`{ $not: { 'order.status': 'open' } }`), so write `$ne` / `$nin` inside the
547+
condition instead; and `$nin: []` (an empty list) selects every row on the
548+
native path, such rows included, where the engine path leaves them out.
549+
535550
A related field in a **dataset's own** `filter`, or in a **measure's** own
536551
`filter`, is still evaluated only on the native SQL path; the engine-aggregate
537552
path refuses it (`400 INVALID_FIELD`) rather than count rows it cannot join.

0 commit comments

Comments
 (0)