Skip to content

Commit f159aaa

Browse files
fix(service-analytics)!: a dotted member like vendor.region no longer filters the base field of the same name (#31878)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9EMQuDus5tHtakmfkN4PXrg)_ Fixes #31842 Clause-②: no (narrowing) Metadata-protocol: none ## 维护者速读 - 改了什么:分析查询里带点的成员(如筛选 `vendor.region`)只在第一段是本数据集/本对象名时才按本对象字段解析;否则一律按关联路径处理(未声明 include 就明确拒绝,已声明就筛关联对象的字段)。校验门和两种执行策略共用同一条规则。 - 为什么改:以前只要最后一段和本对象某个字段同名,`vendor.region` 就会悄悄按本对象自己的 region 筛选,图表数字是错的,且没有任何提示。 - 风险与回滚:属于收窄:原来"答错"的写法现在会被拒(INVALID_FIELD/400)或改为筛关联字段;一方代码里没有这种写法。回滚即 revert 本 PR。 - 先看:`packages/services/service-analytics/src/cube-member-key.ts`(唯一规则)、`analytics-service.ts` 的 `declaredMemberEntry`、两个策略的 `lookupMember`。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/dotted-dimension-unbacked-join-parity.test.ts`,预期 17 个全绿(其中 8 个是本卡新增)。 - 需要你做的:无,席位落地。 ## What changes One rule for which declared cube member a spelling names, in a new module `cube-member-key.ts` (`declaredCubeMemberKey`, not exported from the package root), read by every resolver that used to carry its own copy: - the door's gates: `declaredMemberEntry` in `analytics-service.ts` (the where gate, the dimension gate, the include gate, the field-read admission, the preview column map); - `NativeSQLStrategy.lookupMember` and `ObjectQLStrategy`'s `lookupCubeMember`; - the structured-JSON door's `measureEntryOf` (the same lookup for measures; see Acceptance notes). A spelling names a declared key verbatim (a declared dotted key included), behind the cube's own qualifier (CUBE.region, or OBJECT.region where OBJECT is the bare object the cube's `sql` reads), or through an underscore-flattened key ONLY when that key's own `sql` is the same relationship path. The bare-tail arm (`if (bag[tail]) return bag[tail]`), which made the `first === cube.name` arm above it dead, is gone from all four copies. Any other dotted member is a relationship path: the dimension tier hands it to the join machinery, and on a compiled dataset the existing include gate (or the existing related-column gate) answers. No error code, envelope or export is added. The three undeclared fallbacks that read `member.split('.')[1]` as a base column (`resolveFieldSql`, `resolveDimensionSql`, `resolveCubeFieldName`) and the `split('.').slice(1)` one in `resolveStorageTarget` now return the member itself. Measured: they were unreachable for a dotted member, because the dimension lookup answers every dotted member first (a declared key, or the synthetic traversal), so the only path into them was a bare member; `resolveCubeFieldName`'s could be reached dotted only with kind `measure`, which no caller passes. Seat ruling 3 (flat keys): nothing in the package MINTS a flat key. `inferCubeFromQuery` mints a dotted member verbatim, and the dataset compiler keys a dimension by its authored `name`. A flat key is authored only; `skills/objectstack-ui/rules/dashboards.md` teaches `account_industry` with `sql: 'account.industry'`, which names the related field and still answers `account.industry`. A flat key over a base column (a dataset dimension `vendor_region` over `region`) no longer answers `vendor.region`. ## Tests `dotted-dimension-unbacked-join-parity.test.ts` (the existing real-SQLite harness for dotted members on both strategies) gains one top-level `describe` with its own fixture: a deal with its own `region`, a `vendor` lookup to an object with no `region`, and a `supplier` lookup to one that has it (the supplier's region disagrees with the deal's on every row, so the answer shows which column was read). Eight pins: 1. `vendor.region` through no include: refused `INVALID_FIELD` / 400, param `where`, on both strategies. RED on main (served the base filter). 2. `vendor.region` through a declared include to an object without `region`: refused `INVALID_FIELD` / 400 on both. RED on main. 3. `supplier.region` through a declared include: native filters the joined supplier column; the engine-aggregate face refuses it as it refuses every related filter. RED on main (both served `[]`, the base filter). 4. CONTROL: DATASET.region and OBJECT.region still filter the base column on both. Green on main. 5. `vendor.region` beside a flat `vendor_region` over the BASE column: refused on both. RED on main. 6. A flat `supplier_region` over `supplier.region` answers that spelling with the related column. RED on main (the bare-tail arm caught it first). 7. A hand-authored cube (`query`): native joins the supplier for `supplier.region`; the engine face refuses `vendor.region`. RED on main. 8. CONTROL: a hand-authored cube still filters CUBE.region as the base column on both. Green on main. No existing test was edited. <details><summary>Red on main, then green</summary> Sources restored from `origin/main` `31ae944b` (tree only), the new pins run, then restored from `HEAD` (`git diff HEAD` empty): ``` × refuses 'vendor.region' through no include on both strategies, instead of filtering the deal's own region × refuses 'vendor.region' through a declared include to an object with no 'region' on both strategies × filters the RELATED 'supplier.region' through a declared include, never the deal's own region × refuses 'vendor.region' beside a flat key 'vendor_region' over the BASE column on both strategies × a flat key 'supplier_region' over the related 'supplier.region' answers ... (named a CONTROL in that run; renamed after it went red) × a hand-authored cube: 'supplier.region' joins the supplier on the native strategy, and the engine face refuses 'vendor.region' Tests 6 failed | 11 passed (17) ``` On the fix: `Tests 17 passed (17)`. </details> <details><summary>Ablations (scripts/ablation-replace.mjs, anchor hit 1 to 0 and blob moved each time; restored, git diff HEAD empty)</summary> | ablation | file | result | |:--|:--|:--| | A1 drop the first-segment guard (any first segment names the tail) | `cube-member-key.ts` | 5 failed / 12 passed | | A2 restore the bare-tail arm in `NativeSQLStrategy.lookupMember` only | `native-sql-strategy.ts` | 2 failed / 15 passed (pins 3 and 7) | | A3 restore the bare-tail arm in `lookupCubeMember` only | `objectql-strategy.ts` | 2 failed / 15 passed (pins 3 and 7) | | A4 let any flat key answer a dotted path | `cube-member-key.ts` | 1 failed / 16 passed (pin 5) | The tests import the sources (`../plugin.js`), not a `dist/`, so no build leg applies. </details> ## Acceptance notes - **Measured on main (seat ruling 1).** `origin/main` `31ae944b`, real `SqlDriver` (SQLite), the engine's `execute` / `aggregate` recorded. A dataset over a deal with its own `region` answered `runtimeFilter: { 'vendor.region': 'emea' }` with `[{ region: 'emea', total: 11 }]` on both strategies: native ran `... WHERE region = ? ...`, the engine face handed `where: { region: 'emea' }`, with and without `vendor` in the include. `supplier.region: 'apac'` (supplier HAS `region`) served `[]` on both, from the same base filter. A flat `vendor_region` over `region` answered `vendor.region` the same way. A hand-authored cube through `query` did too. An undeclared dotted member with no same-named member (`supplier.name`) already reached the JOIN machinery on main (native LEFT JOIN, include gate refusal when unbacked). - **Clause-② (seat ruling 5).** `no (narrowing)`: `vendor.region` is now refused where the related object lacks the column or the path is undeclared, so not every such input resolves to a related field. BREAKING banner, ADR-0087 disposition `not-required (no-migration-prescription)`, and the full dogfood battery on the final head below. First-party count of a dotted analytics member whose tail names a base member: 0 (grepped `content/`, `examples/`, `skills/`, `packages/qa/dogfood`; the three dotted `where` hits are ObjectQL data-query docs, not analytics). - **OBJECT qualifier kept beside CUBE.** Seat ruling 2 names only the cube's own name. A compiled dataset is named for the dataset, and OBJECT.region has always named its base field: the existing #28258 control and the #28691 preview map pin it. The rule treats the bare object of the cube's `sql` as an own qualifier too. Raised as an open question in the report. - **Changeset remedy.** The delta asked for a FROM / TO line. The ADR-0087 gate reads a FROM-TO label as a migration prescription and refuses it beside `no-migration-prescription`, so the remedy is stated in prose (spell it CUBE.region or region; a stored member is not rewritten, because only its author knows which field it meant). - **Files beyond the claim's surface.** `src/cube-member-key.ts` (new module, the one rule, not exported from the package root) and `src/structured-json-dimension-door.ts` (`measureEntryOf` carried the same bare-tail copy for measures; same defect class, mechanical, no new gate family). - **Out of scope, reported to the seat.** (a) A CUBE-qualified MEASURE in a dataset `where` (`DATASET.total`) is read by the gate as the declared measure but compiled by both strategies as a join through a hop named for the dataset (native `DATASET_INVALID` "join ... is not backed", engine face the cross-object refusal), while bare `total` serves. Pre-existing on main, unchanged here. (b) On a hand-authored cube (no include gate), the native strategy answers `DATABASE_ERROR` / 500 for a related column the related object lacks (`vendor.nope` on main; now `vendor.region` lands there too, instead of being served from the wrong column). The dataset path refuses the same input `INVALID_FIELD` / 400. ## Verification Head `93e3a44a` (merge of `origin/main` `ef194d79`). <details><summary>Local runs</summary> - `pnpm --filter @objectstack/service-analytics test` on `93e3a44a`: Test Files 214 passed (214), Tests 5148 passed, 332 skipped. - `pnpm --filter @objectstack/service-analytics typecheck` on `93e3a44a` (closure built with DTS): 0 errors. - `eslint packages/services/service-analytics --no-inline-config`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands`: 70 families, all run with exit 0 recorded; `--ran` reconciliation: 70 derived, 70 run, 0 NOT-MEASURED (derived zero). After the merge the derivation is unchanged and the diff-sensitive families (adr-0087 registration, changeset no-major, empty changeset, closing-keyword parity, issue citations, doc-authoring, nul-bytes, cross-package test inputs, test-source alias, affected docs) were re-run: all exit 0. - Full dogfood battery: `93e3a44a` · os-verify-lock VERDICT command-exit 0 · Test Files 441 passed, 3 skipped (444) · Tests 3662 passed, 42 skipped (3704) · no failures. (Also green on the pre-merge head `21e229dc`, same counts.) </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmP7cP3t3ncc39aFhhx)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3684d18 commit f159aaa

7 files changed

Lines changed: 326 additions & 65 deletions

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)!: 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
6+
7+
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.
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 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. -->
11+
12+
**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.
13+
14+
- **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`.
15+
- **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`.
16+
- **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.
17+
18+
**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.

