Skip to content

Commit 8882857

Browse files
fix(service-analytics): a live dataset query serves a derived measure built on another derived measure, and refuses a derived cycle with its path (#28169)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DQcUJMSg3N7pTvoXMtHAZbF)_ domain:server#4 · os-elon-musk · session_016WV4cyJ2FnmRRSXEUtT6G1 Fixes #28127 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:数据集查询里,派生度量的 `of` 引用另一个派生度量(派生套派生)时,执行器现在沿 `of` 一路展开到聚合度量,按依赖先后计算;环路(`loop_a → loop_b → loop_a`)在读任何数据前以 `DATASET_INVALID` / 400 拒绝,消息写出环路路径。 - 为什么改:实测 main 上实时查询(native 与 ObjectQL 两策略)把派生操作数当成基础字段,拒为 `INVALID_FIELD`;草稿预览不是“能答”,而是把它当行计数,答出看似合理的错数(应为 150,答 1),环路也答出数字。 - 风险与回滚:只改 `DatasetExecutor.executeSelection` 的度量展开;预览与实时共用同一执行器,所以一处修复两边一致。普通派生度量值与列不变(对照钉子)。回滚即 revert 本 PR。 - 先看:`packages/services/service-analytics/src/dataset-executor.ts` 的 `expandSelectedMeasures`。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/derived-of-derived-measure.test.ts`,预期 16 passed。 - 需要你做的:无,席位落地。环路在预览上由“答出错数”改为拒绝,是否需契约复审由席位定。 ## What changes - **`packages/services/service-analytics/src/dataset-executor.ts`.** New exported `expandSelectedMeasures(measures, derived)`: the selected non-derived measures, then a depth-first walk of each selected derived measure's `of`, which adds aggregated operands to the base set and returns the derived measures dependencies first (each once). A derived measure that reaches itself is refused `DATASET_INVALID` / 400 (`datasetInvalidError`, an existing code) with the cycle's path, before any query. `executeSelection` calls it in place of the one-level expansion; the derived pass, the `totals` re-entry and the single-query test read its result unchanged. For a derived measure whose operands are all aggregated, the base set and derived order are what they were. - **`packages/services/service-analytics/src/__tests__/derived-of-derived-measure.test.ts`** (new). On the native strategy, the ObjectQL strategy and the draft preview, over a real SQLite engine: two levels served with values; three levels served, with a `totals` grand total; the cycle and a measure built on it refused `DATASET_INVALID` / 400 with `loop_a → loop_b → loop_a` and zero reads; CONTROL, a plain derived measure keeps its value and its columns. Plus one pure cell on `expandSelectedMeasures` (dependency order, a shared operand once, base order). - **`.changeset/28127-derived-of-derived-measure.md`.** `@objectstack/service-analytics` patch. ## Why ### Before (measured at `origin/main` `062a2323`) Dataset over `amount` with `total` (sum), `deals` (count), `total_twice` = derived sum of `[total, total]`, `twice_per_deal` = derived ratio of `[total_twice, deals]`; rows amer 100 + 50, emea 30. Selecting `twice_per_deal` by region: | Face | Before | After | |:---|:---|:---| | native | refused `INVALID_FIELD` / 400: "Measure 'total_twice' on cube 'os28127_ds' aggregates field 'total_twice', which object 'os28127_deal' does not have" | amer 150, emea 60 | | ObjectQL | same refusal | amer 150, emea 60 | | draft preview | served amer **1**, emea **1** (`total_twice` answered as a row count: 2 and 1) | amer 150, emea 60 | A cycle (`loop_a` = sum of `[loop_b, total]`, `loop_b` = sum of `[loop_a, total]`; `DatasetSchema` parses it, refusing only the one-step self-reference), selecting `loop_a`: native and ObjectQL refused `INVALID_FIELD` naming `loop_b` as a missing field; the draft preview served amer 152, emea 31. After: `DATASET_INVALID` / 400 on all three, "derived measure "loop_a" depends on itself: loop_a → loop_b → loop_a", before any read. ### Why this path The card read the draft preview as expanding derived-of-derived. It does not: the preview runs the same `DatasetExecutor` over seed rows (`analytics-service.ts`, the ADR-0037 P3 branch), and its in-memory evaluator answers a measure the cube does not declare as `count(*)`. So there was no preview expansion to share; the one fix in the shared executor serves both faces, and the preview's wrong number goes with it. ### Clause-② `no`: `DatasetSchema` accepts a derived measure over a derived measure, and `content/docs/data-modeling/currency.mdx` describes one ("A derived `sum` or `difference` over one `fixed` code carries that code, so a measure built on it is judged the same way"); the live refusal contradicted that text. The cycle refusal reaches a selection no face answered correctly: the live faces already refused it (the code moves from `INVALID_FIELD` to `DATASET_INVALID`, both existing), and the draft preview served a meaningless number, which it now refuses. `Metadata-protocol: none`: nothing an author can write changes. ## Verification - New pins red on `origin/main` (fix reverted, test kept): 13 of 16 failed; green there: the three CONTROL cells. Green after: 16 of 16. - Ablations on the committed head (`scripts/ablation-replace.mjs`, each restored to the HEAD blob with `git diff HEAD` empty): derived operand added to the base set instead of walked → 13 failed; cycle check disabled → the 6 cycle cells fail (stack overflow instead of the refusal); derived order reversed → the 6 value cells and the pure cell fail; aggregated operands dropped → the 3 CONTROL cells, the 6 value cells and the pure cell fail. - `@objectstack/service-analytics` full suite: 197 files, 4775 passed / 282 skipped. `tsc --noEmit`: exit 0. - `dispatch-gates --commands` derived 59 families on the committed head `925343a7`, run after a whole-tree `turbo run build` and fetching the teardown self-test's pinned commit: all 59 exit 0. `--ran`: 59 derived, 59 run, 0 NOT-MEASURED. `pnpm lint`: exit 0. ## Acceptance notes - **Out of scope, not changed:** the draft preview's in-memory evaluator (`evaluateAnalyticsQueryOverRows`) answers a measure the cube does not declare as `count(*)` where the live faces refuse it `INVALID_FIELD`. Measured only through the derived operand this PR stops sending; whether another caller reaches it was not measured. - A derived measure's intermediate derived operands appear as columns of the result, as its aggregated operands already did. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (Not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is the repo's own Chinese reader section). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cyJ2FnmRRSXEUtT6G1)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cyJ2FnmRRSXEUtT6G1 Co-authored-by: Claude <noreply@anthropic.com>
1 parent f9a1363 commit 8882857

3 files changed

Lines changed: 284 additions & 13 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(service-analytics): a live dataset query serves a derived measure built on another derived measure, and refuses a derived cycle with its path
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`DatasetSchema` accepts a derived measure whose `of` names another derived measure, and the currency page (`content/docs/data-modeling/currency.mdx`) describes one: "a measure built on it is judged the same way". `queryDataset` did not answer it:
11+
12+
- **Live query, native and ObjectQL strategies.** The derived operand was handed to the cube as a base measure and refused `INVALID_FIELD` / 400 ("Measure 'total_twice' on cube … aggregates field 'total_twice', which object … does not have"). It is now served: the executor follows `of` until it reaches aggregated measures and computes the derived measures dependencies first, at any depth, in `totals` too.
13+
- **Draft preview.** It runs the same executor over seed rows and answered the derived operand as a row count, so a `ratio` over a derived `sum` read `1` where the answer was `150`. It now answers the same value as the live query.
14+
- **A cycle.** A derived measure that reaches itself through `of` (`loop_a` → `loop_b` → `loop_a`; the schema refuses only the one-step self-reference) has no value at any depth. Selecting it, or a measure built on it, is refused `DATASET_INVALID` / 400 before anything is read, and the message names the cycle. Before, the live strategies refused it `INVALID_FIELD` as an unknown field and the draft preview served a number.
15+
16+
A derived measure whose operands are all aggregated measures is unchanged: same value, same columns.
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28127] A derived measure whose `of` names ANOTHER derived measure, through
5+
* `queryDataset` on both strategies and on the draft preview.
6+
*
7+
* ## What these pins hold
8+
*
9+
* - Served with its value on the native strategy and on the ObjectQL one:
10+
* `DatasetExecutor` follows `of` until it reaches aggregated measures and
11+
* computes the derived ones dependencies first. Before, the derived operand
12+
* was handed to the cube as a base measure and both strategies refused it
13+
* (`INVALID_FIELD`, "aggregates field 'total_twice', which object … does not
14+
* have").
15+
* - The draft preview answers the same value. It runs the same executor over
16+
* seed rows, and before it answered the derived operand as a row COUNT
17+
* (`total_twice` = 2 for two deals), so `twice_per_deal` read 1 instead of 150.
18+
* - A cycle (`loop_a` → `loop_b` → `loop_a`) is refused `DATASET_INVALID` /
19+
* 400 with its path, before anything is read, on every face. Before, the
20+
* live faces refused it as an unknown field and the preview served a number.
21+
* - CONTROL: a plain derived measure keeps its value and its columns.
22+
*/
23+
24+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
25+
import { ObjectQL } from '@objectstack/objectql';
26+
import { SqlDriver } from '@objectstack/driver-sql';
27+
import { DatasetSchema } from '@objectstack/spec/ui';
28+
import type { AnalyticsResult } from '@objectstack/spec/contracts';
29+
import type { AnalyticsService } from '../analytics-service.js';
30+
import { expandSelectedMeasures } from '../dataset-executor.js';
31+
import { AnalyticsServicePlugin } from '../plugin.js';
32+
import { installDefaultOrganization } from './default-organization.testkit.js';
33+
34+
const OBJECT = 'os28127_deal';
35+
36+
const ROWS = [
37+
{ id: 'd1', region: 'amer', amount: 100 },
38+
{ id: 'd2', region: 'amer', amount: 50 },
39+
{ id: 'd3', region: 'emea', amount: 30 },
40+
] as const;
41+
42+
const DATASET = DatasetSchema.parse({
43+
name: 'os28127_deals',
44+
label: 'Deals',
45+
object: OBJECT,
46+
dimensions: [{ name: 'region', field: 'region', type: 'string' }],
47+
measures: [
48+
{ name: 'total', aggregate: 'sum', field: 'amount' },
49+
{ name: 'deals', aggregate: 'count' },
50+
{ name: 'per_deal', derived: { op: 'ratio', of: ['total', 'deals'] } },
51+
{ name: 'total_twice', derived: { op: 'sum', of: ['total', 'total'] } },
52+
{ name: 'twice_per_deal', derived: { op: 'ratio', of: ['total_twice', 'deals'] } },
53+
{ name: 'twice_per_deal_over_total', derived: { op: 'difference', of: ['twice_per_deal', 'total'] } },
54+
],
55+
});
56+
57+
const CYCLE = DatasetSchema.parse({
58+
name: 'os28127_cycle',
59+
label: 'Cycle',
60+
object: OBJECT,
61+
dimensions: [{ name: 'region', field: 'region', type: 'string' }],
62+
measures: [
63+
{ name: 'total', aggregate: 'sum', field: 'amount' },
64+
{ name: 'loop_a', derived: { op: 'sum', of: ['loop_b', 'total'] } },
65+
{ name: 'loop_b', derived: { op: 'sum', of: ['loop_a', 'total'] } },
66+
{ name: 'on_loop', derived: { op: 'sum', of: ['total', 'loop_a'] } },
67+
],
68+
});
69+
70+
type Path = 'native' | 'objectql' | 'preview';
71+
const PATHS: readonly Path[] = ['native', 'objectql', 'preview'];
72+
73+
const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } };
74+
75+
type Refusal = Error & { code?: string; status?: number };
76+
77+
const refusalOf = (p: Promise<unknown>): Promise<Refusal> =>
78+
p.then<never, Refusal>(
79+
() => {
80+
throw new Error('expected a refusal, but the query resolved');
81+
},
82+
(e) => e as Refusal,
83+
);
84+
85+
const byRegion = (result: AnalyticsResult, measure: string) =>
86+
Object.fromEntries((result.rows as Array<Record<string, unknown>>).map((r) => [r.region, Number(r[measure])]));
87+
88+
/** A `'protocol'` service answering one pending seed draft, which routes `previewDrafts` onto the preview path. */
89+
const pendingSeedProtocol = {
90+
getMetaItems: async () => [{ name: 'os28127_seed', object: OBJECT }],
91+
getMetaItem: async () => ({ item: { records: ROWS } }),
92+
};
93+
94+
describe('[#28127] a derived measure over a derived measure', () => {
95+
let engine: ObjectQL;
96+
/** Raw-SQL statements and engine aggregates that read THIS object. */
97+
const reads = { rawSql: 0, aggregate: 0 };
98+
const services: Partial<Record<'native' | 'objectql', AnalyticsService>> = {};
99+
100+
const ask = (path: Path, dataset: typeof DATASET, selection: Record<string, unknown>) =>
101+
services[path === 'preview' ? 'objectql' : path]!.queryDataset(
102+
dataset,
103+
selection as never,
104+
undefined,
105+
path === 'preview' ? { previewDrafts: true } : undefined,
106+
);
107+
108+
beforeAll(async () => {
109+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
110+
engine = new ObjectQL({ logger: quiet } as never);
111+
engine.registerDriver(driver as never, true);
112+
await engine.init();
113+
engine.registry.registerObject({
114+
name: OBJECT,
115+
label: 'Deal',
116+
fields: {
117+
region: { name: 'region', type: 'text' },
118+
amount: { name: 'amount', type: 'number' },
119+
},
120+
} as never);
121+
await engine.syncSchemas();
122+
await installDefaultOrganization(engine as never);
123+
for (const row of ROWS) await engine.insert(OBJECT, { ...row } as never);
124+
125+
const realExecute = (engine as any).execute.bind(engine);
126+
(engine as any).execute = (sql: unknown, opts?: { object?: string }) => {
127+
if (opts?.object === OBJECT) reads.rawSql += 1;
128+
return realExecute(sql, opts);
129+
};
130+
const realAggregate = engine.aggregate.bind(engine);
131+
(engine as any).aggregate = (object: string, ...rest: unknown[]) => {
132+
if (object === OBJECT) reads.aggregate += 1;
133+
return (realAggregate as any)(object, ...rest);
134+
};
135+
136+
for (const [face, caps] of [
137+
['native', undefined],
138+
['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })],
139+
] as const) {
140+
const registered: Record<string, unknown> = {};
141+
const provided: Record<string, unknown> = { data: engine, protocol: pendingSeedProtocol };
142+
await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({
143+
getService: (name: string) => provided[name] ?? registered[name],
144+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
145+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
146+
hook: () => {},
147+
logger: quiet,
148+
} as never);
149+
services[face] = registered.analytics as AnalyticsService;
150+
}
151+
});
152+
153+
afterAll(async () => {
154+
try { await engine?.destroy(); } catch { /* noop */ }
155+
});
156+
157+
for (const path of PATHS) {
158+
describe(`${path} path`, () => {
159+
it('serves a derived measure over a derived one with its value', async () => {
160+
const result = await ask(path, DATASET, { dimensions: ['region'], measures: ['twice_per_deal'] });
161+
// amer: (150 + 150) / 2 deals; emea: (30 + 30) / 1 deal.
162+
expect(byRegion(result, 'twice_per_deal')).toEqual({ amer: 150, emea: 60 });
163+
expect(byRegion(result, 'total_twice')).toEqual({ amer: 300, emea: 60 });
164+
});
165+
166+
it('serves three levels, and a totals grand total over them', async () => {
167+
const result = await ask(path, DATASET, {
168+
dimensions: ['region'],
169+
measures: ['twice_per_deal_over_total'],
170+
totals: { groupings: [[]] },
171+
});
172+
// twice_per_deal − total: amer 150 − 150, emea 60 − 30.
173+
expect(byRegion(result, 'twice_per_deal_over_total')).toEqual({ amer: 0, emea: 30 });
174+
// Grand total: 360 / 3 deals − 180.
175+
expect(Number((result.totals?.[0]?.rows[0] as Record<string, unknown>).twice_per_deal_over_total)).toBe(-60);
176+
});
177+
178+
for (const [label, measure] of [['the cycle itself', 'loop_a'], ['a measure on the cycle', 'on_loop']] as const) {
179+
it(`refuses ${label} DATASET_INVALID / 400 with the cycle's path, before anything is read`, async () => {
180+
const before = { ...reads };
181+
const err = await refusalOf(ask(path, CYCLE, { dimensions: ['region'], measures: [measure] }));
182+
expect(err.code, err.message).toBe('DATASET_INVALID');
183+
expect(err.status).toBe(400);
184+
expect(err.message).toContain('loop_a → loop_b → loop_a');
185+
expect(reads.rawSql - before.rawSql).toBe(0);
186+
expect(reads.aggregate - before.aggregate).toBe(0);
187+
});
188+
}
189+
190+
it('CONTROL: a plain derived measure keeps its value and its columns', async () => {
191+
const result = await ask(path, DATASET, { dimensions: ['region'], measures: ['per_deal'] });
192+
expect(byRegion(result, 'per_deal')).toEqual({ amer: 75, emea: 30 });
193+
expect((result.fields ?? []).map((f) => f.name)).toEqual(['region', 'total', 'deals', 'per_deal']);
194+
});
195+
});
196+
}
197+
198+
it('expandSelectedMeasures: dependencies first, a shared operand once, base measures in selection order', () => {
199+
const derived = [
200+
{ name: 'c', op: 'sum' as const, of: ['b', 'a'] },
201+
{ name: 'b', op: 'sum' as const, of: ['a', 'x'] },
202+
{ name: 'a', op: 'sum' as const, of: ['x', 'y'] },
203+
];
204+
const { base, derived: ordered } = expandSelectedMeasures(['z', 'c', 'b'], derived);
205+
expect([...base]).toEqual(['z', 'x', 'y']);
206+
expect(ordered.map((d) => d.name)).toEqual(['a', 'b', 'c']);
207+
});
208+
});

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

Lines changed: 60 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,63 @@ export function splitMeasuresByFilter(
191191
return { unfiltered, filtered };
192192
}
193193

194+
/**
195+
* [#28127] Expand a selection's measures into the base measures the queries
196+
* must aggregate and the derived measures the executor computes afterwards.
197+
*
198+
* A derived measure's `of` may name ANOTHER derived measure (`DatasetSchema`
199+
* accepts it, and the currency guard judges it at the next level), so the walk
200+
* follows `of` until it reaches aggregated measures. Before, only the selected
201+
* measure's own `of` was read: a derived operand was handed to the cube as a
202+
* base measure, which the live strategies refused (`INVALID_FIELD`, "aggregates
203+
* field 'total_twice', which object … does not have") and the draft preview
204+
* answered as a row count — a plausible wrong number.
205+
*
206+
* `derived` comes back dependencies first, so {@link evaluateDerivedMeasures}
207+
* finds every operand already computed on the row. A derived measure that
208+
* reaches itself through `of` has no value at any depth and is refused
209+
* `DATASET_INVALID` / 400 with the cycle's path (`DatasetSchema` refuses only
210+
* the one-step self-reference).
211+
*/
212+
export function expandSelectedMeasures(
213+
measures: readonly string[],
214+
derived: readonly DerivedMeasureSpec[],
215+
): { base: Set<string>; derived: DerivedMeasureSpec[] } {
216+
const derivedByName = new Map(derived.map((d) => [d.name, d]));
217+
const base = new Set<string>();
218+
const ordered: DerivedMeasureSpec[] = [];
219+
const done = new Set<string>();
220+
const path: string[] = [];
221+
const visit = (d: DerivedMeasureSpec): void => {
222+
if (done.has(d.name)) return;
223+
const at = path.indexOf(d.name);
224+
if (at >= 0) {
225+
const cycle = [...path.slice(at), d.name].join(' → ');
226+
throw datasetInvalidError(
227+
`[dataset-executor] derived measure "${d.name}" depends on itself: ${cycle}. `
228+
+ 'A derived measure must reach aggregated measures through `of`; remove one of these names from the `of` that closes the cycle.',
229+
);
230+
}
231+
path.push(d.name);
232+
for (const dep of d.of) {
233+
const inner = derivedByName.get(dep);
234+
if (inner) visit(inner);
235+
else base.add(dep);
236+
}
237+
path.pop();
238+
done.add(d.name);
239+
ordered.push(d);
240+
};
241+
for (const m of measures) {
242+
if (!derivedByName.has(m)) base.add(m);
243+
}
244+
for (const m of measures) {
245+
const d = derivedByName.get(m);
246+
if (d) visit(d);
247+
}
248+
return { base, derived: ordered };
249+
}
250+
194251
/**
195252
* Evaluate derived measures on each aggregated row, mutating a shallow copy.
196253
* Division by zero (and missing operands) yields `null` rather than Infinity/NaN.
@@ -1215,19 +1272,9 @@ export class DatasetExecutor {
12151272
selection: DatasetSelection,
12161273
context?: ExecutionContext,
12171274
): Promise<AnalyticsResult> {
1218-
const derivedByName = new Map(compiled.derived.map((d) => [d.name, d]));
1219-
const selectedDerived = selection.measures
1220-
.map((m) => derivedByName.get(m))
1221-
.filter((d): d is DerivedMeasureSpec => !!d);
1222-
1223-
// Base measures = selected non-derived + dependencies of selected derived.
1224-
const baseMeasures = new Set<string>();
1225-
for (const m of selection.measures) {
1226-
if (!derivedByName.has(m)) baseMeasures.add(m);
1227-
}
1228-
for (const d of selectedDerived) {
1229-
for (const dep of d.of) baseMeasures.add(dep);
1230-
}
1275+
// Base measures = selected non-derived + the aggregated measures the
1276+
// selected derived ones reach through `of`, at any depth (#28127).
1277+
const { base: baseMeasures, derived: selectedDerived } = expandSelectedMeasures(selection.measures, compiled.derived);
12311278

12321279
// Split measures into those with a scoped filter and those without.
12331280
const { unfiltered, filtered } = splitMeasuresByFilter(baseMeasures, compiled.measureFilters);

0 commit comments

Comments
 (0)