From 937010052fa633ed83320ac522fa97c738295de9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 13:13:27 +0000 Subject: [PATCH 1/2] fix(service-analytics): the draft preview resolves a { $field } comparand as the live faces do Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As92T28dA9wc7wtu3iE --- .../preview-field-reference-comparand.md | 10 + .../preview-field-reference-36677.test.ts | 279 ++++++++++++++++++ .../src/preview-evaluator.ts | 34 ++- .../src/preview-field-reference.ts | 223 ++++++++++++++ 4 files changed, 544 insertions(+), 2 deletions(-) create mode 100644 .changeset/preview-field-reference-comparand.md create mode 100644 packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts create mode 100644 packages/services/service-analytics/src/preview-field-reference.ts diff --git a/.changeset/preview-field-reference-comparand.md b/.changeset/preview-field-reference-comparand.md new file mode 100644 index 00000000000..0477990905e --- /dev/null +++ b/.changeset/preview-field-reference-comparand.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-analytics': patch +--- + +Clause-②: no +Metadata-protocol: none + +The analytics draft preview (`queryDataset` with `previewDrafts`, the face Studio's preview mode reads) now resolves a `{ $field }` comparand the way the published dataset does. A comparison between two scalar columns of the row (`{ label: { $eq: { $field: 'alias' } } }`, and `$ne` / `$gt` / `$gte` / `$lt` / `$lte`) compares the two columns, with the same answer for empty values as the live faces (both empty is equal). A reference the live faces refuse is refused with their `INVALID_FILTER` / 400: a multi-value, JSON, file or formula column on either side, two columns of different comparison classes, an undeclared column, a dotted path, and a reference in an `$in` / `$nin` list or under a text-pattern operator. Before, the preview compared the row value with the reference object as text, so every field-to-field filter showed a wrong count with no error, and the count changed at publish. + +One shape is refused on the preview although the published dataset serves it: a reference with an `addDays` offset (`{ $field: 'due_on', addDays: 3 }`). The preview refuses it by name rather than evaluate the day shift differently; publish the draft to chart it. diff --git a/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts b/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts new file mode 100644 index 00000000000..38df87901f8 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts @@ -0,0 +1,279 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36677] The draft preview answers a `{ $field }` comparand as the live + * faces of the dataset door answer it: a scalar-to-scalar reference compares + * the row's two columns, and a reference the live faces refuse is refused with + * their `INVALID_FILTER` / 400. + * + * Measured on `origin/main` (`e845656d`) before the change, through + * `queryDataset` on the production composition below (counts over the six + * rows of {@link ROWS}): + * + * | filter | native | ObjectQL | preview | + * |---|---|---|---| + * | `label $eq {$field:'alias'}` | 2 | 2 | 0 | + * | `label $ne {$field:'alias'}` | 4 | 4 | 6 | + * | `label $gt {$field:'alias'}` | 1 | 1 | 4 | + * | `label $eq {$field:'tags'}` (and `picks`, a `select` declared `multiple`) | 400 | 400 | 0 | + * | `label $ne {$field:'tags'}` (and `picks`) | 400 | 400 | 6 | + * | `label $eq {$field:'amount'}` (cross-class) | 400 | 400 | 0 | + * | `label $in [{$field:'alias'}]` | 400 | 400 | 0 | + * + * The preview compared the row value with the reference OBJECT, as text. + * + * What these pins hold: + * - the scalar rows, under all six operators, `$not` and `$or`: the preview's + * count EQUALS the native strategy's, and both equal the declared count; + * - the multi-value rows, and every other reference the live faces refuse: + * the preview refuses with the same `code` and `status`; + * - the shared cross-field corpus (`@objectstack/driver-sql`'s + * `CROSS_FIELD_CASES`, which holds `@objectstack/formula`'s evaluator and the + * SQL compile to the same rows) row for row at the preview's filters, and + * its refusal table refused, but for the two tenant-column rows the preview + * does not judge (`preview-field-reference.ts`); + * - the one shape the preview refuses where a live face serves it: an + * `addDays` offset reference, refused by name over the corpus's offset + * cases, while the same corpus's bare-reference controls are served with its + * rows. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { + CROSS_FIELD_CASES, + CROSS_FIELD_OBJECT_FIELDS, + CROSS_FIELD_OFFSET_CASES, + CROSS_FIELD_OFFSET_OBJECT_FIELDS, + CROSS_FIELD_OFFSET_ROWS, + CROSS_FIELD_REFUSALS, + CROSS_FIELD_ROWS, + SqlDriver, +} from '@objectstack/driver-sql'; +import type { ValueShapeFieldDef } from '@objectstack/spec/data'; +import { DatasetSchema, type Dataset } from '@objectstack/spec/ui'; +import type { AnalyticsQuery } from '@objectstack/spec/contracts'; +import type { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import { lowerPreviewRowFilters } from '../preview-evaluator.js'; +import { PREVIEW_FIELD_REFERENCE_OPERATORS } from '../preview-field-reference.js'; +import { CROSS_FIELD_COMPARISON_OPERATORS } from '../comparand-shape.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECT = 'os36677_item'; + +/** One row per cell of the comparison's truth table, on a text pair and a numeric pair. */ +const ROWS = [ + { id: 'r1', label: 'b', alias: 'a', amount: 10, budget: 5, tags: ['b'], picks: ['b'] }, // target > referent + { id: 'r2', label: 'a', alias: 'b', amount: 3, budget: 5, tags: ['a'], picks: ['a'] }, // target < referent + { id: 'r3', label: 'm', alias: 'm', amount: 7, budget: 7, tags: ['m'], picks: ['m'] }, // equal + { id: 'r4', label: null, alias: 'm', amount: null, budget: 5, tags: null, picks: null }, // target empty + { id: 'r5', label: 'w', alias: null, amount: 10, budget: null, tags: ['w'], picks: ['w'] }, // referent empty + { id: 'r6', label: null, alias: null, amount: null, budget: null, tags: null, picks: null }, // both empty +]; + +const DATASET = DatasetSchema.parse({ + name: 'os36677_items', + label: 'Items', + object: OBJECT, + dimensions: [{ name: 'label', field: 'label', type: 'string' }], + measures: [{ name: 'cnt', aggregate: 'count' }], +}) as Dataset; + +/** A `'protocol'` service answering one pending seed draft of the same rows, which routes `previewDrafts` onto the draft preview. */ +const pendingSeedProtocol = { + getMetaItems: async () => [{ name: 'os36677_seed', object: OBJECT }], + getMetaItem: async () => ({ item: { records: ROWS } }), +}; + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; + +type Face = 'native' | 'objectql' | 'preview'; +const FACES: readonly Face[] = ['native', 'objectql', 'preview']; + +/** The scalar rows: the filter and the count the native strategy answers (measured, see the header). */ +const SCALAR: Array<[Record, number]> = [ + [{ label: { $eq: { $field: 'alias' } } }, 2], + [{ label: { $ne: { $field: 'alias' } } }, 4], + [{ label: { $gt: { $field: 'alias' } } }, 1], + [{ label: { $gte: { $field: 'alias' } } }, 2], + [{ label: { $lt: { $field: 'alias' } } }, 1], + [{ label: { $lte: { $field: 'alias' } } }, 2], + [{ amount: { $eq: { $field: 'budget' } } }, 2], + [{ amount: { $ne: { $field: 'budget' } } }, 4], + [{ amount: { $gt: { $field: 'budget' } } }, 1], + [{ $not: { label: { $eq: { $field: 'alias' } } } }, 4], + [{ $or: [{ label: { $gt: { $field: 'alias' } } }, { label: 'w' }] }, 2], + [{ label: { $eq: { $field: 'label' } } }, 6], +]; + +/** References every live face refuses `INVALID_FILTER` / 400. */ +const REFUSED: Record[] = [ + { label: { $eq: { $field: 'tags' } } }, + { label: { $ne: { $field: 'tags' } } }, + { label: { $eq: { $field: 'picks' } } }, + { label: { $ne: { $field: 'picks' } } }, + { label: { $gt: { $field: 'tags' } } }, + { tags: { $eq: { $field: 'label' } } }, + { label: { $eq: { $field: 'amount' } } }, + { label: { $eq: { $field: 'nope' } } }, + { label: { $eq: { $field: 'account.name' } } }, + { label: { $in: [{ $field: 'alias' }] } }, + { label: { $contains: { $field: 'alias' } } }, + { amount: { $eq: { $field: 'budget', addDays: 1 } } }, +]; + +describe('[#36677] the draft preview resolves a { $field } comparand as the live faces do', () => { + let engine: ObjectQL; + const services: Partial> = {}; + + const query = (face: Face, runtimeFilter: Record) => + services[face === 'preview' ? 'objectql' : face]!.queryDataset( + DATASET, + { measures: ['cnt'], runtimeFilter } as never, + undefined, + face === 'preview' ? { previewDrafts: true } : undefined, + ) as Promise<{ rows: Array> }>; + + const countOf = async (face: Face, filter: Record) => Number((await query(face, filter)).rows[0]?.cnt ?? 0); + + const refusalOf = async (face: Face, filter: Record) => { + try { + await query(face, filter); + } catch (e) { + const { code, status } = e as { code?: unknown; status?: unknown }; + return { code, status }; + } + return 'served'; + }; + + 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: OBJECT, + label: 'Item', + fields: { + label: { name: 'label', type: 'text' }, + alias: { name: 'alias', type: 'text' }, + amount: { name: 'amount', type: 'number' }, + budget: { name: 'budget', type: 'number' }, + tags: { name: 'tags', type: 'tags' }, + picks: { name: 'picks', type: 'select', multiple: true, options: ['a', 'b', 'm', 'w'].map((value) => ({ label: value, value })) }, + }, + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + for (const row of ROWS) await engine.insert(OBJECT, { ...row } as never); + + for (const [face, caps] of [ + ['native', undefined], + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], + ] as const) { + const registered: Record = {}; + const provided: Record = { data: engine, protocol: pendingSeedProtocol }; + 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 */ } + }); + + it('CONTROL: the fixture is served unfiltered on every face', async () => { + for (const face of FACES) expect(await countOf(face, {}), face).toBe(ROWS.length); + }); + + for (const [filter, count] of SCALAR) { + it(`${JSON.stringify(filter)} → ${count}, the preview equal to the native strategy`, async () => { + const [native, objectql, preview] = await Promise.all(FACES.map((face) => countOf(face, filter))); + expect({ native, objectql, preview }).toEqual({ native: count, objectql: count, preview: count }); + }); + } + + for (const filter of REFUSED) { + it(`${JSON.stringify(filter)} is refused INVALID_FILTER / 400 on every face`, async () => { + const answers = await Promise.all(FACES.map((face) => refusalOf(face, filter))); + const refused = { code: 'INVALID_FILTER', status: 400 }; + expect(answers).toEqual([refused, refused, refused]); + }); + } +}); + +// ───────────────────────────────────────────────────────────────────────────── + +/** The preview's row filters for `where`, with the corpus fixture's declarations. */ +function previewFiltersOver(fields: Record>) { + const SHAPES = fields as Record; + const declaredShape = (field: string) => SHAPES[field] ? { type: SHAPES[field]!.type, multiple: SHAPES[field]!.multiple === true } : undefined; + const declaredType = (field: string) => SHAPES[field]?.type; + const CUBE = { name: 'c', sql: 'x', measures: {}, dimensions: {} } as never; + return (where: unknown) => + lowerPreviewRowFilters({ cube: 'c', measures: [], where } as unknown as AnalyticsQuery, CUBE, declaredType, undefined, declaredShape); +} + +/** Does any `{ $field }` in `node` carry an `addDays` offset? */ +function carriesOffset(node: unknown): boolean { + if (Array.isArray(node)) return node.some(carriesOffset); + if (node === null || typeof node !== 'object') return false; + const record = node as Record; + if (typeof record.$field === 'string' && record.addDays !== undefined) return true; + return Object.values(record).some(carriesOffset); +} + +describe('[#36677] the preview filters, measured against the shared cross-field corpus', () => { + const filtersOf = previewFiltersOver(CROSS_FIELD_OBJECT_FIELDS); + + it('evaluates exactly the six operators the live faces compile a reference under', () => { + expect([...PREVIEW_FIELD_REFERENCE_OPERATORS.keys()].sort()).toEqual([...CROSS_FIELD_COMPARISON_OPERATORS].sort()); + }); + + it.each(CROSS_FIELD_CASES.map((c) => [c.name, c] as const))('%s', (_name, c) => { + const { matches } = filtersOf(c.filter); + const ids = CROSS_FIELD_ROWS.filter((row) => matches({ ...row })).map((row) => row.id); + expect(ids).toEqual(c.expected); + }); + + /** The two rows the preview cannot judge: it is handed no tenant-column fact (see `preview-field-reference.ts`). */ + const TENANT_ROWS = new Set([ + 'the tenant-isolation column is refused as the REFERENT', + 'the tenant-isolation column is refused as the TARGET', + ]); + + it('the tenant rows are present in the corpus, so the exclusion below names real rows', () => { + expect(CROSS_FIELD_REFUSALS.filter((c) => TENANT_ROWS.has(c.name))).toHaveLength(TENANT_ROWS.size); + }); + + it.each(CROSS_FIELD_REFUSALS.filter((c) => !TENANT_ROWS.has(c.name)).map((c) => [c.name, c] as const))('%s', (_name, c) => { + expect(() => filtersOf(c.filter)).toThrow(expect.objectContaining({ code: 'INVALID_FILTER', status: 400 })); + }); + + const offsetFiltersOf = previewFiltersOver(CROSS_FIELD_OFFSET_OBJECT_FIELDS); + const OFFSET = CROSS_FIELD_OFFSET_CASES.filter((c) => carriesOffset(c.filter)); + const BARE = CROSS_FIELD_OFFSET_CASES.filter((c) => !carriesOffset(c.filter)); + + it('the offset corpus carries both kinds of row, so neither table below is empty', () => { + expect({ offset: OFFSET.length > 0, bare: BARE.length > 0 }).toEqual({ offset: true, bare: true }); + }); + + it.each(OFFSET.map((c) => [c.name, c] as const))('an offset reference is refused by name: %s', (_name, c) => { + expect(() => offsetFiltersOf(c.filter)).toThrow( + expect.objectContaining({ code: 'INVALID_FILTER', status: 400, message: expect.stringContaining('addDays offset') }), + ); + }); + + it.each(BARE.map((c) => [c.name, c] as const))('a bare reference on the offset fixture is served: %s', (_name, c) => { + const { matches } = offsetFiltersOf(c.filter); + const ids = CROSS_FIELD_OFFSET_ROWS.filter((row) => matches({ ...row })).map((row) => row.id); + expect(ids).toEqual(c.expected); + }); +}); diff --git a/packages/services/service-analytics/src/preview-evaluator.ts b/packages/services/service-analytics/src/preview-evaluator.ts index aa1a1f1a063..821f350cb98 100644 --- a/packages/services/service-analytics/src/preview-evaluator.ts +++ b/packages/services/service-analytics/src/preview-evaluator.ts @@ -9,7 +9,8 @@ // // Scope (deliberately the dataset-query subset, not a general engine): // • Mongo-style `where` filters ($eq implicit, $ne/$gt/$gte/$lt/$lte/ -// $between/$in/$nin/$contains/$notContains/$null, $and/$or/$not) +// $between/$in/$nin/$contains/$notContains/$null, $and/$or/$not), and +// a `{ $field }` comparand under the six scalar operators (#36677) // • timeDimensions date-range filtering + granularity bucketing // (day/week/month/quarter/year) // • group-by dimensions; count / count_distinct / sum / avg / min / max @@ -62,6 +63,14 @@ import type { DurationMeasureSpec } from './strategies/types.js'; import { invalidFilterError, normalizeWhereComparands } from './strategies/filter-normalizer.js'; import { comparisonColumnClass, refusePreviewJsonColumnComparisons } from './json-column-comparison-refusal.js'; import { isJsonStoredShape } from './contains-membership-sql.js'; +// [#36677] A `{ $field }` comparand: resolved against the row's own column +// under the six scalar operators, and refused where the live faces refuse it. +import { isFieldReference } from './comparand-shape.js'; +import { + assertPreviewFieldReferencesEvaluable, + fieldReferencePredicate, + refusePreviewFieldReferenceClasses, +} from './preview-field-reference.js'; import type { AnalyticsQuery, AnalyticsResult } from '@objectstack/spec/contracts'; import { emptyGroupValueFor, lowerFilterCondition, type Cube, type FilterLoweringOptions, type ValueShapeFieldDef } from '@objectstack/spec/data'; @@ -404,6 +413,14 @@ export function matchesWhere( } else if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) { const shape = shapeOf?.(key); for (const [op, expected] of Object.entries(cond as Row)) { + // [#36677] A `{ $field }` comparand compares the row's two columns. + // It used to reach {@link matchOp} as a literal and be compared as the + // text `[object Object]`. See `preview-field-reference.ts`. + const byReference = fieldReferencePredicate(key, op, expected); + if (byReference) { + if (!byReference(row[key], row[(expected as { $field: string }).$field], compare)) return false; + continue; + } if (!matchOp(row[key], op, expected, key, shape)) return false; } } else if (!(row[key] === cond || String(row[key]) === String(cond))) { @@ -781,7 +798,9 @@ function previewStorageComparands(node: Row | undefined, kindOf: PreviewTemporal } else { out[key] = Object.fromEntries(Object.entries(cond as Row).map(([op, expected]) => [ op, - STORAGE_FORM_OPERATORS.has(op) && expected != null ? storageForm(expected, kind) : expected, + // [#36677] A `{ $field }` comparand names a column, not a value: the + // referent is read from the row, which is in its storage form already. + STORAGE_FORM_OPERATORS.has(op) && expected != null && !isFieldReference(expected) ? storageForm(expected, kind) : expected, ])); } } @@ -903,6 +922,10 @@ export function lowerPreviewRowFilters( // text `'null'` or `'undefined'` — onto every driver's answer. const lowered = lowerFilterCondition(normalizeWhereComparands(query.where), lowering); assertPreviewCanEvaluate(lowered); + // [#36677] …and every `{ $field }` comparand where this face evaluates one + // (the six scalar operators, a same-object column, no offset), refused in + // the live faces' positions otherwise. Row-independent, so before any row. + assertPreviewFieldReferencesEvaluable(lowered); // [#36168] …then a scalar comparison on a field declared multi-valued or // JSON-stored, refused as the live faces refuse it: a drafted row holds the // list, which never equals a scalar, so `$in` matched no row and `$nin` @@ -915,6 +938,13 @@ export function lowerPreviewRowFilters( const classOf = (column: string) => comparisonColumnClass(declaredShape?.(column), storedJsonClass?.(column)); refusePreviewJsonColumnComparisons(lowered, classOf, (member) => whereColumns?.[member] ?? member); } + // [#36677] …then each `{ $field }` comparison's two columns, as the live + // faces judge them: both declared, one comparison class + // (`crossFieldComparisonVerdict`). A host that names no declaration is not + // judged, and its references are compared type-blind. + if (declaredShape) { + refusePreviewFieldReferenceClasses(lowered, (member) => declaredShape(whereColumns?.[member] ?? member), declaredShape); + } // [#21505] …then each value comparison in the temporal STORAGE form, the // comparand here and the row value at the match (see {@link previewTemporalKind}). const whereKindOf = previewTemporalKind(whereType); diff --git a/packages/services/service-analytics/src/preview-field-reference.ts b/packages/services/service-analytics/src/preview-field-reference.ts new file mode 100644 index 00000000000..d9e178f2733 --- /dev/null +++ b/packages/services/service-analytics/src/preview-field-reference.ts @@ -0,0 +1,223 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36677] A `{ $field }` comparand on the draft-data preview + * (`preview-evaluator.ts`), answered as the live faces of the dataset door + * answer it. + * + * ## The defect + * + * The preview's operator table compared the row value with the reference + * OBJECT, through `String()` (`'[object Object]'`), so every field-to-field + * filter answered a wrong count with a `200`: `label $eq { $field: 'alias' }` + * matched no row, `$ne` every row, and a reference to a multi-value column + * (`{ $field: 'tags' }`) was counted where both live faces refuse it + * `INVALID_FILTER` / 400. The live faces are one path: `NativeSQLStrategy` + * declines a cross-field comparison (`findCrossFieldComparand`, ruling Q1 = B) + * so it routes to the ObjectQL strategy, whose engine hands it to the driver + * that compiles it (`driver-sql`'s `applyCrossFieldComparison`). + * + * ## The rules, and where each one comes from + * + * - **The truth table** of the six scalar operators is the shared cross-field + * corpus's (`driver-sql`'s `cross-field-conformance-cases.ts`, which pins + * `@objectstack/formula`'s `matchesFilterCondition` and the SQL compile to the + * same rows): `$eq` matches a row whose two columns are both empty, `$ne` is + * its exact complement, and an ordering needs a value on both sides. So every + * arm is TOTAL, and the shared lowering puts no NULL guard around it + * (`operatorIsNullTotal` in `@objectstack/spec/data`). + * - **The comparison class** is `@objectstack/spec`'s + * `crossFieldComparisonVerdict`, the one classification driver-sql, the + * in-process write check and the authoring door read: two columns compare + * only within one class, and a list, an object, a file or a formula column + * has none. + * - **The positions and the referent** follow driver-sql's own refusal arm, + * case for case: a reference must name a declared column of the same object + * (no dotted path), and a reference anywhere but the six scalar operators is + * refused with the sentence this package's `where` door says for it + * (`comparand-shape.ts`). + * + * ## What the preview refuses that a live face serves + * + * One shape: a `{ $field, addDays }` offset reference. The live faces shift a + * `date` / `datetime` referent by whole days in SQL; this face would need a + * second copy of that arithmetic to evaluate it, and an offset it evaluated + * differently would be the wrong number this card removes. It is REFUSED, + * named, in the preview's not-evaluated words (#19810), never answered. + * + * ## What the preview does not judge + * + * The tenant-isolation column. driver-sql refuses it on either side of a + * comparison, reading which column it is off the object's schema + * (`resolveTenantFieldName` in `@objectstack/core`); the preview is handed a + * field's declared shape only (`sourceFieldMeta`), so it compares such a + * reference like any other text column. Recorded on #36677 rather than + * guessed by name here. + * + * Every refusal is the `where` door's envelope (`INVALID_FILTER` / 400), and + * judged once, before any row is read, so an empty seed draft refuses too. + */ + +import { crossFieldComparisonVerdict, type ValueShapeFieldDef } from '@objectstack/spec/data'; +import { + CROSS_FIELD_COMPARISON_OPERATORS, + TEXT_PATTERN_OPERATORS, + isFieldReference, + unbindableListMemberMessage, + unrenderableTextComparandMessage, +} from './comparand-shape.js'; +import { invalidFilterError } from './strategies/filter-normalizer.js'; + +type Row = Record; + +/** + * One scalar operator's test of a row's value against the row's REFERENT — + * the value of the column the `{ $field }` names. `order` is the preview's + * shared operand ordering (`compare` in `preview-evaluator.ts`), handed in so + * the two tables order a pair one way. + */ +export type FieldReferencePredicate = (value: unknown, referent: unknown, order: (a: unknown, b: unknown) => number) => boolean; + +/** Both sides equal, or both empty — the corpus's `$eq` (row 6, both NULL, matches). */ +function referenceEquals(value: unknown, referent: unknown, order: (a: unknown, b: unknown) => number): boolean { + if (referent == null || value == null) return referent == null && value == null; + return value === referent || order(value, referent) === 0; +} + +/** + * The six operators a `{ $field }` comparand is evaluated under — the set + * `comparand-shape.ts` names `CROSS_FIELD_COMPARISON_OPERATORS` (pinned equal + * in this card's test). + */ +export const PREVIEW_FIELD_REFERENCE_OPERATORS: ReadonlyMap = new Map([ + ['$eq', (value, referent, order) => referenceEquals(value, referent, order)], + ['$ne', (value, referent, order) => !referenceEquals(value, referent, order)], + ['$gt', (value, referent, order) => value != null && referent != null && order(value, referent) > 0], + ['$gte', (value, referent, order) => value != null && referent != null && order(value, referent) >= 0], + ['$lt', (value, referent, order) => value != null && referent != null && order(value, referent) < 0], + ['$lte', (value, referent, order) => value != null && referent != null && order(value, referent) <= 0], +]); + +/** + * The predicate for `op` when `comparand` is a reference this face evaluates, + * else `undefined`. An offset reference is refused here too, so a direct + * caller of the matcher cannot have it compared without its offset. + */ +export function fieldReferencePredicate(field: string, op: string, comparand: unknown): FieldReferencePredicate | undefined { + if (!isFieldReference(comparand)) return undefined; + const predicate = PREVIEW_FIELD_REFERENCE_OPERATORS.get(op); + if (predicate && hasOffset(comparand)) throw offsetRefusal(field, op, comparand.$field); + return predicate; +} + +function hasOffset(ref: { $field: string }): boolean { + return 'addDays' in ref && (ref as Row).addDays !== undefined; +} + +function offsetRefusal(field: string, op: string, ref: string): Error { + return fieldReferenceRefusal(field, op, ref, + `the draft-data preview does not evaluate an addDays offset on a field reference. It is ` + + `refused rather than answered: the preview has no copy of the whole-day shift the published ` + + `dataset applies, and a count it shifted differently would change at publish. Publish the ` + + `draft to chart it, or compare against the field without an offset.`); +} + +/** The refusal driver-sql's arm gives a reference, in its words, seated in this face's envelope. */ +function fieldReferenceRefusal(field: string, op: string, ref: string, reason: string): Error { + return invalidFilterError( + `[analytics] Operator "${op}" on field "${field}" compares against another field ` + + `({ "$field": "${ref}" }), which the draft-data preview refuses, as the published dataset ` + + `does: ${reason}`, + ); +} + +/** Each field constraint of a lowered `where`, at any depth, with the key it constrains. */ +function forEachFieldConstraint(where: unknown, visit: (field: string, ops: Row) => void): void { + if (where === null || typeof where !== 'object' || Array.isArray(where)) return; + for (const [key, cond] of Object.entries(where as Row)) { + if (key === '$and' || key === '$or') { + if (Array.isArray(cond)) cond.forEach((arm) => forEachFieldConstraint(arm, visit)); + } else if (key === '$not') { + forEachFieldConstraint(cond, visit); + } else if (cond !== null && typeof cond === 'object' && !Array.isArray(cond) && !(cond instanceof Date)) { + visit(key, cond as Row); + } + } +} + +/** + * The row-INDEPENDENT half: every `{ $field }` comparand sits where this face + * evaluates one, names a same-object column, and carries no offset. Needs no + * declaration, so it runs on every preview. + */ +export function assertPreviewFieldReferencesEvaluable(where: Row | undefined): void { + forEachFieldConstraint(where, (field, ops) => { + for (const [op, comparand] of Object.entries(ops)) { + if (Array.isArray(comparand)) { + if (op === '$in' || op === '$nin') { + comparand.forEach((member, index) => { + if (isFieldReference(member)) throw invalidFilterError(`[analytics] ${unbindableListMemberMessage(op, field, member, index)}`); + }); + } + continue; + } + if (!isFieldReference(comparand)) continue; + if (TEXT_PATTERN_OPERATORS.has(op)) { + throw invalidFilterError(`[analytics] ${unrenderableTextComparandMessage(op, field, comparand)}`); + } + const ref = comparand.$field; + if (!CROSS_FIELD_COMPARISON_OPERATORS.has(op)) { + throw fieldReferenceRefusal(field, op, ref, + `a field reference is a comparand of the six scalar operators only ($eq, $ne, $gt, $gte, $lt, $lte).`); + } + if (ref.includes('.')) { + throw fieldReferenceRefusal(field, op, ref, + `"${ref}" is a dotted path, and a field reference names a column of the same object only ` + + `(no relation traversal).`); + } + if (hasOffset(comparand)) throw offsetRefusal(field, op, ref); + } + }); +} + +/** + * The DECLARATION half: both columns of each comparison are declared and share + * one comparison class (`crossFieldComparisonVerdict`). `targetShapeOf` reads a + * filter key's declared value shape through the column it binds to; + * `columnShapeOf` reads a column's. A type outside `FieldType` is not judged, + * as the shared verdict judges none. + */ +export function refusePreviewFieldReferenceClasses( + where: Row | undefined, + targetShapeOf: (member: string) => ValueShapeFieldDef | undefined, + columnShapeOf: (column: string) => ValueShapeFieldDef | undefined, +): void { + forEachFieldConstraint(where, (field, ops) => { + for (const [op, comparand] of Object.entries(ops)) { + if (!CROSS_FIELD_COMPARISON_OPERATORS.has(op) || !isFieldReference(comparand)) continue; + const ref = comparand.$field; + const referent = columnShapeOf(ref); + if (!referent) { + throw fieldReferenceRefusal(field, op, ref, `"${ref}" is not a declared field of this object — only declared fields can be referenced.`); + } + const target = targetShapeOf(field); + if (!target) { + throw fieldReferenceRefusal(field, op, ref, + `the target field "${field}" is not a declared field of this object, so the two columns' types ` + + `cannot be checked as comparable.`); + } + const verdict = crossFieldComparisonVerdict(target, referent); + if (verdict.verdict === 'no-class') { + const [side, shape] = verdict.right.kind === 'no-class' ? [`"${ref}"`, referent] : [`the target field "${field}"`, target]; + throw fieldReferenceRefusal(field, op, ref, + `${side} (type "${shape.type}"${shape.multiple ? ', multiple' : ''}) has no scalar stored column ` + + `a comparison can read.`); + } + if (verdict.verdict === 'cross-class') { + throw fieldReferenceRefusal(field, op, ref, + `"${field}" is stored as ${verdict.left} but "${ref}" as ${verdict.right}, and a cross-class ` + + `comparison answers differently by backend — compare same-class columns.`); + } + } + }); +} From 8a7f8ff4cae36d39377e34d90dc36ecf2a501fc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 13:20:40 +0000 Subject: [PATCH 2/2] test(service-analytics): type the corpus declarations the preview pins read Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As92T28dA9wc7wtu3iE --- .../src/__tests__/preview-field-reference-36677.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts b/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts index 38df87901f8..6e759297898 100644 --- a/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-field-reference-36677.test.ts @@ -213,9 +213,11 @@ describe('[#36677] the draft preview resolves a { $field } comparand as the live /** The preview's row filters for `where`, with the corpus fixture's declarations. */ function previewFiltersOver(fields: Record>) { - const SHAPES = fields as Record; - const declaredShape = (field: string) => SHAPES[field] ? { type: SHAPES[field]!.type, multiple: SHAPES[field]!.multiple === true } : undefined; - const declaredType = (field: string) => SHAPES[field]?.type; + const declaredType = (field: string) => (typeof fields[field]?.type === 'string' ? (fields[field]!.type as string) : undefined); + const declaredShape = (field: string): ValueShapeFieldDef | undefined => { + const type = declaredType(field); + return type === undefined ? undefined : { type, multiple: fields[field]!.multiple === true }; + }; const CUBE = { name: 'c', sql: 'x', measures: {}, dimensions: {} } as never; return (where: unknown) => lowerPreviewRowFilters({ cube: 'c', measures: [], where } as unknown as AnalyticsQuery, CUBE, declaredType, undefined, declaredShape);