Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/31842-dotted-filter-member-tail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/service-analytics': patch
---

fix(service-analytics)!: a dotted member such as `vendor.region` no longer names a declared member by its tail alone, so a filter on a related field never silently filters the base field of the same name

Clause-②: no (narrowing) — a dotted analytics member (a `where` / `runtimeFilter` leaf, a dimension, a time dimension, an `order` key) whose first segment is neither the cube's name nor the object it reads, and which no member declares verbatim, is no longer resolved to the declared member named by its last segment. It is a relationship path: through a compiled dataset the `include` gate refuses an undeclared path, and the related-column gate refuses a column the related object lacks, both `INVALID_FIELD` / 400 as before; a declared path filters the related column. An underscore-flattened key (`vendor_region`) answers `vendor.region` only when its own `sql` is that same relationship path. Nothing is widened: no export of the package root, public member, error code or status is added.
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export or type of the package root changes: a query member that read the wrong column is answered as the relationship path it spells, with error codes and statuses already on the wire. There is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** accept-set narrowing on the analytics query doors (`@objectstack/service-analytics`), for a dotted member whose last segment names a declared member while its first segment names neither the cube nor its object.

- **Before.** Measured on `main` `31ae944b` with a real `SqlDriver`: a dataset over a deal that declares its own `region`, with a `vendor` lookup to an object that has no `region`, answered `runtimeFilter: { 'vendor.region': 'emea' }` with the deals whose OWN region is EMEA, on the native-SQL and the engine-aggregate strategies alike (`WHERE region = ?`), with or without `vendor` in the dataset's `include`. A `supplier.region` filter over a supplier that does have `region` filtered the deal's own `region` too, and so did `vendor.region` beside a dataset dimension `vendor_region` over the base `region`. A hand-authored cube answered the same way through `AnalyticsService.query`.
- **Now.** Without `vendor` in the `include`, `vendor.region` is refused `INVALID_FIELD` / 400 ("traverses relationship path 'vendor', which the dataset does not declare in its `include`"). With it, a related object that lacks `region` is refused `INVALID_FIELD` / 400 naming the related object, and one that has it is filtered on the joined column (the engine-aggregate strategy keeps refusing any related filter, as it does for every other one). On a hand-authored cube, which has no `include` gate, the native strategy joins the lookup as it does for any other related member: `supplier.region` filters the supplier's column, and a related object that lacks the column answers the database's refusal (`DATABASE_ERROR` / 500), the same answer `vendor.anything_missing` gets today. `<cube>.region` and `<object>.region` still name the declared `region`.
- **Who moves.** A query, dashboard filter or tool call that wrote `<lookup>.<field>` to mean the base object's own `<field>`: spell it `<cube>.<field>` or `<field>`. No first-party metadata in `content/`, `examples/`, `skills/` or the dogfood apps spells one.

**The remedy.** A member written `'vendor.region'` to mean the base object's own field is spelled `'<cube>.region'` or `'region'` instead. A stored member is not rewritten for you: whether it meant the base field or the related one is the author's intent, which no migration can read.
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,199 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do
expect(err.member).toBe('account.name');
});
});

