diff --git a/.changeset/33792-cross-object-orphan-native.md b/.changeset/33792-cross-object-orphan-native.md new file mode 100644 index 00000000000..db571968c9c --- /dev/null +++ b/.changeset/33792-cross-object-orphan-native.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-analytics': patch +--- + +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` + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**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`: + +- 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. + +**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. + +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. diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index a84c2b15e86..f1b83370864 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -532,6 +532,21 @@ the base rows whose relationship points at a record it returned: condition under `$not` (write `$ne` / `$nin` inside the condition instead), and a related field compared with another field (`$field`). +On the native SQL path, too, a related-field condition that is not under +`$not` never selects a row with no related record (an empty relationship, or +one naming a record that no longer exists), whether it sits in the query's +filter, a measure's own `filter` or the dataset's own `filter`: `$ne`, `$nin`, +`$notContains`, `$null: true`, `$eq: null`, `$exists: false` and `$empty: true` +included, so the two paths agree on such rows. The same `$or` brings back the +rows with an empty relationship on both paths; a row naming a record that no +longer exists is not brought back by it. A related record that exists with no +value in the field still satisfies `$ne` and `$nin`. Two native-path exceptions +remain: under `$not`, which the engine path refuses, the native path still +selects such a row when the negated condition is a comparison with a value +(`{ $not: { 'order.status': 'open' } }`), so write `$ne` / `$nin` inside the +condition instead; and `$nin: []` (an empty list) selects every row on the +native path, such rows included, where the engine path leaves them out. + A related field in a **dataset's own** `filter`, or in a **measure's** own `filter`, is still evaluated only on the native SQL path; the engine-aggregate path refuses it (`400 INVALID_FIELD`) rather than count rows it cannot join. diff --git a/packages/services/service-analytics/src/__tests__/cross-object-negative-orphan.test.ts b/packages/services/service-analytics/src/__tests__/cross-object-negative-orphan.test.ts new file mode 100644 index 00000000000..d1381d1b274 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/cross-object-negative-orphan.test.ts @@ -0,0 +1,304 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A cross-object leaf (`'order.status'`, and through two hops) never selects a + * detail row that has no parent — on the native SQL strategy as on the engine path and + * the `/data` nested-relation filter — outside `$not`, for every operator pinned + * below. Two native answers still select one and are not pinned here: a + * positive comparison under `$not` (the engine refuses the shape) and + * `$nin: []`, which folds to the constant TRUE. + * + * ## What was wrong + * + * The shared lowering (`lowerFilterCondition`, rule 3) makes a negative leaf + * NULL-safe as structure: `{ 'order.status': { $ne: 'open' } }` arrives as + * `$or: [{ 'order.status': { $null: true } }, { 'order.status': { $ne: 'open' } }]`. + * The native strategy reads a dotted member through a `LEFT JOIN`, and for a + * detail row with no parent every joined column is NULL, so the escape arm + * `"order"."status" IS NULL` was TRUE for the orphan and it was counted. The + * engine path reads the parent first and keeps the rows whose relation field + * names one of the parents that match (`cross-object-where.ts`: "no parent + * never matches, whatever the operator"), so the same widget answered a + * different total once a time bucket routed it to the engine. + * + * Measured on `origin/main` `5a755791a9` with this fixture (two orphans: `l7` + * with an empty relation, `l8` naming a parent that is gone), before the + * change, as `count / sum(amount)`: + * + * | `where` on `order.status` | native, before | engine and `/data` (and native, now) | + * |:--|:--|:--| + * | `$ne 'open'`, `$nin ['open']`, `$notContains 'pe'` | 6 / 6600 | 4 / 600 | + * | `$null: true`, `$eq: null`, `$empty: true`, `$exists: false` | 3 / 6300 | 1 / 300 | + * | `$ne 'cancelled'` | 5 / 6302 | 3 / 302 | + * | two hops, `order.customer.tier $ne 'gold'` | 6 / 6600 | 3 / 300 | + * | two hops, `order.customer.tier $null: true` | 3 / 6300 | 0 / 0 | + * + * `$eq 'cancelled'` agreed before and after (3 / 300): a positive comparison is + * UNKNOWN on a NULL, so it never selected an orphan. + * A measure's own `filter` (`$ne 'open'`: 6 / 6600 before, 4 / 600 now) and the + * dataset's own `filter` (`$null: true`: 3 / 6300 before, 1 / 300 now) go + * through the same compile and moved the same way. + * + * ## What holds now + * + * A joined leaf that a NULL column satisfies (`notSet`, `empty`, `notContains`) + * is evaluated on an existing parent: the native compile conjoins the last + * hop's `"ALIAS"."id" = "ALIAS"."id"` to it: TRUE for an existing parent and + * UNKNOWN for an orphan, so a `$not` cannot flip it. Every other leaf is UNKNOWN on a NULL + * and its statement does not move. A parent that exists + * with a NULL `status` still satisfies `$ne` (the #5298 ruling, unchanged), and + * an author who wants the orphans says so on the base relation field + * (`{ order: { $null: true } }`), which reads no join. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { DatasetSchema } from '@objectstack/spec/ui'; +import type { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const CUSTOMER = 'os33792_customer'; +const ORDER = 'os33792_order'; +const LINE = 'os33792_line'; + +const CUSTOMERS = [ + { id: 'c1', tier: 'gold' }, + { id: 'c2', tier: 'silver' }, +] as const; +const ORDERS = [ + { id: 'o1', status: 'open', customer: 'c1' }, + { id: 'o2', status: 'cancelled', customer: 'c2' }, + { id: 'o3' }, // exists, with no status and no customer: `$ne` selects its lines (#5298) + { id: 'o9', status: 'cancelled' }, // removed after its line is written, leaving `l8` naming no record +] as const; +const LINES = [ + { id: 'l1', amount: 1, order: 'o1' }, + { id: 'l2', amount: 1, order: 'o1' }, + { id: 'l3', amount: 100, order: 'o2' }, + { id: 'l4', amount: 100, order: 'o2' }, + { id: 'l5', amount: 100, order: 'o2' }, + { id: 'l6', amount: 300, order: 'o3' }, + { id: 'l7', amount: 1000 }, // an orphan: no parent + { id: 'l8', amount: 5000, order: 'o9' }, // an orphan: its parent is removed below, behind the engine +] as const; + +const DATASET = DatasetSchema.parse({ + name: 'os33792_lines', + label: 'Lines', + object: LINE, + include: ['order', 'order.customer'], + dimensions: [{ name: 'amount', field: 'amount', type: 'number' }], + measures: [ + { name: 'line_count', aggregate: 'count' }, + { name: 'total', aggregate: 'sum', field: 'amount' }, + ], +}); + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; + +type Face = 'native' | 'objectql'; + +describe('a cross-object leaf never selects an orphan detail row, on the native strategy as on the engine', () => { + let engine: ObjectQL; + const services: Partial> = {}; + + const totals = async (face: Face, where: Record) => { + const res = await services[face]!.queryDataset(DATASET, { measures: ['line_count', 'total'], runtimeFilter: where } as never); + const [row] = res.rows as Array>; + return { n: Number(row?.line_count ?? 0), total: Number(row?.total ?? 0) }; + }; + const dataIds = async (where: Record) => + ((await engine.find(LINE, { where } as never)) as Array<{ id: string }>).map((r) => r.id).sort(); + + beforeAll(async () => { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); + engine = new ObjectQL({ logger: quiet } as never); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registry.registerObject({ + name: CUSTOMER, + label: 'Customer', + fields: { tier: { name: 'tier', type: 'text' } }, + } as never); + engine.registry.registerObject({ + name: ORDER, + label: 'Order', + fields: { + status: { name: 'status', type: 'text' }, + customer: { name: 'customer', type: 'lookup', reference: CUSTOMER }, + }, + } as never); + engine.registry.registerObject({ + name: LINE, + label: 'Line', + fields: { + amount: { name: 'amount', type: 'number' }, + order: { name: 'order', type: 'lookup', reference: ORDER }, + }, + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + for (const row of CUSTOMERS) await engine.insert(CUSTOMER, { ...row } as never); + for (const row of ORDERS) await engine.insert(ORDER, { ...row } as never); + for (const row of LINES) await engine.insert(LINE, { ...row } as never); + // A reference the engine would refuse to write, reached the way a stored row + // reaches it: the parent goes away underneath (an import, a direct write). + expect(await driver.delete(ORDER, 'o9')).toBeTruthy(); + + for (const [face, caps] of [ + ['native', undefined], + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], + ] as const) { + const registered: Record = {}; + const provided: Record = { data: engine }; + await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({ + getService: (name: string) => provided[name] ?? registered[name], + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + hook: () => {}, + logger: quiet, + } as never); + services[face] = registered.analytics as AnalyticsService; + } + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + // [where, the nested-relation spelling `/data` serves, the lines each answer selects] + const CASES: Array<[string, Record, Record, string[]]> = [ + ["$ne 'open'", { 'order.status': { $ne: 'open' } }, { order: { status: { $ne: 'open' } } }, ['l3', 'l4', 'l5', 'l6']], + ["$nin ['open']", { 'order.status': { $nin: ['open'] } }, { order: { status: { $nin: ['open'] } } }, ['l3', 'l4', 'l5', 'l6']], + ["$notContains 'pe'", { 'order.status': { $notContains: 'pe' } }, { order: { status: { $notContains: 'pe' } } }, ['l3', 'l4', 'l5', 'l6']], + ['$null true', { 'order.status': { $null: true } }, { order: { status: { $null: true } } }, ['l6']], + ['$eq null', { 'order.status': { $eq: null } }, { order: { status: { $eq: null } } }, ['l6']], + ['$empty true', { 'order.status': { $empty: true } }, { order: { status: { $empty: true } } }, ['l6']], + ['$exists false', { 'order.status': { $exists: false } }, { order: { status: { $exists: false } } }, ['l6']], + ["$ne 'cancelled'", { 'order.status': { $ne: 'cancelled' } }, { order: { status: { $ne: 'cancelled' } } }, ['l1', 'l2', 'l6']], + // A positive operator never selected an orphan: the comparison is UNKNOWN on a NULL. Unchanged. + ["$eq 'cancelled'", { 'order.status': { $eq: 'cancelled' } }, { order: { status: { $eq: 'cancelled' } } }, ['l3', 'l4', 'l5']], + ]; + const sumOf = (ids: string[]) => LINES.filter((l) => ids.includes(l.id)).reduce((s, l) => s + l.amount, 0); + + for (const [label, where, nested, expected] of CASES) { + it(`order.status ${label}: native, engine and /data select the same lines, the orphan not among them`, async () => { + expect(await dataIds(nested), '/data').toEqual(expected); + const want = { n: expected.length, total: sumOf(expected) }; + for (const face of ['native', 'objectql'] as const) { + expect.soft(await totals(face, where), face).toEqual(want); + } + }); + } + + // Two hops: the leaf is evaluated on the record the LAST hop reaches, so a line + // whose order has no customer is not selected either (`l6`, on `o3`). + const TWO_HOP: Array<[string, Record, Record, string[]]> = [ + ["$ne 'gold'", { 'order.customer.tier': { $ne: 'gold' } }, { order: { customer: { tier: { $ne: 'gold' } } } }, ['l3', 'l4', 'l5']], + ['$null true', { 'order.customer.tier': { $null: true } }, { order: { customer: { tier: { $null: true } } } }, []], + ]; + for (const [label, where, nested, expected] of TWO_HOP) { + it(`order.customer.tier ${label}: native, engine and /data select the same lines`, async () => { + expect(await dataIds(nested), '/data').toEqual(expected); + const want = { n: expected.length, total: sumOf(expected) }; + for (const face of ['native', 'objectql'] as const) { + expect.soft(await totals(face, where), face).toEqual(want); + } + }); + } + + it('the native statement over the inferred cube evaluates the joined leaf on an existing parent', async () => { + // A cube query with no time bucket, served natively: the statement, and its answer. + const query = { cube: LINE, measures: ['count'], where: { 'order.status': { $ne: 'open' } } }; + const { sql } = await services.native!.generateSql(query as never); + const res = await services.native!.query(query as never); + expect(sql).toContain('LEFT JOIN "os33792_order" "order" ON'); + // The lowering's NULL-safe escape is evaluated on an existing parent; the + // comparison, UNKNOWN on a NULL, is left as it was. + expect(sql).toContain('(("order"."status" IS NULL AND "order"."id" = "order"."id") OR "order"."status" != $1)'); + expect(Number((res.rows as Array>)[0]?.count)).toBe(4); + + // Two hops: the key of the last hop's join alias. + const twoHop = await services.native!.generateSql({ + cube: LINE, + measures: ['count'], + where: { 'order.customer.tier': { $ne: 'gold' } }, + } as never); + expect(twoHop.sql).toContain('"order__customer"."tier" IS NULL AND "order__customer"."id" = "order__customer"."id"'); + + // A positive leaf takes no conjunct: its statement is the one it always was. + const positive = await services.native!.generateSql({ cube: LINE, measures: ['count'], where: { 'order.status': 'open' } } as never); + expect(positive.sql).toMatch(/ WHERE "order"\."status" = \$1$/); + }); + + it('an author keeps the rows with an empty relation by naming the base relation field, which reads no join', async () => { + const where = { $or: [{ 'order.status': { $ne: 'open' } }, { order: { $null: true } }] }; + const expected = ['l3', 'l4', 'l5', 'l6', 'l7']; + expect(await dataIds({ $or: [{ order: { status: { $ne: 'open' } } }, { order: { $null: true } }] }), '/data').toEqual(expected); + for (const face of ['native', 'objectql'] as const) { + expect.soft(await totals(face, where), face).toEqual({ n: expected.length, total: sumOf(expected) }); + } + }); + + // Under `$not` the native answer is the one it was before the conjunct existed: + // the lowering hands a `$not` operand the same `notSet` / `empty` / + // `notContains` leaves, and a conjunct that were FALSE for an orphan would let + // the `NOT` select it. The engine path refuses a related-field condition under + // `$not` (`negated`), so this is the native face alone, held to its own answer + // on `origin/main` `5a755791a9`. + const NEGATED: Array<[string, Record, string[]]> = [ + ['$not $null true', { $not: { 'order.status': { $null: true } } }, ['l1', 'l2', 'l3', 'l4', 'l5']], + ['$not $eq null', { $not: { 'order.status': { $eq: null } } }, ['l1', 'l2', 'l3', 'l4', 'l5']], + ['$not $empty true', { $not: { 'order.status': { $empty: true } } }, ['l1', 'l2', 'l3', 'l4', 'l5']], + ["$not $notContains 'pe'", { $not: { 'order.status': { $notContains: 'pe' } } }, ['l1', 'l2']], + ["$not $ne 'open'", { $not: { 'order.status': { $ne: 'open' } } }, ['l1', 'l2']], + // Inside a combinator under the `NOT`: an orphan's leaf never decides the branch. + ['$not $or [$null true, amount > 2000]', { $not: { $or: [{ 'order.status': { $null: true } }, { amount: { $gt: 2000 } }] } }, ['l1', 'l2', 'l3', 'l4', 'l5']], + // …and where main's answer DOES select an orphan (`l8`: its `amount` sinks the `$and`), it still does. + ['$not $and [$null true, amount < 2000]', { $not: { $and: [{ 'order.status': { $null: true } }, { amount: { $lt: 2000 } }] } }, ['l1', 'l2', 'l3', 'l4', 'l5', 'l8']], + // Two hops, the last hop's key. + ['$not two-hop $null true', { $not: { 'order.customer.tier': { $null: true } } }, ['l1', 'l2', 'l3', 'l4', 'l5']], + ]; + for (const [label, where, expected] of NEGATED) { + it(`native, ${label}: the answer it gave before the conjunct`, async () => { + expect(await totals('native', where)).toEqual({ n: expected.length, total: sumOf(expected) }); + }); + } + + // The same compile serves the two other filter positions of a dataset: a + // measure's own `filter` (the conditional aggregate) and the dataset's own + // `filter`. Both moved with `where` (native, before: 6 / 6600 and 3 / 6300). + // The engine path refuses a related field in a measure's `filter`, so that + // position is the native face alone. + it("a measure's own filter leaves the orphan out of its conditional aggregate (native)", async () => { + const notOpen = { 'order.status': { $ne: 'open' } }; + const scoped = DatasetSchema.parse({ + ...DATASET, + name: 'os33792_lines_measure_filter', + measures: [ + { name: 'line_count', aggregate: 'count', filter: notOpen }, + { name: 'total', aggregate: 'sum', field: 'amount', filter: notOpen }, + ], + }); + const res = await services.native!.queryDataset(scoped, { measures: ['line_count', 'total'] } as never); + const [row] = res.rows as Array>; + const expected = ['l3', 'l4', 'l5', 'l6']; + expect({ n: Number(row?.line_count), total: Number(row?.total) }).toEqual({ n: expected.length, total: sumOf(expected) }); + }); + + it("the dataset's own filter leaves the orphan out, native and engine alike", async () => { + const scoped = DatasetSchema.parse({ ...DATASET, name: 'os33792_lines_dataset_filter', filter: { 'order.status': { $null: true } } }); + for (const face of ['native', 'objectql'] as const) { + const res = await services[face]!.queryDataset(scoped, { measures: ['line_count', 'total'] } as never); + const [row] = res.rows as Array>; + expect.soft({ n: Number(row?.line_count ?? 0), total: Number(row?.total ?? 0) }, face).toEqual({ n: 1, total: sumOf(['l6']) }); + } + }); + + it('native: `$not` over `$null: true` answers what `$null: false` answers', async () => { + expect(await totals('native', { $not: { 'order.status': { $null: true } } })) + .toEqual(await totals('native', { 'order.status': { $null: false } })); + }); +}); diff --git a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts index 854df5b5f4f..37ce29eca26 100644 --- a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts @@ -389,6 +389,23 @@ function measureColumnOf( return { object: columnObjectOf(cube, parentTable, sql, referenceOf), field: sql.slice(sql.lastIndexOf('.') + 1) }; } +/** + * The leaf operators whose compiled clause a NULL column can satisfy, so a + * joined column's NULL from a row the `LEFT JOIN` reached no parent for would + * select that row ({@link NativeSQLStrategy}'s `compileFilterNode` leaf arm): + * + * - `notSet` — `col IS NULL`, the escape arm of the negative operators' NULL + * guard, `$null: true` and `$eq: null`; + * - `empty` — `col IS NULL OR …` (`empty-operator-sql.ts`); + * - `notContains` — the constant TRUE on a column that stores no text + * (`non-text-column.ts`), and `NOT EXISTS (… json_each(col) …)` on a + * JSON-stored one (`contains-membership-sql.ts`), both TRUE on a NULL. + * + * Every other operator of the normalized vocabulary compiles to a comparison + * that is UNKNOWN on a NULL, or to `IS NOT NULL`, and selects no such row. + */ +const NULL_SATISFIED_LEAF_OPERATORS: ReadonlySet = new Set(['notSet', 'empty', 'notContains']); + /** * [#20986] The joins ONE statement registers, keyed by alias: each join's SQL * and the object it reads — the object {@link resolvePathHops} named for that @@ -2034,6 +2051,29 @@ export class NativeSQLStrategy implements AnalyticsStrategy { return this.qualifyAndRegisterJoin(member, parentTable, joins, cube); } + /** + * The key column of the row a filter member's relationship path reaches, as + * {@link qualifyAndRegisterJoin} joined it (`"order"."id"`, or + * `"account__owner"."id"` for two hops), or `null` for a base-table column or + * an SQL expression. The hops are {@link resolvePathHops}'s, the one resolver + * the join itself reads; every hop joins `ON … = ""."id"`, so the last + * hop's key is NULL exactly when the chain reached no row. Read after the + * leaf resolved, so the join is registered. + */ + private joinedParentKey( + cube: Cube, + member: string, + parentTable: string, + joins: StatementJoins, + ): string | null { + const rawSql = this.lookupFilterMember(cube, member)?.sql ?? member; + if (!rawSql.includes('.') || !IDENTIFIER_PATH.test(rawSql)) return null; + const hops = rawSql.split('.').slice(0, -1); + const resolved = resolvePathHops(cube, parentTable, hops, joins.referenceOf); + const last = resolved[resolved.length - 1]; + return last && joins.has(last.alias) ? `"${last.alias}"."id"` : null; + } + /** * Resolve the (object, column) a filter member binds against, so its * comparand can be coerced to that column's on-disk storage form. @@ -2201,7 +2241,34 @@ export class NativeSQLStrategy implements AnalyticsStrategy { // Resolve the (object, column) this member binds against so the value // can be coerced to the column's storage form (see buildFilterClause). const target = this.resolveStorageTarget(cube, node.member, parentTable, joins.referenceOf); - return this.buildFilterClause(colExpr, node.operator, node.values, params, ctx, target); + const clause = this.buildFilterClause(colExpr, node.operator, node.values, params, ctx, target); + // A leaf on a joined column is evaluated on an EXISTING parent. The + // `LEFT JOIN` gives a detail row with no parent a NULL in every joined + // column, and a leaf a NULL satisfies read that NULL as "the parent's + // value is missing", selecting the orphan: the escape the shared lowering + // lays around `$ne` / `$nin` / `$notContains` (`col IS NULL OR …`), + // `$null: true`, `$eq: null`, `$empty: true`. The engine path and the + // `/data` nested-relation filter read the parent first, so no parent + // never matches, whatever the operator (`cross-object-where.ts`); this + // conjunct is that rule here. Only the operators of + // {@link NULL_SATISFIED_LEAF_OPERATORS} take it: every other clause is + // UNKNOWN on a NULL and already leaves the orphan out. A parent that + // exists with a NULL value still answers its own polarity (#5298). Added + // only around a clause that bound, so `params` stays aligned. + // + // The conjunct is `key = key`, never `key IS NOT NULL`: it is TRUE for an + // existing parent and UNKNOWN (not FALSE) for an orphan, so the leaf is + // UNKNOWN there. A `$not` operand reaches this arm with the same leaves + // (the lowering leaves `$null` / `$empty` / a null `$eq` alone under + // `$not`, and escapes `$ne` / `$nin` / `$notContains`), and a FALSE leaf + // would let the `NOT` select the orphan. Under Kleene logic, turning TRUE + // into UNKNOWN can never turn a FALSE row TRUE, at any depth of `NOT`, + // `AND` or `OR`, so no row this compile left out before is selected now. + // Outside a `NOT`, UNKNOWN selects exactly what FALSE selects. + const parentKey = clause !== null && NULL_SATISFIED_LEAF_OPERATORS.has(node.operator) + ? this.joinedParentKey(cube, node.member, parentTable, joins) + : null; + return parentKey ? `(${clause} AND ${parentKey} = ${parentKey})` : clause; } if (node.kind === 'not') {