Skip to content

Commit 9ac6346

Browse files
committed
fix(service-analytics): refuse a plain group over a virtual field on every analytics face
Claude-Session: https://claude.ai/code/session_016WV4cyTehJsfYGVMzcXLJD Co-authored-by: Claude <noreply@anthropic.com>
1 parent 85663e9 commit 9ac6346

4 files changed

Lines changed: 120 additions & 20 deletions

File tree

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

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ import {
125125
} from './dimension-labels.js';
126126
import { evaluateAnalyticsQueryOverRows, lowerPreviewRowFilters } from './preview-evaluator.js';
127127
import { assertDatasetGroupColumnsDistinct } from './dataset-group-column-door.js';
128-
import { assertDatasetDateBucketsTemporal } from './dataset-date-bucket-door.js';
128+
import { assertDatasetDateBucketsTemporal, assertDatasetGroupTargetsStored } from './dataset-date-bucket-door.js';
129129
// [#25778] The one lookup of a dataset duration measure by name.
130130
import { durationMeasureIn } from './duration-measure-sql.js';
131131
import { scopedMeasureFilter, scopedMeasureKey } from './scoped-measure-key.js';
@@ -2967,6 +2967,10 @@ export class AnalyticsService implements IAnalyticsService {
29672967
// nor a datetime, with the refusal the engine gives both live faces
29682968
// for the same keys (after the column refusal above, as there),
29692969
// where the evaluator served one `null` (or `1970`) group.
2970+
// [#29304] A key of any form over a virtual (`formula`) field
2971+
// first, as the engine judges it first: the evaluator served one
2972+
// `null` group holding the total for a plain dimension over one.
2973+
assertDatasetGroupTargetsStored(aggregateObjectOf(cube), aggregateGroupKeys(q, cube), declaredType);
29702974
assertDatasetDateBucketsTemporal(aggregateObjectOf(cube), aggregateGroupKeys(q, cube), declaredType);
29712975
return evaluateAnalyticsQueryOverRows(
29722976
q,
@@ -5125,16 +5129,20 @@ export function inferredCallerMeasureSql(measure: string, cubeName: string): str
51255129
* `executeAggregate`, so every bucketed query goes to the engine); reached by
51265130
* a host composing `new AnalyticsService({ fallbackService })`, or a
51275131
* `queryCapabilities` override with `objectqlAggregate: false`.
5132+
*
5133+
* [#29304] The storage-axis door (`assertDatasetGroupTargetsStored`) runs
5134+
* first, on the same keys: a key of any form over a virtual (`formula`) field
5135+
* is refused as the engine refuses it.
51285136
*/
51295137
function assertDelegatedDateBucketsTemporal(query: AnalyticsQuery, ctx: StrategyContext): void {
51305138
const cube = ctx.getCube(query.cube!);
51315139
if (!cube) return;
51325140
const object = aggregateObjectOf(cube);
5133-
assertDatasetDateBucketsTemporal(
5134-
object,
5135-
aggregateGroupKeys(query, cube),
5136-
(field) => (ctx as DatasetScopedStrategyContext).declaredFieldType?.(object, field),
5137-
);
5141+
const groupBy = aggregateGroupKeys(query, cube);
5142+
const declaredType = (field: string) => (ctx as DatasetScopedStrategyContext).declaredFieldType?.(object, field);
5143+
// [#29304] A key of any form over a virtual field first, as the engine.
5144+
assertDatasetGroupTargetsStored(object, groupBy, declaredType);
5145+
assertDatasetDateBucketsTemporal(object, groupBy, declaredType);
51385146
}
51395147

51405148
/**

‎packages/services/service-analytics/src/dataset-date-bucket-door.ts‎

Lines changed: 56 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,19 @@
4444
* both its query and its dry run (`analytics-service.ts`,
4545
* `assertDelegatedDateBucketsTemporal`).
4646
*
47+
* [#29304] …and a PLAIN group key over a virtual field, which the engine's
48+
* storage-axis door (`assertGroupByTargetsAreStored`) now refuses ahead of its
49+
* date-bucket door, `INVALID_FIELD` / 400 at `groupBy.N`. Measured on
50+
* `origin/main` `447226b2` before it, a dataset or cube dimension over a
51+
* `formula` (`returnType` `date` or `text`): the dry run rendered
52+
* `GROUP BY calc` on both compositions and the preview served one `null`
53+
* group holding the total, while the native strategy answered
54+
* `DATABASE_ERROR` / 500 and the ObjectQL strategy the SQL driver's
55+
* missing-column backstop. {@link assertDatasetGroupTargetsStored} gives the
56+
* engine's refusal on the faces that hand it no keys (the preview, the dry
57+
* run, the delegated service), and `NativeSQLStrategy.canHandle` declines a
58+
* grouped dimension over a virtual field so the live query reaches the engine.
59+
*
4760
* Why a copy of the sentence: `@objectstack/objectql` is a dev dependency of
4861
* this package, never a runtime one, and its root does not export the door.
4962
* The message, code, status and keys are the engine's, and
@@ -61,7 +74,7 @@ type DateBucketRefusal = Error & {
6174
field?: string; fields?: string[]; object?: string; param?: string; path?: string;
6275
};
6376

64-
/** The refusal `assertDatasetDateBucketsTemporal` throws, with the engine's keys. */
77+
/** The refusal this module's two doors throw, with the engine's keys. */
6578
function dateBucketRefusal(message: string, object: string, field: string, path: string): DateBucketRefusal {
6679
const err = new Error(message) as DateBucketRefusal;
6780
err.code = StandardErrorCode.enum.INVALID_FIELD;
@@ -72,25 +85,27 @@ function dateBucketRefusal(message: string, object: string, field: string, path:
7285
}
7386

7487
/**
75-
* Refuse the first bucketed key in `groupBy` (built for a query on `object`)
76-
* whose field `declaredType` reads as a virtual field, or as declared and
77-
* neither a date nor a datetime, with the engine's refusal for it.
88+
* [#29167, #29304] Refuse the first key in `groupBy` (built for a query on
89+
* `object`), plain or bucketed, whose field `declaredType` reads as a VIRTUAL
90+
* field (the spec's `isVirtualSearchField`), with the engine's refusal for it:
91+
* `aggregate-query-shape-door.ts` `assertGroupByTargetsAreStored`, the bucket
92+
* in `virtualDateBucketMessage`'s words, the plain key in
93+
* `virtualGroupMessage`'s. Called ahead of
94+
* {@link assertDatasetDateBucketsTemporal}, as the engine calls its two doors.
7895
*/
79-
export function assertDatasetDateBucketsTemporal(
96+
export function assertDatasetGroupTargetsStored(
8097
object: string,
8198
groupBy: readonly AggregateGroupKey[],
8299
declaredType: (field: string) => string | undefined,
83100
): void {
84101
for (const [i, key] of groupBy.entries()) {
85-
if (typeof key === 'string') continue;
86-
const { field, dateGranularity } = key;
102+
const field = typeof key === 'string' ? key : key.field;
87103
const type = declaredType(field);
88-
const path = `groupBy.${i}.dateGranularity`;
89-
// [#29167] The engine's virtual-field arm (`aggregate-query-shape-door.ts`
90-
// `virtualDateBucketMessage`), judged first as there.
91-
if (type !== undefined && isVirtualSearchField({ type } as never)) {
104+
if (type === undefined || !isVirtualSearchField({ type } as never)) continue;
105+
if (typeof key !== 'string') {
106+
const path = `groupBy.${i}.dateGranularity`;
92107
throw dateBucketRefusal(
93-
`aggregate('${object}'): ${path} buckets '${field}' by '${dateGranularity}', but '${field}' `
108+
`aggregate('${object}'): ${path} buckets '${field}' by '${key.dateGranularity}', but '${field}' `
94109
+ `is a ${type} field — its value is computed on read and never stored, so no driver materialises a `
95110
+ `column to bucket. The query was NOT run. Denormalise the value onto '${object}' (a stored date or `
96111
+ 'datetime field, written when the source changes) and bucket that. A formula field is virtual: with '
@@ -99,6 +114,35 @@ export function assertDatasetDateBucketsTemporal(
99114
object, field, path,
100115
);
101116
}
117+
const path = `groupBy.${i}`;
118+
throw dateBucketRefusal(
119+
`aggregate('${object}'): ${path} groups by '${field}', but '${field}' is a ${type} field — its value `
120+
+ 'is computed on read and never stored, so no driver materialises a column to group by. The query was NOT '
121+
+ `run. Denormalise the value onto '${object}' (a stored field, written when the source changes) and group `
122+
+ 'by that. A formula field is virtual: with no column behind it the group key reached the driver as a '
123+
+ 'column that does not exist, and an engine that aggregates in memory put every row into one null group '
124+
+ 'while the answer looked served.',
125+
object, field, path,
126+
);
127+
}
128+
}
129+
130+
/**
131+
* Refuse the first bucketed key in `groupBy` (built for a query on `object`)
132+
* whose field `declaredType` reads as declared and neither a date nor a
133+
* datetime, with the engine's refusal for it. A virtual field is judged ahead
134+
* of this door, by {@link assertDatasetGroupTargetsStored}.
135+
*/
136+
export function assertDatasetDateBucketsTemporal(
137+
object: string,
138+
groupBy: readonly AggregateGroupKey[],
139+
declaredType: (field: string) => string | undefined,
140+
): void {
141+
for (const [i, key] of groupBy.entries()) {
142+
if (typeof key === 'string') continue;
143+
const { field, dateGranularity } = key;
144+
const type = declaredType(field);
145+
const path = `groupBy.${i}.dateGranularity`;
102146
if (type === undefined || CALENDAR_DATE_TYPES.has(type) || INSTANT_TYPES.has(type)) continue;
103147
throw dateBucketRefusal(
104148
`aggregate('${object}'): ${path} buckets '${field}' by '${dateGranularity}', but '${field}' `

‎packages/services/service-analytics/src/strategies/native-sql-strategy.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ import { AGGREGATE_ANSWER_KIND, presentAsNumber } from '@objectstack/core';
6060
// boolean-aggregand cast, and the one column-class predicate both read — the
6161
// operand rule `driver-sql`'s own `aggregate()` applies, defined once in core.
6262
import { aggregandColumnClass, aggregandOperandSql } from '@objectstack/core';
63-
import { emptyGroupValueFor } from '@objectstack/spec/data';
63+
import { emptyGroupValueFor, isVirtualSearchField } from '@objectstack/spec/data';
6464
import { explicitDateRangeWindow } from '../date-range-array-arm.js';
6565

6666
/**
@@ -838,6 +838,21 @@ export class NativeSQLStrategy implements AnalyticsStrategy {
838838
// decline above is: the query routes on, and the service refuses a
839839
// duration measure no native statement serves, with the reason.
840840
if (this.durationMeasureOnUnknownDialectIn(query, ctx)) return false;
841+
// ── [#29304] DECLINE a grouped dimension over a VIRTUAL field ──────────
842+
//
843+
// A `formula` is computed on read: no table stores a column for it, so the
844+
// `GROUP BY calc` this strategy compiles reached the database as a column
845+
// that does not exist and answered `DATABASE_ERROR` / 500, where the engine
846+
// refuses the same group key `INVALID_FIELD` / 400 at its position with the
847+
// store-the-value remedy (`@objectstack/objectql`'s
848+
// `assertGroupByTargetsAreStored`). The mechanism of the declines above:
849+
// what this strategy cannot serve as the engine would, the engine serves —
850+
// here, refuses — so the query routes to the ObjectQL strategy and every
851+
// composition answers one refusal. Only a GROUPED member is judged: a
852+
// `dimensions` entry (a bucketed `timeDimensions` entry already declines
853+
// above). A stored dimension, and a query that groups by no virtual field,
854+
// stay here. See {@link groupsByVirtualField}.
855+
if (this.groupsByVirtualField(query, ctx)) return false;
841856
const caps = ctx.queryCapabilities(query.cube);
842857
return caps.nativeSql && typeof ctx.executeRawSql === 'function';
843858
}
@@ -861,6 +876,35 @@ export class NativeSQLStrategy implements AnalyticsStrategy {
861876
return objects.some((object) => findReadableIdsLeaf(ctx.getReadScope!(object)) !== null);
862877
}
863878

879+
/**
880+
* [#29304] Does a `dimensions` entry of this query resolve to a column the
881+
* host declares VIRTUAL (the spec's `isVirtualSearchField`: `formula`)? See
882+
* the decline at {@link canHandle}. Each member resolves to the (object,
883+
* column) {@link resolveStorageTarget} gives the compiler — the object a
884+
* relationship path's last hop reaches for a dotted one — and is asked of the
885+
* host's `declaredFieldType`. An expression `sql`, a member that does not
886+
* resolve, and a host that wired no field types are not judged: "cannot
887+
* answer, do not block", the tiering every such hook here takes.
888+
*/
889+
private groupsByVirtualField(query: AnalyticsQuery, ctx: StrategyContext): boolean {
890+
const declared = (ctx as DatasetScopedStrategyContext).declaredFieldType;
891+
if (typeof declared !== 'function') return false;
892+
const cube = query.cube ? ctx.getCube(query.cube) : undefined;
893+
if (!cube) return false;
894+
const baseTable = this.extractObjectName(cube);
895+
const referenceOf = relationshipReferenceOf(ctx);
896+
return (query.dimensions ?? []).some((member) => {
897+
let target: { object: string; field: string };
898+
try {
899+
target = this.resolveStorageTarget(cube, member, baseTable, referenceOf);
900+
} catch {
901+
return false;
902+
}
903+
const type = declared.call(ctx, target.object, target.field);
904+
return type !== undefined && isVirtualSearchField({ type } as never);
905+
});
906+
}
907+
864908
/**
865909
* [#25778] Does this query request a dataset duration measure on a base
866910
* object whose SQL dialect the host cannot name? See the decline at

‎packages/services/service-analytics/src/strategies/objectql-strategy.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { markFilterSubtreeProvenance } from '@objectstack/spec/data';
88
import { StandardErrorCode } from '@objectstack/spec/api';
99
import type { AnalyticsStrategy, StrategyContext, DatasetScopedStrategyContext } from './types.js';
1010
import { assertDatasetGroupColumnsDistinct } from '../dataset-group-column-door.js';
11-
import { assertDatasetDateBucketsTemporal } from '../dataset-date-bucket-door.js';
11+
import { assertDatasetDateBucketsTemporal, assertDatasetGroupTargetsStored } from '../dataset-date-bucket-door.js';
1212
import {
1313
declaredDatetimeLowering,
1414
declaredDateColumn,
@@ -803,6 +803,10 @@ export class ObjectQLStrategy implements AnalyticsStrategy {
803803
// the query is served. A host that names no declared type is not judged,
804804
// as the engine judges no undeclared field.
805805
const declaredType = (ctx as DatasetScopedStrategyContext).declaredFieldType;
806+
// [#29304] A key of any form over a virtual (`formula`) field first, as
807+
// the engine judges it first: the echo printed `GROUP BY calc` for a
808+
// column no table stores.
809+
assertDatasetGroupTargetsStored(tableName, echoGroupBy, (field) => declaredType?.call(ctx, tableName, field));
806810
assertDatasetDateBucketsTemporal(tableName, echoGroupBy, (field) => declaredType?.call(ctx, tableName, field));
807811
const joinClauses: string[] = [];
808812
// [#21441] The bucket expression the driver itself groups by for its

0 commit comments

Comments
 (0)