/**
* [#31842] A dotted FILTER member whose tail names a declared member, on both
* live strategies, through a compiled dataset (`queryDataset`) and a
* hand-authored cube (`query`), on real SQLite.
*
* The deal declares its own `region`; `vendor` is a lookup to an object with
* NO `region`, `supplier` a lookup to one that has it. Before, a dotted member
* named a declared key by its tail alone, whatever its first segment, so
* `vendor.region` and `supplier.region` both filtered the deal's OWN `region`
* on both strategies (and through the gate, which read the same lookup), and a
* flat key over a base column (`vendor_region` over `region`) answered
* `vendor.region` the same way. Now a dotted member names a declared key only
* verbatim, behind the cube's own qualifier (`<dataset>.region`,
* `<object>.region`), or through a flat key over the same relationship path;
* anything else is a relationship path, which the include gate judges or the
* traversal tier joins.
*/
describe('[#31842] a dotted filter member whose tail names a declared member', () => {
const DEAL = 'os31842_deal';
const VENDOR = 'os31842_vendor';
const SUPPLIER = 'os31842_supplier';
const dealShape = {
label: 'Deals',
object: DEAL,
dimensions: [{ name: 'region', field: 'region', type: 'string' }],
measures: [{ name: 'total', aggregate: 'sum', field: 'amount' }],
};
/** Declares no relationship. */
const NO_INCLUDE = DatasetSchema.parse({ name: 'os31842_deals', ...dealShape });
/** Declares both relationships. */
const INCLUDES = DatasetSchema.parse({ name: 'os31842_deals_inc', include: ['vendor', 'supplier'], ...dealShape });
/** A flat key over a BASE column: it names the deal's own `region`, never a related one. */
const FLAT_BASE = DatasetSchema.parse({
name: 'os31842_deals_flat',
...dealShape,
dimensions: [{ name: 'vendor_region', field: 'region', type: 'string' }],
});
/** A flat key over the RELATED column: it names `supplier.region`, so that spelling still answers it. */
const FLAT_RELATED = DatasetSchema.parse({
name: 'os31842_deals_flat_rel',
include: ['supplier'],
...dealShape,
dimensions: [...dealShape.dimensions, { name: 'supplier_region', field: 'supplier.region', type: 'string' }],
});
/** A hand-authored cube over the deal, named for the object. */
const CUBE = {
name: DEAL,
sql: DEAL,
dimensions: { region: { sql: 'region', type: 'string' } },
measures: { count: { type: 'count', sql: '*' } },
};

let engine: ObjectQL;
const services: Partial<Record<'native' | 'objectql', AnalyticsService>> = {};
const LIVE = ['native', 'objectql'] as const;

const filterDataset = (face: (typeof LIVE)[number], dataset: typeof NO_INCLUDE, runtimeFilter: Record<string, unknown>, dimension = 'region') =>
services[face]!.queryDataset(dataset, { dimensions: [dimension], measures: ['total'], runtimeFilter } as never);
const filterCube = (face: (typeof LIVE)[number], where: Record<string, unknown>) =>
services[face]!.query({ cube: DEAL, dimensions: [`${DEAL}.region`], measures: [`${DEAL}.count`], where } as never);
const rowsOf = (rows: unknown) =>
(rows as Array<Record<string, unknown>>)
.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, typeof v === 'string' ? v : Number(v)])))
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));

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: VENDOR, label: 'Vendor', fields: { name: { name: 'name', type: 'text' } } } as never);
engine.registry.registerObject({
name: SUPPLIER,
label: 'Supplier',
fields: { name: { name: 'name', type: 'text' }, region: { name: 'region', type: 'text' } },
} as never);
engine.registry.registerObject({
name: DEAL,
label: 'Deal',
fields: {
region: { name: 'region', type: 'text' },
amount: { name: 'amount', type: 'number' },
vendor: { name: 'vendor', type: 'lookup', reference: VENDOR },
supplier: { name: 'supplier', type: 'lookup', reference: SUPPLIER },
},
} as never);
await engine.syncSchemas();
await installDefaultOrganization(engine as never);
await engine.insert(VENDOR, { id: 'v1', name: 'Initech' } as never);
await engine.insert(SUPPLIER, { id: 's1', name: 'Hooli', region: 'apac' } as never);
await engine.insert(SUPPLIER, { id: 's2', name: 'Umbrella', region: 'emea' } as never);
// The deal's OWN region and its supplier's region disagree on every row,
// so which column a filter read shows in the answer.
for (const row of [
{ id: 'd1', region: 'emea', amount: 1, vendor: 'v1', supplier: 's1' },
{ id: 'd2', region: 'emea', amount: 10, vendor: 'v1', supplier: 's1' },
{ id: 'd3', region: 'amer', amount: 100, vendor: 'v1', supplier: 's2' },
]) await engine.insert(DEAL, row as never);