‎packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts‎

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,3 +241,199 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do
241241
expect(err.member).toBe('account.name');
242242
});
243243
});
244+
245+
/**
246+
* [#31842] A dotted FILTER member whose tail names a declared member, on both
247+
* live strategies, through a compiled dataset (`queryDataset`) and a
248+
* hand-authored cube (`query`), on real SQLite.
249+
*
250+
* The deal declares its own `region`; `vendor` is a lookup to an object with
251+
* NO `region`, `supplier` a lookup to one that has it. Before, a dotted member
252+
* named a declared key by its tail alone, whatever its first segment, so
253+
* `vendor.region` and `supplier.region` both filtered the deal's OWN `region`
254+
* on both strategies (and through the gate, which read the same lookup), and a
255+
* flat key over a base column (`vendor_region` over `region`) answered
256+
* `vendor.region` the same way. Now a dotted member names a declared key only
257+
* verbatim, behind the cube's own qualifier (`<dataset>.region`,
258+
* `<object>.region`), or through a flat key over the same relationship path;
259+
* anything else is a relationship path, which the include gate judges or the
260+
* traversal tier joins.
261+
*/
262+
describe('[#31842] a dotted filter member whose tail names a declared member', () => {
263+
const DEAL = 'os31842_deal';
264+
const VENDOR = 'os31842_vendor';
265+
const SUPPLIER = 'os31842_supplier';
266+
const dealShape = {
267+
label: 'Deals',
268+
object: DEAL,
269+
dimensions: [{ name: 'region', field: 'region', type: 'string' }],
270+
measures: [{ name: 'total', aggregate: 'sum', field: 'amount' }],
271+
};
272+
/** Declares no relationship. */
273+
const NO_INCLUDE = DatasetSchema.parse({ name: 'os31842_deals', ...dealShape });
274+
/** Declares both relationships. */
275+
const INCLUDES = DatasetSchema.parse({ name: 'os31842_deals_inc', include: ['vendor', 'supplier'], ...dealShape });
276+
/** A flat key over a BASE column: it names the deal's own `region`, never a related one. */
277+
const FLAT_BASE = DatasetSchema.parse({
278+
name: 'os31842_deals_flat',
279+
...dealShape,
280+
dimensions: [{ name: 'vendor_region', field: 'region', type: 'string' }],
281+
});
282+
/** A flat key over the RELATED column: it names `supplier.region`, so that spelling still answers it. */
283+
const FLAT_RELATED = DatasetSchema.parse({
284+
name: 'os31842_deals_flat_rel',
285+
include: ['supplier'],
286+
...dealShape,
287+
dimensions: [...dealShape.dimensions, { name: 'supplier_region', field: 'supplier.region', type: 'string' }],
288+
});
289+
/** A hand-authored cube over the deal, named for the object. */
290+
const CUBE = {
291+
name: DEAL,
292+
sql: DEAL,
293+
dimensions: { region: { sql: 'region', type: 'string' } },
294+
measures: { count: { type: 'count', sql: '*' } },
295+
};
296+
297+
let engine: ObjectQL;
298+
const services: Partial<Record<'native' | 'objectql', AnalyticsService>> = {};
299+
const LIVE = ['native', 'objectql'] as const;
300+
301+
const filterDataset = (face: (typeof LIVE)[number], dataset: typeof NO_INCLUDE, runtimeFilter: Record<string, unknown>, dimension = 'region') =>
302+
services[face]!.queryDataset(dataset, { dimensions: [dimension], measures: ['total'], runtimeFilter } as never);
303+
const filterCube = (face: (typeof LIVE)[number], where: Record<string, unknown>) =>
304+
services[face]!.query({ cube: DEAL, dimensions: [`${DEAL}.region`], measures: [`${DEAL}.count`], where } as never);
305+
const rowsOf = (rows: unknown) =>
306+
(rows as Array<Record<string, unknown>>)
307+
.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, typeof v === 'string' ? v : Number(v)])))
308+
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
309+
310+
beforeAll(async () => {
311+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
312+
engine = new ObjectQL({ logger: quiet } as never);
313+
engine.registerDriver(driver as never, true);
314+
await engine.init();
315+
engine.registry.registerObject({ name: VENDOR, label: 'Vendor', fields: { name: { name: 'name', type: 'text' } } } as never);
316+
engine.registry.registerObject({
317+
name: SUPPLIER,
318+
label: 'Supplier',
319+
fields: { name: { name: 'name', type: 'text' }, region: { name: 'region', type: 'text' } },
320+
} as never);
321+
engine.registry.registerObject({
322+
name: DEAL,
323+
label: 'Deal',
324+
fields: {
325+
region: { name: 'region', type: 'text' },
326+
amount: { name: 'amount', type: 'number' },
327+
vendor: { name: 'vendor', type: 'lookup', reference: VENDOR },
328+
supplier: { name: 'supplier', type: 'lookup', reference: SUPPLIER },
329+
},
330+
} as never);
331+
await engine.syncSchemas();
332+
await installDefaultOrganization(engine as never);
333+
await engine.insert(VENDOR, { id: 'v1', name: 'Initech' } as never);
334+
await engine.insert(SUPPLIER, { id: 's1', name: 'Hooli', region: 'apac' } as never);
335+
await engine.insert(SUPPLIER, { id: 's2', name: 'Umbrella', region: 'emea' } as never);
336+
// The deal's OWN region and its supplier's region disagree on every row,
337+
// so which column a filter read shows in the answer.
338+
for (const row of [
339+
{ id: 'd1', region: 'emea', amount: 1, vendor: 'v1', supplier: 's1' },
340+
{ id: 'd2', region: 'emea', amount: 10, vendor: 'v1', supplier: 's1' },
341+
{ id: 'd3', region: 'amer', amount: 100, vendor: 'v1', supplier: 's2' },
342+
]) await engine.insert(DEAL, row as never);
343+
344+
for (const [face, caps] of [
345+
['native', undefined],
346+
['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })],
347+
] as const) {
348+
const registered: Record<string, unknown> = {};
349+
const provided: Record<string, unknown> = { data: engine };
350+
await new AnalyticsServicePlugin({ cubes: [CUBE], ...(caps ? { queryCapabilities: caps } : {}) } as never).init({
351+
getService: (name: string) => provided[name] ?? registered[name],
352+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
353+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
354+
hook: () => {},
355+
logger: quiet,
356+
} as never);
357+
services[face] = registered.analytics as AnalyticsService;
358+
}
359+
});
360+
361+
afterAll(async () => {
362+
try { await engine?.destroy(); } catch { /* noop */ }
363+
});
364+
365+
it("refuses 'vendor.region' through no include on both strategies, instead of filtering the deal's own region", async () => {
366+
for (const face of LIVE) {
367+
const err = await refusalOf(filterDataset(face, NO_INCLUDE, { 'vendor.region': 'emea' }));
368+
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
369+
expect(err.status).toBe(400);
370+
expect(err.param).toBe('where');
371+
expect(err.member).toBe('vendor.region');
372+
expect(err.message).toContain("traverses relationship path 'vendor'");
373+
}
374+
});
375+
376+
it("refuses 'vendor.region' through a declared include to an object with no 'region' on both strategies", async () => {
377+
for (const face of LIVE) {
378+
const err = await refusalOf(filterDataset(face, INCLUDES, { 'vendor.region': 'emea' }));
379+
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
380+
expect(err.status).toBe(400);
381+
expect(err.param).toBe('where');
382+
expect(err.member).toBe('vendor.region');
383+
}
384+
});
385+
386+
it("filters the RELATED 'supplier.region' through a declared include, never the deal's own region", async () => {
387+
// Native joins the supplier: d1 and d2 point at the APAC supplier.
388+
const native = await filterDataset('native', INCLUDES, { 'supplier.region': 'apac' });
389+
expect(rowsOf(native.rows)).toEqual([{ region: 'emea', total: 11 }]);
390+
// The engine-aggregate face cannot join, and says so for this member as it
391+
// does for every related filter.
392+
const err = await refusalOf(filterDataset('objectql', INCLUDES, { 'supplier.region': 'apac' }));
393+
expect(err.code, err.message).toBe('INVALID_FIELD');
394+
expect(err.status).toBe(400);
395+
expect(err.param).toBe('where');
396+
expect(err.member).toBe('supplier.region');
397+
});
398+
399+
it("CONTROL: '<dataset>.region' and '<object>.region' still filter the deal's own region on both strategies", async () => {
400+
for (const face of LIVE) {
401+
for (const member of [`${NO_INCLUDE.name}.region`, `${DEAL}.region`]) {
402+
const result = await filterDataset(face, NO_INCLUDE, { [member]: 'emea' });
403+
expect(rowsOf(result.rows), `${face} ${member}`).toEqual([{ region: 'emea', total: 11 }]);
404+
}
405+
}
406+
});
407+
408+
it("refuses 'vendor.region' beside a flat key 'vendor_region' over the BASE column on both strategies", async () => {
409+
for (const face of LIVE) {
410+
const err = await refusalOf(filterDataset(face, FLAT_BASE, { 'vendor.region': 'emea' }, 'vendor_region'));
411+
expect(err.code, `${face}: ${err.message}`).toBe('INVALID_FIELD');
412+
expect(err.status).toBe(400);
413+
expect(err.member).toBe('vendor.region');
414+
expect(err.message).toContain("traverses relationship path 'vendor'");
415+
}
416+
});
417+
418+
it("a flat key 'supplier_region' over the related 'supplier.region' answers that spelling with the related column", async () => {
419+
const result = await filterDataset('native', FLAT_RELATED, { 'supplier.region': 'apac' });
420+
expect(rowsOf(result.rows)).toEqual([{ region: 'emea', total: 11 }]);
421+
});
422+
423+
it("a hand-authored cube: 'supplier.region' joins the supplier on the native strategy, and the engine face refuses 'vendor.region'", async () => {
424+
const native = await filterCube('native', { 'supplier.region': 'apac' });
425+
expect(rowsOf(native.rows)).toEqual([{ [`${DEAL}.region`]: 'emea', [`${DEAL}.count`]: 2 }]);
426+
const err = await refusalOf(filterCube('objectql', { 'vendor.region': 'emea' }));
427+
expect(err.code, err.message).toBe('INVALID_FIELD');
428+
expect(err.status).toBe(400);
429+
expect(err.param).toBe('where');
430+
expect(err.member).toBe('vendor.region');
431+
});
432+
433+
it("CONTROL: a hand-authored cube still filters '<cube>.region' as the deal's own region on both strategies", async () => {
434+
for (const face of LIVE) {
435+
const result = await filterCube(face, { [`${DEAL}.region`]: 'emea' });
436+
expect(rowsOf(result.rows), face).toEqual([{ [`${DEAL}.region`]: 'emea', [`${DEAL}.count`]: 2 }]);
437+
}
438+
});
439+
});

