Skip to content

Commit 85663e9

Browse files
committed
fix(objectql): refuse a plain group over a virtual field at the aggregate door
A groupBy entry of any form naming a formula field (no stored column) is refused INVALID_FIELD / 400 at groupBy.N / groupBy.N.field before any driver is asked; a bucket over one keeps the date-bucket words. Claude-Session: https://claude.ai/code/session_016WV4cyTehJsfYGVMzcXLJD Co-authored-by: Claude <noreply@anthropic.com>
1 parent 447226b commit 85663e9

3 files changed

Lines changed: 140 additions & 24 deletions

File tree

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

Lines changed: 80 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212
* used twice, an aggregation alias equal to a group column, or two group
1313
* entries projecting one column — {@link assertAggregatedColumnsAreDistinct}.
1414
*
15+
* [#29167, #29304] …and, ahead of the first, a `groupBy` entry of any form —
16+
* a name, `{ field }`, or a bucket — naming a VIRTUAL field, which no driver
17+
* stores a column for — {@link assertGroupByTargetsAreStored}.
18+
*
1519
* ## What ran before this door, measured on `origin/main` `cb0a2fcf4f`
1620
*
1721
* Through `findData` (the `POST /api/v1/data/:object/query` door) over three
@@ -48,26 +52,34 @@
4852
* ingress door answers an unknown one first; a system column the map does not
4953
* declare is bucketed as before), or a registry-less host.
5054
*
51-
* ## A virtual field (`formula`) is refused, on its storage ground [#29167]
55+
* ## A virtual field (`formula`) is refused, on its storage ground [#29167, #29304]
5256
*
5357
* A `formula` names no stored value class (its value is the expression's), so
5458
* the class reading above cannot judge it. It is refused on the ground the
5559
* sort, filter, search and value-aggregate axes already refuse it on: it is
5660
* VIRTUAL — computed on read, no column — judged by the spec's
5761
* `isVirtualSearchField` (`SEARCH_VIRTUAL_TYPES`), never a local type list,
5862
* and whatever its `returnType` says. Measured on `origin/main` `7788eedb`
59-
* before this arm, a month bucket over a `formula` with `returnType: 'date'`:
63+
* before the bucket arm (#29167), a month bucket over a `formula` with
64+
* `returnType: 'date'`, and on `origin/main` `447226b2` before the plain arm
65+
* (#29304), a plain group over a `formula` (`returnType` `date` or `text`):
6066
*
6167
* | caller | answer |
6268
* |:--|:--|
6369
* | a SQL driver | `INVALID_FIELD` / 400 from the driver's missing-column backstop: no `path`, and a "run schema sync" prescription that cannot help |
6470
* | a driver with no native `aggregate` (the in-memory aggregation) | `200`, one `null` group holding every row |
6571
*
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).
72+
* Every `groupBy` entry is judged, whatever its form, by
73+
* {@link assertGroupByTargetsAreStored}, ahead of the date-bucket door: a
74+
* bucket answers {@link virtualDateBucketMessage} at
75+
* `groupBy.N.dateGranularity` (the #29167 words), a plain group answers
76+
* {@link virtualGroupMessage} at `groupBy.N` (a name) or `groupBy.N.field`
77+
* (the object form) — `INVALID_FIELD` / 400 either way, with the remedy those
78+
* axes give: store the value on a stored field and use that.
79+
* `@objectstack/service-analytics`'s `dataset-date-bucket-door.ts` gives the
80+
* same refusals on the faces that reach no engine (the `/analytics/sql` dry
81+
* run and the draft preview), and its native-SQL strategy declines a grouped
82+
* dimension over a virtual field, so that face reaches this door.
7183
*
7284
* ## The column names
7385
*
@@ -127,11 +139,69 @@ function virtualDateBucketMessage(
127139
+ 'that aggregates in memory put every row into one null group while the answer looked served.';
128140
}
129141

142+
/**
143+
* [#29304] The refusal of a plain group over a VIRTUAL field (see the module
144+
* header): {@link virtualDateBucketMessage}'s words for a group key with no
145+
* bucket. `@objectstack/service-analytics`'s `dataset-date-bucket-door.ts`
146+
* carries the one copy, compared field for field by its tests.
147+
*/
148+
function virtualGroupMessage(object: string, path: string, field: string, type: string): string {
149+
return `aggregate('${object}'): ${path} groups by '${field}', but '${field}' is a ${type} field — its value `
150+
+ 'is computed on read and never stored, so no driver materialises a column to group by. The query was NOT '
151+
+ `run. Denormalise the value onto '${object}' (a stored field, written when the source changes) and group `
152+
+ 'by that. A formula field is virtual: with no column behind it the group key reached the driver as a '
153+
+ 'column that does not exist, and an engine that aggregates in memory put every row into one null group '
154+
+ 'while the answer looked served.';
155+
}
156+
157+
/**
158+
* Refuse a `groupBy` entry of any form — a name, `{ field }`, or a
159+
* `{ field, dateGranularity }` bucket — naming a field the object declares
160+
* VIRTUAL (`formula`; the spec's `isVirtualSearchField`), `INVALID_FIELD` /
161+
* 400 at the position it names. See the module header.
162+
*/
163+
export function assertGroupByTargetsAreStored(
164+
object: string,
165+
schema: unknown,
166+
groupBy: unknown,
167+
): void {
168+
if (!Array.isArray(groupBy) || groupBy.length === 0) return;
169+
const fields = (schema as { fields?: unknown } | undefined)?.fields;
170+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return;
171+
for (const [i, entry] of groupBy.entries()) {
172+
const named = typeof entry === 'string';
173+
if (!named && (entry === null || typeof entry !== 'object' || Array.isArray(entry))) continue;
174+
const { field, dateGranularity } = named
175+
? { field: entry, dateGranularity: undefined }
176+
: entry as { field?: unknown; dateGranularity?: unknown };
177+
if (typeof field !== 'string' || !Object.prototype.hasOwnProperty.call(fields, field)) continue;
178+
const declared = (fields as Record<string, { type?: unknown }>)[field];
179+
if (!isVirtualSearchField(declared as never)) continue;
180+
const type = String(declared?.type);
181+
if (dateGranularity != null) {
182+
// [#29167] The bucket keeps its own words and position.
183+
const path = `groupBy.${i}.dateGranularity`;
184+
throw refusal(
185+
'INVALID_FIELD',
186+
virtualDateBucketMessage(object, path, field, type, String(dateGranularity)),
187+
{ field, fields: [field], object, param: 'groupBy', path },
188+
);
189+
}
190+
const path = named ? `groupBy.${i}` : `groupBy.${i}.field`;
191+
throw refusal(
192+
'INVALID_FIELD',
193+
virtualGroupMessage(object, path, field, type),
194+
{ field, fields: [field], object, param: 'groupBy', path },
195+
);
196+
}
197+
}
198+
130199
/**
131200
* Refuse a `groupBy` entry whose `dateGranularity` buckets a field the object
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.
201+
* declares neither a date nor a datetime — `INVALID_FIELD` / 400, naming the
202+
* position, the field and its declared type. A virtual field is judged ahead
203+
* of this door, by {@link assertGroupByTargetsAreStored}. See the module
204+
* header.
135205
*/
136206
export function assertDateBucketTargetsAreTemporal(
137207
object: string,
@@ -147,18 +217,6 @@ export function assertDateBucketTargetsAreTemporal(
147217
const { field, dateGranularity } = entry as { field?: unknown; dateGranularity?: unknown };
148218
if (dateGranularity == null || typeof field !== 'string') continue;
149219
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-
}
162220
classes ??= declaredFieldClasses(fields);
163221
const cls = classes.get(field);
164222
if (cls === undefined || cls === 'date' || cls === 'datetime') continue;

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

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
* query runs the engine's in-memory aggregation over them: the controls below
1515
* read real buckets, and a refusal is proven to precede every read.
1616
*
17+
* [#29304] …and a plain group (a name, or `{ field }`) over a virtual
18+
* (`formula`) field, beside the #29167 bucket over one: `INVALID_FIELD` / 400
19+
* at `groupBy.N` / `groupBy.N.field`.
20+
*
1721
* [#25819] The REST door's empty-list refusal is the protocol's own
1822
* (`protocol.empty-aggregate-axis.test.ts`); the wire half below runs it over
1923
* the real engine, which is what turned it into `404 OBJECT_NOT_FOUND`.
@@ -128,6 +132,45 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
128132
expect(reads, 'every refusal precedes the driver').toHaveLength(0);
129133
});
130134

135+
it('[#29304] refuses a plain group over a virtual (formula) field, whatever its returnType: INVALID_FIELD / 400 at groupBy.N (a name) or groupBy.N.field — no read', async () => {
136+
// Before this arm the in-memory aggregation served one null group holding
137+
// every row, and a SQL driver refused a missing column with no path.
138+
const cases: ReadonlyArray<readonly [unknown, string, string]> = [
139+
['doubled', 'doubled', 'groupBy.1'],
140+
['opened_calc', 'opened_calc', 'groupBy.1'],
141+
[{ field: 'opened_calc' }, 'opened_calc', 'groupBy.1.field'],
142+
[{ field: 'doubled', alias: 'd' }, 'doubled', 'groupBy.1.field'],
143+
];
144+
for (const [entry, field, path] of cases) {
145+
const label = JSON.stringify(entry);
146+
const err = await refusalOf(aggregate({ groupBy: ['status', entry], aggregations: [COUNT] }));
147+
expect(envelopeOf(err), label).toEqual({ code: 'INVALID_FIELD', status: 400, httpStatus: 400 });
148+
expect({ path: err?.path, param: err?.param, field: err?.field, fields: err?.fields, object: err?.object }, label)
149+
.toEqual({ path, param: 'groupBy', field, fields: [field], object: OBJECT });
150+
expect(err!.message, label).toBe(
151+
`aggregate('${OBJECT}'): ${path} groups by '${field}', but '${field}' is a formula field — its value is computed `
152+
+ 'on read and never stored, so no driver materialises a column to group by. The query was NOT run. Denormalise '
153+
+ `the value onto '${OBJECT}' (a stored field, written when the source changes) and group by that. A formula `
154+
+ 'field is virtual: with no column behind it the group key reached the driver as a column that does not exist, '
155+
+ 'and an engine that aggregates in memory put every row into one null group while the answer looked served.',
156+
);
157+
}
158+
// The first offending position is named, whichever axis would refuse later ones.
159+
const first = await refusalOf(aggregate({ groupBy: ['doubled', { field: 'name', dateGranularity: 'month' }], aggregations: [COUNT] }));
160+
expect({ code: first?.code, path: first?.path }).toEqual({ code: 'INVALID_FIELD', path: 'groupBy.0' });
161+
expect(reads, 'every refusal precedes the driver').toHaveLength(0);
162+
});
163+
164+
it('[#29304] the REST door answers the plain-group refusal at its path, through findData and the wire mapping', async () => {
165+
const protocol = new ObjectStackProtocolImplementation(engine);
166+
const err = await refusalOf(protocol.findData({ object: OBJECT, query: { groupBy: ['opened_calc'], aggregations: [COUNT] } } as any));
167+
expect({ code: err?.code, status: err?.status, path: err?.path }).toEqual({ code: 'INVALID_FIELD', status: 400, path: 'groupBy.0' });
168+
const wire = mapDataError(err, OBJECT);
169+
expect({ status: wire.status, code: wire.body.code }).toEqual({ status: 400, code: 'INVALID_FIELD' });
170+
expect(String(wire.body.error)).toContain("groupBy.0 groups by 'opened_calc', but 'opened_calc' is a formula field");
171+
expect(reads).toHaveLength(0);
172+
});
173+
131174
it('refuses a repeated aggregation alias: INVALID_QUERY / 400 at the second aggregations.N.alias — no read', async () => {
132175
const err = await refusalOf(aggregate({
133176
aggregations: [COUNT, { function: 'sum', field: 'amount', alias: 'n' }],
@@ -174,6 +217,12 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
174217
// The declaration cannot type an undeclared column: no verdict. [#29167] A
175218
// formula under a dateGranularity is refused (above), no longer a control.
176219
await expect(aggregate({ groupBy: [{ field: 'created_at', dateGranularity: 'month' }], aggregations: [COUNT] })).resolves.toBeDefined();
220+
// [#29304] A stored field grouped plainly, as a name and in the object form,
221+
// and a value aggregate beside no virtual group key: served.
222+
await expect(aggregate({ groupBy: ['status'], aggregations: [COUNT] }))
223+
.resolves.toEqual([{ status: 'open', n: 2 }, { status: 'won', n: 1 }]);
224+
await expect(aggregate({ groupBy: [{ field: 'status' }], aggregations: [COUNT] }))
225+
.resolves.toEqual([{ status: 'open', n: 2 }, { status: 'won', n: 1 }]);
177226
// An alias moves the group column, so the field's own name is free.
178227
await expect(aggregate({ groupBy: [{ field: 'status', alias: 's' }], aggregations: [{ function: 'count', alias: 'status' }] }))
179228
.resolves.toEqual([{ s: 'open', status: 2 }, { s: 'won', status: 1 }]);
@@ -182,7 +231,7 @@ describe('[#25818] the aggregate query shapes that answered a plausible wrong ta
182231
groupBy: [{ field: 'opened_on', dateGranularity: 'year', alias: 'y' }, { field: 'opened_on', dateGranularity: 'month', alias: 'm' }],
183232
aggregations: [COUNT, { function: 'sum', field: 'amount', alias: 'total' }],
184233
})).resolves.toEqual([{ y: '2026', m: '2026-01', n: 1, total: 10 }, { y: '2026', m: '2026-02', n: 2, total: 50 }]);
185-
expect(reads, "each served query read once").toHaveLength(5);
234+
expect(reads, "each served query read once").toHaveLength(7);
186235
});
187236

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

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,11 @@ import { assertNoInternalFieldEvaluated, rejectInternalFieldEvaluation } from '.
4040
import { assertGroupByNamesNoJsonStoredField } from './group-by-structured-json-door.js';
4141
import { assertAggregationFieldTypesAccepted } from './aggregate-field-type-door.js';
4242
import { assertRecordCurrencyAggregatesGrouped } from './record-currency-aggregate-door.js';
43-
import { assertAggregatedColumnsAreDistinct, assertDateBucketTargetsAreTemporal } from './aggregate-query-shape-door.js';
43+
import {
44+
assertAggregatedColumnsAreDistinct,
45+
assertDateBucketTargetsAreTemporal,
46+
assertGroupByTargetsAreStored,
47+
} from './aggregate-query-shape-door.js';
4448
import { applyInMemoryAggregation } from './in-memory-aggregation.js';
4549
import { aggregatedRowColumnClasses, aggregatedRowColumnTypes, aggregatedRowColumns, applyHaving, assertAggregationFilterIsEvaluable, assertHavingIsEvaluable, assertHavingIsFilterCondition } from './having-filter.js';
4650
import {
@@ -131,6 +135,11 @@ export class DeleteAndAggregateFacet {
131135
// (every row in one null bucket), and two columns of the aggregated row
132136
// under one name (the last value written won). After the two doors
133137
// above, so a JSON field under a date bucket keeps their words.
138+
// [#29167, #29304] A group entry of any form over a VIRTUAL (`formula`)
139+
// field first: no driver stores a column for it (a SQL driver refused
140+
// it as a missing column, the in-memory aggregation served one null
141+
// group), and the date-bucket door has no class to judge it by.
142+
assertGroupByTargetsAreStored(object, this._registry.getObject(object), query.groupBy);
134143
assertDateBucketTargetsAreTemporal(object, this._registry.getObject(object), query.groupBy);
135144
assertAggregatedColumnsAreDistinct(object, query.groupBy, query.aggregations);
136145
// [#10576] The per-aggregation `filter` (`AggregationNodeSchema.filter`,

0 commit comments

Comments
 (0)