for (const [face, caps] of [
['native', undefined],
['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })],
] as const) {
const registered: Record<string, unknown> = {};
const provided: Record<string, unknown> = { data: engine };
await new AnalyticsServicePlugin({ cubes: [CUBE], ...(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("refuses 'vendor.region' through no include on both strategies, instead of filtering the deal's own region", async () => {
for (const face of LIVE) {
const err = await refusalOf(filterDataset(face, NO_INCLUDE, { 'vendor.region': 'emea' }));
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
expect(err.status).toBe(400);
expect(err.param).toBe('where');
expect(err.member).toBe('vendor.region');
expect(err.message).toContain("traverses relationship path 'vendor'");
}
});

it("refuses 'vendor.region' through a declared include to an object with no 'region' on both strategies", async () => {
for (const face of LIVE) {
const err = await refusalOf(filterDataset(face, INCLUDES, { 'vendor.region': 'emea' }));
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
expect(err.status).toBe(400);
expect(err.param).toBe('where');
expect(err.member).toBe('vendor.region');
}
});

it("filters the RELATED 'supplier.region' through a declared include, never the deal's own region", async () => {
// Native joins the supplier: d1 and d2 point at the APAC supplier.
const native = await filterDataset('native', INCLUDES, { 'supplier.region': 'apac' });
expect(rowsOf(native.rows)).toEqual([{ region: 'emea', total: 11 }]);
// The engine-aggregate face cannot join, and says so for this member as it
// does for every related filter.
const err = await refusalOf(filterDataset('objectql', INCLUDES, { 'supplier.region': 'apac' }));
expect(err.code, err.message).toBe('INVALID_FIELD');
expect(err.status).toBe(400);
expect(err.param).toBe('where');
expect(err.member).toBe('supplier.region');
});

it("CONTROL: '<dataset>.region' and '<object>.region' still filter the deal's own region on both strategies", async () => {
for (const face of LIVE) {
for (const member of [`${NO_INCLUDE.name}.region`, `${DEAL}.region`]) {
const result = await filterDataset(face, NO_INCLUDE, { [member]: 'emea' });
expect(rowsOf(result.rows), `${face} ${member}`).toEqual([{ region: 'emea', total: 11 }]);
}
}
});

it("refuses 'vendor.region' beside a flat key 'vendor_region' over the BASE column on both strategies", async () => {
for (const face of LIVE) {
const err = await refusalOf(filterDataset(face, FLAT_BASE, { 'vendor.region': 'emea' }, 'vendor_region'));
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
expect(err.status).toBe(400);
expect(err.member).toBe('vendor.region');
expect(err.message).toContain("traverses relationship path 'vendor'");
}
});

it("a flat key 'supplier_region' over the related 'supplier.region' answers that spelling with the related column", async () => {
const result = await filterDataset('native', FLAT_RELATED, { 'supplier.region': 'apac' });
expect(rowsOf(result.rows)).toEqual([{ region: 'emea', total: 11 }]);
});

it("a hand-authored cube: 'supplier.region' joins the supplier on the native strategy, and the engine face refuses 'vendor.region'", async () => {
const native = await filterCube('native', { 'supplier.region': 'apac' });
expect(rowsOf(native.rows)).toEqual([{ [`${DEAL}.region`]: 'emea', [`${DEAL}.count`]: 2 }]);
const err = await refusalOf(filterCube('objectql', { 'vendor.region': 'emea' }));
expect(err.code, err.message).toBe('INVALID_FIELD');
expect(err.status).toBe(400);
expect(err.param).toBe('where');
expect(err.member).toBe('vendor.region');
});

it("CONTROL: a hand-authored cube still filters '<cube>.region' as the deal's own region on both strategies", async () => {
for (const face of LIVE) {
const result = await filterCube(face, { [`${DEAL}.region`]: 'emea' });
expect(rowsOf(result.rows), face).toEqual([{ [`${DEAL}.region`]: 'emea', [`${DEAL}.count`]: 2 }]);
}
});
});
16 changes: 7 additions & 9 deletions packages/services/service-analytics/src/analytics-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import { AMOUNT_AGGREGATES, assertRecordCurrencyAggregatesGrouped } from './cube
import type { AnalyticsStrategy, AnalyticsDriverCapabilities, StrategyContext, DatasetScopedStrategyContext, DatasetScope, DurationMeasureSpec, ReadScopeFilterJudge } from './strategies/types.js';
import { NativeSQLStrategy } from './strategies/native-sql-strategy.js';
import { ObjectQLStrategy, aggregateGroupKeys, aggregateObjectOf, resolveCubeFieldName } from './strategies/objectql-strategy.js';
import { declaredCubeMemberKey } from './cube-member-key.js';
// [#5669] The `where` source-field gate reads the filter tree through the SAME
// pair the strategies compile it with, so "the field the gate saw" and "the
// column that reached SQL" cannot be two different things.
Expand Down Expand Up @@ -402,16 +403,13 @@ function declaredMemberEntry(
];
// `key` is spread LAST in every arm: it is the bag key this member RESOLVED
// to, and a `key` property on the cube entry itself must not shadow it.
// [#31842] Which key a spelling names is `declaredCubeMemberKey`'s rule, the
// one both strategies' `lookupMember` read: a dotted member names a declared
// key only verbatim, behind the cube's own qualifier, or through a flat key
// over the same relationship path — never by its tail alone.
for (const bag of bags) {
if (bag[member]) return { ...bag[member], key: member };
if (member.includes('.')) {
const [first, ...rest] = member.split('.');
const tail = rest.join('.');
if (first === cube.name && bag[tail]) return { ...bag[tail], key: tail };
if (bag[tail]) return { ...bag[tail], key: tail };
const flat = member.replace(/\./g, '_');
if (bag[flat]) return { ...bag[flat], key: flat };
}
const key = declaredCubeMemberKey(cube, bag, member);
if (key !== undefined) return { ...bag[key], key };
}
return undefined;
}
Expand Down
64 changes: 64 additions & 0 deletions packages/services/service-analytics/src/cube-member-key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#31842] The ONE rule for "which declared cube member does this spelling
* name?", for every reader in this package that resolves one: the door's gates
* (`declaredMemberEntry`, `analytics-service.ts`), both strategies'
* `lookupMember`, and the structured-JSON door's measure lookup. So the member
* a gate judges and the member a strategy compiles are the same key by
* construction.
*
* A spelling names the declared key:
*
* 1. **verbatim** — the key itself, a declared dotted key included;
* 2. **behind the cube's own qualifier** — `CUBE.region` or `OBJECT.region`,
* where `CUBE` is the cube's name and `OBJECT` the bare object its `sql`
* reads (a compiled dataset is named for the dataset, and both spellings
* have always named its base fields);
* 3. **through its flattened key** — `vendor.region` → a declared
* `vendor_region` — ONLY when that key's `sql` is the same relationship
* path, i.e. the flat key names the related field. A flat key over a base
* column (a dataset dimension `vendor_region` over `region`) names a base
* field, and a relationship path must not answer it.
*
* Anything else dotted names no declared key: it is a relationship path, which
* the dimension tier hands to the join machinery and the door's include gate
* judges. Before this rule, `vendor.region` resolved to a declared `region` by
* its tail alone, whatever the first segment was, so a filter on a related
* field silently filtered the base field of the same name.
*/

import type { Cube } from '@objectstack/spec/data';

/** A cube's member bag, read only for its entries' `sql`. */
type MemberBag = Readonly<Record<string, { sql?: unknown } | undefined>> | undefined;

/** Whether `segment` is the cube's own qualifier: its name, or the bare object its `sql` reads. */
function isOwnQualifier(cube: Cube, segment: string): boolean {
if (segment === cube.name) return true;
return typeof cube.sql === 'string' && cube.sql.trim() === segment;
}

/** The relationship path an entry's `sql` reads, with the engine's `$` field sigil dropped. */
function pathOf(entry: { sql?: unknown }): string | undefined {
return typeof entry.sql === 'string' ? entry.sql.trim().replace(/^\$/, '') : undefined;
}

/**
* The key of `bag` that `member` names under the rule above, or `undefined`
* when it names none. ⛔ No synthetic tier here: what an undeclared spelling
* becomes is each caller's business, and only the dimension resolution turns
* a dotted one into a relationship path.
*/
export function declaredCubeMemberKey(cube: Cube, bag: MemberBag, member: string): string | undefined {
if (!bag) return undefined;
if (bag[member]) return member;
const dot = member.indexOf('.');
if (dot < 0) return undefined;
const tail = member.slice(dot + 1);
if (isOwnQualifier(cube, member.slice(0, dot)) && bag[tail]) return tail;
const flat = member.replace(/\./g, '_');
const flatEntry = bag[flat];
if (flatEntry && pathOf(flatEntry) === member) return flat;
return undefined;
}
Loading
Loading