‎packages/services/service-analytics/src/analytics-service.ts‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ import { AMOUNT_AGGREGATES, assertRecordCurrencyAggregatesGrouped } from './cube
9393
import type { AnalyticsStrategy, AnalyticsDriverCapabilities, StrategyContext, DatasetScopedStrategyContext, DatasetScope, DurationMeasureSpec, ReadScopeFilterJudge } from './strategies/types.js';
9494
import { NativeSQLStrategy } from './strategies/native-sql-strategy.js';
9595
import { ObjectQLStrategy, aggregateGroupKeys, aggregateObjectOf, resolveCubeFieldName } from './strategies/objectql-strategy.js';
96+
import { declaredCubeMemberKey } from './cube-member-key.js';
9697
// [#5669] The `where` source-field gate reads the filter tree through the SAME
9798
// pair the strategies compile it with, so "the field the gate saw" and "the
9899
// column that reached SQL" cannot be two different things.
@@ -402,16 +403,13 @@ function declaredMemberEntry(
402403
];
403404
// `key` is spread LAST in every arm: it is the bag key this member RESOLVED
404405
// to, and a `key` property on the cube entry itself must not shadow it.
406+
// [#31842] Which key a spelling names is `declaredCubeMemberKey`'s rule, the
407+
// one both strategies' `lookupMember` read: a dotted member names a declared
408+
// key only verbatim, behind the cube's own qualifier, or through a flat key
409+
// over the same relationship path — never by its tail alone.
405410
for (const bag of bags) {
406-
if (bag[member]) return { ...bag[member], key: member };
407-
if (member.includes('.')) {
408-
const [first, ...rest] = member.split('.');
409-
const tail = rest.join('.');
410-
if (first === cube.name && bag[tail]) return { ...bag[tail], key: tail };
411-
if (bag[tail]) return { ...bag[tail], key: tail };
412-
const flat = member.replace(/\./g, '_');
413-
if (bag[flat]) return { ...bag[flat], key: flat };
414-
}
411+
const key = declaredCubeMemberKey(cube, bag, member);
412+
if (key !== undefined) return { ...bag[key], key };
415413
}
416414
return undefined;
417415
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#31842] The ONE rule for "which declared cube member does this spelling
5+
* name?", for every reader in this package that resolves one: the door's gates
6+
* (`declaredMemberEntry`, `analytics-service.ts`), both strategies'
7+
* `lookupMember`, and the structured-JSON door's measure lookup. So the member
8+
* a gate judges and the member a strategy compiles are the same key by
9+
* construction.
10+
*
11+
* A spelling names the declared key:
12+
*
13+
* 1. **verbatim** — the key itself, a declared dotted key included;
14+
* 2. **behind the cube's own qualifier** — `CUBE.region` or `OBJECT.region`,
15+
* where `CUBE` is the cube's name and `OBJECT` the bare object its `sql`
16+
* reads (a compiled dataset is named for the dataset, and both spellings
17+
* have always named its base fields);
18+
* 3. **through its flattened key** — `vendor.region` → a declared
19+
* `vendor_region` — ONLY when that key's `sql` is the same relationship
20+
* path, i.e. the flat key names the related field. A flat key over a base
21+
* column (a dataset dimension `vendor_region` over `region`) names a base
22+
* field, and a relationship path must not answer it.
23+
*
24+
* Anything else dotted names no declared key: it is a relationship path, which
25+
* the dimension tier hands to the join machinery and the door's include gate
26+
* judges. Before this rule, `vendor.region` resolved to a declared `region` by
27+
* its tail alone, whatever the first segment was, so a filter on a related
28+
* field silently filtered the base field of the same name.
29+
*/
30+
31+
import type { Cube } from '@objectstack/spec/data';
32+
33+
/** A cube's member bag, read only for its entries' `sql`. */
34+
type MemberBag = Readonly<Record<string, { sql?: unknown } | undefined>> | undefined;
35+
36+
/** Whether `segment` is the cube's own qualifier: its name, or the bare object its `sql` reads. */
37+
function isOwnQualifier(cube: Cube, segment: string): boolean {
38+
if (segment === cube.name) return true;
39+
return typeof cube.sql === 'string' && cube.sql.trim() === segment;
40+
}
41+
42+
/** The relationship path an entry's `sql` reads, with the engine's `$` field sigil dropped. */
43+
function pathOf(entry: { sql?: unknown }): string | undefined {
44+
return typeof entry.sql === 'string' ? entry.sql.trim().replace(/^\$/, '') : undefined;
45+
}
46+
47+
/**
48+
* The key of `bag` that `member` names under the rule above, or `undefined`
49+
* when it names none. ⛔ No synthetic tier here: what an undeclared spelling
50+
* becomes is each caller's business, and only the dimension resolution turns
51+
* a dotted one into a relationship path.
52+
*/
53+
export function declaredCubeMemberKey(cube: Cube, bag: MemberBag, member: string): string | undefined {
54+
if (!bag) return undefined;
55+
if (bag[member]) return member;
56+
const dot = member.indexOf('.');
57+
if (dot < 0) return undefined;
58+
const tail = member.slice(dot + 1);
59+
if (isOwnQualifier(cube, member.slice(0, dot)) && bag[tail]) return tail;
60+
const flat = member.replace(/\./g, '_');
61+
const flatEntry = bag[flat];
62+
if (flatEntry && pathOf(flatEntry) === member) return flat;
63+
return undefined;
64+
}

0 commit comments

Comments
 (0)