Skip to content

Commit 52e0a0a

Browse files
committed
fix(objectql, service-analytics)!: a date bucket over a formula field is refused alike on every analytics face
The engine's date-bucket door judged no formula, so a bucket over one got three answers: the SQL driver's missing-column backstop on the live faces (no path, a "run schema sync" prescription), one null group on an engine that aggregates in memory and on the draft preview, and a rendered strftime(calc) on the /analytics/sql dry run. assertDateBucketTargetsAreTemporal now refuses a virtual field (isVirtualSearchField, the predicate the sort, filter and search axes read) with INVALID_FIELD / 400 at groupBy.N.dateGranularity and the store-the-value remedy; dataset-date-bucket-door.ts, the service's one copy, gains the same arm, so the dry run and the preview answer the engine's refusal field for field. Claude-Session: https://claude.ai/code/session_01ADHkmSJnRcLxaWbuSNkw5L Co-authored-by: Claude <noreply@anthropic.com>
1 parent f125ce4 commit 52e0a0a

5 files changed

Lines changed: 179 additions & 33 deletions

File tree

‎packages/objectql/src/aggregate-query-shape-door.ts‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,28 @@
4646
* day by. A `date` (`CALENDAR_DATE_TYPES`) and a `datetime` (`INSTANT_TYPES`)
4747
* pass. **Not judged:** a field the declaration cannot type — undeclared (the
4848
* ingress door answers an unknown one first; a system column the map does not
49-
* declare is bucketed as before), a `formula`, or a registry-less host.
49+
* declare is bucketed as before), or a registry-less host.
50+
*
51+
* ## A virtual field (`formula`) is refused, on its storage ground [#29167]
52+
*
53+
* A `formula` names no stored value class (its value is the expression's), so
54+
* the class reading above cannot judge it. It is refused on the ground the
55+
* sort, filter, search and value-aggregate axes already refuse it on: it is
56+
* VIRTUAL — computed on read, no column — judged by the spec's
57+
* `isVirtualSearchField` (`SEARCH_VIRTUAL_TYPES`), never a local type list,
58+
* and whatever its `returnType` says. Measured on `origin/main` `7788eedb`
59+
* before this arm, a month bucket over a `formula` with `returnType: 'date'`:
60+
*
61+
* | caller | answer |
62+
* |:--|:--|
63+
* | a SQL driver | `INVALID_FIELD` / 400 from the driver's missing-column backstop: no `path`, and a "run schema sync" prescription that cannot help |
64+
* | a driver with no native `aggregate` (the in-memory aggregation) | `200`, one `null` group holding every row |
65+
*
66+
* Both now answer {@link virtualDateBucketMessage}, `INVALID_FIELD` / 400 at
67+
* `groupBy.N.dateGranularity`, with the remedy those axes give: store the
68+
* value on a stored field and use that. `@objectstack/service-analytics`'s
69+
* `dataset-date-bucket-door.ts` gives the same refusal on the two faces that
70+
* reach no engine (the `/analytics/sql` dry run and the draft preview).
5071
*
5172
* ## The column names
5273
*
@@ -65,6 +86,7 @@
6586
*/
6687

6788
import { StandardErrorCode } from '@objectstack/spec/api';
89+
import { isVirtualSearchField } from '@objectstack/spec/data';
6890
import { declaredFieldClasses } from './having-filter.js';
6991

7092
type ShapeRefusal = Error & {
@@ -87,10 +109,29 @@ function refusal(
87109
return err;
88110
}
89111

112+
/**
113+
* [#29167] The refusal of a date bucket over a VIRTUAL field (see the module
114+
* header): the position, the field, its type and the granularity it was
115+
* bucketed by, then the store-the-value remedy the sort and filter axes give.
116+
* `@objectstack/service-analytics`'s `dataset-date-bucket-door.ts` carries the
117+
* one copy, compared field for field by its tests.
118+
*/
119+
function virtualDateBucketMessage(
120+
object: string, path: string, field: string, type: string, dateGranularity: string,
121+
): string {
122+
return `aggregate('${object}'): ${path} buckets '${field}' by '${dateGranularity}', but '${field}' `
123+
+ `is a ${type} field — its value is computed on read and never stored, so no driver materialises a `
124+
+ `column to bucket. The query was NOT run. Denormalise the value onto '${object}' (a stored date or `
125+
+ 'datetime field, written when the source changes) and bucket that. A formula field is virtual: with '
126+
+ 'no column behind it the bucket reached the driver as a column that does not exist, and an engine '
127+
+ 'that aggregates in memory put every row into one null group while the answer looked served.';
128+
}
129+
90130
/**
91131
* Refuse a `groupBy` entry whose `dateGranularity` buckets a field the object
92-
* declares neither a date nor a datetime — `INVALID_FIELD` / 400, naming the
93-
* position, the field and its declared type. See the module header.
132+
* declares neither a date nor a datetime, or a virtual (`formula`) field —
133+
* `INVALID_FIELD` / 400, naming the position, the field and its declared type.
134+
* See the module header.
94135
*/
95136
export function assertDateBucketTargetsAreTemporal(
96137
object: string,
@@ -105,11 +146,23 @@ export function assertDateBucketTargetsAreTemporal(
105146
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue;
106147
const { field, dateGranularity } = entry as { field?: unknown; dateGranularity?: unknown };
107148
if (dateGranularity == null || typeof field !== 'string') continue;
149+
const path = `groupBy.${i}.dateGranularity`;
150+
const declared = Object.prototype.hasOwnProperty.call(fields, field)
151+
? (fields as Record<string, { type?: unknown }>)[field]
152+
: undefined;
153+
// [#29167] A virtual field first: the class reading below has no class
154+
// for it, so it would otherwise be skipped unjudged.
155+
if (isVirtualSearchField(declared as never)) {
156+
throw refusal(
157+
'INVALID_FIELD',
158+
virtualDateBucketMessage(object, path, field, String(declared?.type), String(dateGranularity)),
159+
{ field, fields: [field], object, param: 'groupBy', path },
160+
);
161+
}
108162
classes ??= declaredFieldClasses(fields);
109163
const cls = classes.get(field);
110164
if (cls === undefined || cls === 'date' || cls === 'datetime') continue;
111165
const type = String((fields as Record<string, { type?: unknown }>)[field]?.type);
112-
const path = `groupBy.${i}.dateGranularity`;
113166
throw refusal(
114167
'INVALID_FIELD',
115168
`aggregate('${object}'): ${path} buckets '${field}' by '${String(dateGranularity)}', but '${field}' `

‎packages/objectql/src/engine-aggregate-query-shape-door.test.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ const PROBE = {
3939
opened_on: { name: 'opened_on', type: 'date' },
4040
seen_at: { name: 'seen_at', type: 'datetime' },
4141
doubled: { name: 'doubled', type: 'formula', expression: 'amount * 2' },
42+
// [#29167] A formula whose declared result IS a date: refused all the same.
43+
opened_calc: { name: 'opened_calc', type: 'formula', expression: 'opened_on', returnType: 'date' },
4244
},
4345
};
4446

@@ -106,6 +108,26 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
106108
expect(reads, 'every refusal precedes the driver').toHaveLength(0);
107109
});
108110

111+
it('[#29167] refuses a dateGranularity over a virtual (formula) field, whatever its returnType: INVALID_FIELD / 400 at groupBy.N.dateGranularity — no read', async () => {
112+
// Before this arm the in-memory aggregation served one null group here:
113+
// the formula has no stored value for it to bucket.
114+
for (const field of ['doubled', 'opened_calc']) {
115+
const err = await refusalOf(aggregate({
116+
groupBy: ['status', { field, dateGranularity: 'month' }],
117+
aggregations: [COUNT],
118+
}));
119+
expect(envelopeOf(err), field).toEqual({ code: 'INVALID_FIELD', status: 400, httpStatus: 400 });
120+
expect({ path: err?.path, param: err?.param, field: err?.field, fields: err?.fields, object: err?.object }, field)
121+
.toEqual({ path: 'groupBy.1.dateGranularity', param: 'groupBy', field, fields: [field], object: OBJECT });
122+
expect(err!.message, field).toContain(
123+
`groupBy.1.dateGranularity buckets '${field}' by 'month', but '${field}' is a formula field — its value is computed on read and never stored`,
124+
);
125+
// The store-the-value remedy the sort and filter axes give a virtual field.
126+
expect(err!.message, field).toContain(`Denormalise the value onto '${OBJECT}' (a stored date or datetime field, written when the source changes) and bucket that.`);
127+
}
128+
expect(reads, 'every refusal precedes the driver').toHaveLength(0);
129+
});
130+
109131
it('refuses a repeated aggregation alias: INVALID_QUERY / 400 at the second aggregations.N.alias — no read', async () => {
110132
const err = await refusalOf(aggregate({
111133
aggregations: [COUNT, { function: 'sum', field: 'amount', alias: 'n' }],
@@ -144,13 +166,13 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
144166
expect(reads).toHaveLength(0);
145167
});
146168

147-
it('CONTROL a date or datetime bucket, a formula or undeclared bucket, and distinct columns are served', async () => {
169+
it('CONTROL a date or datetime bucket, an undeclared bucket, and distinct columns are served', async () => {
148170
await expect(aggregate({ groupBy: [{ field: 'opened_on', dateGranularity: 'month' }], aggregations: [COUNT] }))
149171
.resolves.toEqual([{ opened_on: '2026-01', n: 1 }, { opened_on: '2026-02', n: 2 }]);
150172
await expect(aggregate({ groupBy: [{ field: 'seen_at', dateGranularity: 'month' }], aggregations: [COUNT] }))
151173
.resolves.toEqual([{ seen_at: '2026-01', n: 1 }, { seen_at: '2026-02', n: 2 }]);
152-
// The declaration cannot type a formula or an undeclared column: no verdict.
153-
await expect(aggregate({ groupBy: [{ field: 'doubled', dateGranularity: 'month' }], aggregations: [COUNT] })).resolves.toBeDefined();
174+
// The declaration cannot type an undeclared column: no verdict. [#29167] A
175+
// formula under a dateGranularity is refused (above), no longer a control.
154176
await expect(aggregate({ groupBy: [{ field: 'created_at', dateGranularity: 'month' }], aggregations: [COUNT] })).resolves.toBeDefined();
155177
// An alias moves the group column, so the field's own name is free.
156178
await expect(aggregate({ groupBy: [{ field: 'status', alias: 's' }], aggregations: [{ function: 'count', alias: 'status' }] }))
@@ -160,7 +182,7 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
160182
groupBy: [{ field: 'opened_on', dateGranularity: 'year', alias: 'y' }, { field: 'opened_on', dateGranularity: 'month', alias: 'm' }],
161183
aggregations: [COUNT, { function: 'sum', field: 'amount', alias: 'total' }],
162184
})).resolves.toEqual([{ y: '2026', m: '2026-01', n: 1, total: 10 }, { y: '2026', m: '2026-02', n: 2, total: 50 }]);
163-
expect(reads, "each served query read once").toHaveLength(6);
185+
expect(reads, "each served query read once").toHaveLength(5);
164186
});
165187

166188
it('the REST door answers the engine\'s refusal, not a 200 — through findData and the wire mapping', async () => {

‎packages/services/service-analytics/src/__tests__/objectql-echo-non-date-bucket.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
* | a cube dimension over `region` declaring one granularity, asked raw | the bucket |
2323
* | text `region` by month at `America/New_York` | `NOT_IMPLEMENTED` / 501 saying the query is served |
2424
*
25+
* [#29167] …and a bucket over a `formula` (virtual: no stored column), which
26+
* the dry run rendered as `strftime('%Y-%m', calc)` while the query refused it
27+
* from the SQL driver's missing-column backstop: both now answer the engine's
28+
* virtual-field refusal, field for field.
29+
*
2530
* It now judges the keys `execute()` hands the engine with the service's one
2631
* reading of it (`dataset-date-bucket-door.ts`, #28852), after the `dateRange`
2732
* read and the column-asked-twice door as `query()` refuses, so it answers the
@@ -99,6 +104,8 @@ describe('[#28977] the /analytics/sql dry run refuses a date bucket over a colum
99104
closed_at: { name: 'closed_at', type: 'datetime' },
100105
closed_on: { name: 'closed_on', type: 'date' },
101106
account: { name: 'account', type: 'lookup', reference: ACCOUNT },
107+
// [#29167] A formula the table stores no column for, whose result is a date.
108+
calc: { name: 'calc', type: 'formula', expression: 'closed_on', returnType: 'date' },
102109
},
103110
} as never);
104111
await engine.syncSchemas();
@@ -155,6 +162,25 @@ describe('[#28977] the /analytics/sql dry run refuses a date bucket over a colum
155162
expect(asSql, 'the dry run vs the query').toEqual(asQuery);
156163
});
157164

165+
it.each<[string, Query, string]>([
166+
['by month', onObject({ timeDimensions: [td('calc', 'month')] }), 'groupBy.0.dateGranularity'],
167+
['after a datetime bucket', onObject({ timeDimensions: [td('closed_at', 'year'), td('calc', 'month')] }), 'groupBy.1.dateGranularity'],
168+
['at a non-UTC zone', onObject({ timeDimensions: [td('calc', 'month')], timezone: 'America/New_York' }), 'groupBy.0.dateGranularity'],
169+
])('[#29167] refuses a bucket over a formula (virtual: no stored column) %s with the query\'s refusal, where the dry run rendered strftime', async (_label, query, path) => {
170+
const { asQuery, asSql } = await bothRefusals(query);
171+
expect(asQuery).toEqual({
172+
message:
173+
`aggregate('${DEAL}'): ${path} buckets 'calc' by 'month', but 'calc' is a formula field — its value is computed `
174+
+ 'on read and never stored, so no driver materialises a column to bucket. The query was NOT run. Denormalise '
175+
+ `the value onto '${DEAL}' (a stored date or datetime field, written when the source changes) and bucket that. `
176+
+ 'A formula field is virtual: with no column behind it the bucket reached the driver as a column that does not '
177+
+ 'exist, and an engine that aggregates in memory put every row into one null group while the answer looked served.',
178+
code: 'INVALID_FIELD', status: 400, httpStatus: 400,
179+
object: DEAL, param: 'groupBy', path, field: 'calc', fields: ['calc'],
180+
});
181+
expect(asSql, 'the dry run vs the query').toEqual(asQuery);
182+
});
183+
158184
it.each<[string, Query, string]>([
159185
["beside a cross-object 'account.name' (its FK column first)", onObject({ dimensions: ['account.name'], timeDimensions: [td('region', 'month')] }), 'groupBy.1.dateGranularity'],
160186
['after a raw date column and a datetime bucket', onObject({ dimensions: ['closed_on'], timeDimensions: [td('closed_at', 'month'), td('region', 'month')] }), 'groupBy.2.dateGranularity'],

‎packages/services/service-analytics/src/__tests__/preview-date-bucket-type.test.ts‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@
2323
* (`preview-date-bucket-door.ts`) and gives the same refusal, field for field.
2424
* A date and a datetime bucket are served alike on every face, as before.
2525
*
26-
* [#28977] Pinned too: a `time` column, a dataset dimension's declared
27-
* `dateGranularity` over a text column, and the `formula` skip (the engine
28-
* does not judge a formula, so neither does the door). And the preview now
26+
* [#28977] Pinned too: a `time` column and a dataset dimension's declared
27+
* `dateGranularity` over a text column. [#29167] A `formula` (virtual, no
28+
* stored column) is refused on every face with the engine's virtual-field
29+
* refusal; #28977 pinned it as skipped, and the preview served one `null`
30+
* group for it. And the preview now
2931
* lowers its row filters before the column-asked-twice and date-bucket doors,
3032
* where the live strategy lowers them, so an unrecognised `dateRange` beside
3133
* either fault is refused about the `dateRange` on every face; the preview
@@ -61,6 +63,7 @@ const DATASET = DatasetSchema.parse({
6163
{ name: 'opened_time', field: 'opened_time', type: 'date' },
6264
{ name: 'calc', field: 'calc', type: 'date' },
6365
{ name: 'region_month', field: 'region', type: 'date', dateGranularity: 'month' },
66+
{ name: 'calc_month', field: 'calc', type: 'date', dateGranularity: 'month' },
6467
],
6568
measures: [{ name: 'total', aggregate: 'sum', field: 'amount' }],
6669
});
@@ -188,16 +191,29 @@ describe('[#28852] a date bucket over a column that is not a date, on every face
188191
expect(refusal).toMatchObject({ path: 'groupBy.0.dateGranularity', field: 'region', fields: ['region'] });
189192
});
190193

191-
it('[#28977] does not judge a bucket over a formula, as the engine does not', async () => {
192-
// The engine skips a `formula` (its value class is the expression's), so
193-
// both live faces answer the next refusal, the driver's for a column the
194-
// table does not store. No face answers the date-bucket refusal. (The
195-
// preview serves the selection over its drafted rows, a separate gap.)
196-
for (const face of FACES) {
197-
const outcome = await ask(face, { measures: ['total'], timeDimensions: [{ dimension: 'calc', granularity: 'month' }] })
198-
.then(() => 'served', (e: Error & { path?: string }) => e.path ?? e.message);
199-
expect(outcome, face).not.toBe('groupBy.0.dateGranularity');
200-
}
194+
it('[#29167] refuses a bucket over a formula (virtual: no stored column) with the engine\'s refusal, where the preview served one null group', async () => {
195+
// [#28977] pinned the skip this replaces: the engine judged no formula, so
196+
// the live faces answered the SQL driver's missing-column backstop (no
197+
// path, a "run schema sync" prescription) and the preview served one
198+
// `null` group holding the total. The engine's door now refuses a virtual
199+
// field, and the service's copy gives the same refusal on the preview.
200+
const refusal = await refusedAlike({ measures: ['total'], timeDimensions: [{ dimension: 'calc', granularity: 'month' }] });
201+
expect(refusal).toEqual({
202+
message:
203+
`aggregate('${OBJECT}'): groupBy.0.dateGranularity buckets 'calc' by 'month', but 'calc' is a formula field — `
204+
+ 'its value is computed on read and never stored, so no driver materialises a column to bucket. The query was '
205+
+ `NOT run. Denormalise the value onto '${OBJECT}' (a stored date or datetime field, written when the source `
206+
+ 'changes) and bucket that. A formula field is virtual: with no column behind it the bucket reached the driver '
207+
+ 'as a column that does not exist, and an engine that aggregates in memory put every row into one null group '
208+
+ 'while the answer looked served.',
209+
code: 'INVALID_FIELD', status: 400, httpStatus: 400,
210+
object: OBJECT, param: 'groupBy', path: 'groupBy.0.dateGranularity', field: 'calc', fields: ['calc'],
211+
});
212+
});
213+
214+
it("[#29167] refuses a dataset dimension's declared dateGranularity over a formula", async () => {
215+
const refusal = await refusedAlike({ dimensions: ['calc_month'], measures: ['total'] });
216+
expect(refusal).toMatchObject({ path: 'groupBy.0.dateGranularity', field: 'calc', fields: ['calc'] });
201217
});
202218

203219
/** Every face refuses `selection` with one refusal of `code`, message included. */

0 commit comments

Comments
 (0)