From 197cb3585aaaa54c0b9259c41597ec2542e7592e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:29:07 +0000 Subject: [PATCH 1/9] wip(objectql): engine-internal relation group join on aggregate Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../src/engine-delete-and-aggregate.ts | 71 +++- packages/objectql/src/engine.ts | 1 + packages/objectql/src/relation-group-join.ts | 378 ++++++++++++++++++ 3 files changed, 447 insertions(+), 3 deletions(-) create mode 100644 packages/objectql/src/relation-group-join.ts diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 04061d71105..b0a0b59401b 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -36,7 +36,7 @@ */ import { normalizeFilterComparandTypes } from '@objectstack/spec/data'; -import type { EngineAggregateOptions, EngineDeleteOptions, HookContext, QueryAST } from '@objectstack/spec/data'; +import type { EngineAggregateOptions, EngineDeleteOptions, FilterCondition, HookContext, QueryAST } from '@objectstack/spec/data'; import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts'; import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; import { assertHavingTemporalComparandsInterpretable, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js'; @@ -79,6 +79,12 @@ import { writeFailureLogMeta, } from './engine-top-level.js'; import type { EngineReadOptions, OperationContext } from './engine-top-level.js'; +import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; +import { + assertRelationGroupRequestShape, assertRelationGroupRowsJoined, declineRelationGroup, planRelationGroups, + RELATION_GROUP_JOINS, relationGroupByRequestOf, relationGroupJoinsAtBoundary, relationGroupRegistryDecline, + type PlannedRelationGroup, +} from './relation-group-join.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; @@ -125,6 +131,7 @@ export interface DeleteAndAggregateHost { recomputeSummaries: ObjectQLClass['recomputeSummaries']; rejectCredentialAggregation: ObjectQLClass['rejectCredentialAggregation']; readonly relatedSchemaOf: ObjectQLClass['relatedSchemaOf']; + relationSemiJoinServes: ObjectQLClass['relationSemiJoinServes']; releaseSecretHandles: ObjectQLClass['releaseSecretHandles']; resolveObjectName: ObjectQLClass['resolveObjectName']; resolveWhereTokens: ObjectQLClass['resolveWhereTokens']; @@ -914,8 +921,30 @@ export class DeleteAndAggregateFacet { } /** The body of `ObjectQL#aggregate`; the method's docblock there is its contract. */ - static async aggregate(this: Pick, object: string, query: EngineAggregateOptions, options?: EngineReadOptions): Promise { + static async aggregate(this: Pick, object: string, query: EngineAggregateOptions, options?: EngineReadOptions): Promise { object = this.resolveObjectName(object); + // [relation group join] The engine-internal request to group by a + // related record's attributes (`relation-group-join.ts`). The registry + // half of its decline is judged first: a driver that compiles no join, + // a field that is not a single-valued relation to the named object, a + // related read the semi-join rule keeps out — declined before anything + // is read, so the caller's own path runs the doors below itself. + const relationGroup = relationGroupByRequestOf(options); + if (relationGroup !== undefined) { + const reason = relationGroupRegistryDecline.call({ + getObjectSchema: (name: string) => this._registry.getObject(name), + getDriver: (name: string) => this.getDriver(name) as { readonly name?: unknown; readonly aggregate?: unknown } | undefined, + relationSemiJoinServes: (o: string, t: string) => this.relationSemiJoinServes(o, t), + }, object, relationGroup); + if (reason !== undefined) { + declineRelationGroup(relationGroup, reason); + return []; + } + } + // [relation group join] A PLANNED read (`relation-semi-join.ts`): the + // related read a relation group join is built from is this verb, + // stopped at its driver call. Only the engine's own planner sets it. + const scopePlan = (options as Record | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined; // Fold the `filter` alias into `where` (#4346) — the AST below reads // `query.where` only, so an unfolded `{ filter }` aggregated every row. query = foldEngineOptionAliases(object, 'aggregate', query, ENGINE_WHERE_SLOTS); @@ -1250,6 +1279,19 @@ export class DeleteAndAggregateFacet { } const driver = this.getDriver(object); this.logger.debug(`Aggregate on ${object} using ${driver.name}`, query); + // [relation group join] Every door above has judged the base query; + // now the request's shape against the row it adds columns to, then + // each related read, planned as the caller. + let plannedRelationGroups: PlannedRelationGroup[] | null = null; + if (relationGroup !== undefined) { + assertRelationGroupRequestShape(object, relationGroup, aggregatedRowColumns(query.groupBy, query.aggregations)); + plannedRelationGroups = await planRelationGroups.call( + { aggregate: (o, q, opts) => this.facade.aggregate(o, q as EngineAggregateOptions, opts as EngineReadOptions) }, + relationGroup, + mergeReadContext(query?.context, options?.context), + ); + if (plannedRelationGroups === null) return []; + } const opCtx: OperationContext = { object, @@ -1329,6 +1371,12 @@ export class DeleteAndAggregateFacet { // are the related read's own (`relation-semi-join.ts`). const aggregateOptions = this.buildDriverOptions(object, opCtx.context, undefined, { recordedVerdict: opCtx.tenantLayer0Verdict }); const ast = await this.composeReadableIdsAtBoundary(object, 'aggregate', opCtx.ast as QueryAST, opCtx.context, aggregateOptions); + // [relation group join] A planned read hands its final `where` and + // driver options to the planner in place of the driver call. + if (scopePlan !== undefined) { + scopePlan.capture(ast.where as FilterCondition | undefined, aggregateOptions); + return scopePlan.rows; + } // Prefer driver.aggregate() when available — driver.find() in many // drivers (e.g. driver-sql) does not honor `groupBy` / `aggregations` @@ -1385,7 +1433,24 @@ export class DeleteAndAggregateFacet { return f != null && typeof f === 'object' && Object.keys(f).length > 0; }); const aggregationFilterNative = drv?.supports?.aggregationFilter === true; - if (typeof drv.aggregate === 'function' && allStructuredSupported && !tzRequiresInMemory && (!hasAggregationFilter || aggregationFilterNative)) { + const nativeAggregate = typeof drv.aggregate === 'function' && allStructuredSupported && !tzRequiresInMemory && (!hasAggregationFilter || aggregationFilterNative); + // [relation group join] Served only as the driver's own statement: + // the rows path below cannot join. Each planned related read is + // answered at this boundary, under these driver options, by the rule + // the semi-join's leaf is (`plannedRelationLeafVerdict`). + if (relationGroup !== undefined && plannedRelationGroups !== null) { + if (!nativeAggregate) { + declineRelationGroup(relationGroup, `this aggregate of '${object}' is not one its driver answers natively`); + return []; + } + const joins = relationGroupJoinsAtBoundary(relationGroup, plannedRelationGroups, aggregateOptions); + if (joins === null) return []; + const joined = await drv.aggregate(object, { ...ast, [RELATION_GROUP_JOINS]: joins }, aggregateOptions); + assertRelationGroupRowsJoined(object, drv.name, joined, joins); + relationGroup.outcome = { kind: 'joined' }; + return applyHaving(joined, ast.having, havingColumnClasses); + } + if (nativeAggregate) { // HAVING is engine-owned (#4286): applied AFTER aggregation, over // the aggregated row's own columns (aggregation aliases + groupBy // projections), identically on both paths. No driver implements it diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 7557e0a9da8..8d789a8785f 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5860,6 +5860,7 @@ export class ObjectQL implements IObjectQLEngine { recomputeSummaries: (...a) => engine.recomputeSummaries(...a), rejectCredentialAggregation: (...a) => engine.rejectCredentialAggregation(...a), get relatedSchemaOf() { return engine.relatedSchemaOf; }, + relationSemiJoinServes: (...a) => engine.relationSemiJoinServes(...a), releaseSecretHandles: (...a) => engine.releaseSecretHandles(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), resolveWhereTokens: (...a) => engine.resolveWhereTokens(...a), diff --git a/packages/objectql/src/relation-group-join.ts b/packages/objectql/src/relation-group-join.ts new file mode 100644 index 00000000000..f95723674a0 --- /dev/null +++ b/packages/objectql/src/relation-group-join.ts @@ -0,0 +1,378 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * An aggregate grouped by an attribute of a RELATED record, served as ONE + * statement on the SQL family: `engine.aggregate('line', …)` grouped by + * `opportunity.stage` reaches the driver as + * `… FROM line LEFT JOIN (SELECT id, stage FROM opportunity WHERE AND ) p ON line.opportunity + * = p.id GROUP BY p.stage, `, with no id list read first and no + * bound-parameter ceiling, however many related records the rows point at. + * + * ## An engine-internal option, never a wire key + * + * The request rides on {@link RELATION_GROUP_BY}, a symbol-keyed READ option + * (the `EngineReadOptions` third argument of `aggregate`): no wire request, + * JSON body or spread author input can carry a symbol, so the public + * `groupBy` vocabulary is unchanged — a dotted `groupBy` entry is still + * refused at its door. The one in-repo caller is `@objectstack/service-analytics` + * (`ObjectQLStrategy`), through its plugin's engine bridge; it is a + * `Symbol.for` key because that package does not depend on this one at + * runtime. Holding the key grants nothing: the engine plans the related read + * itself, as the caller, below. + * + * ## How the related half is built: the related object's own read, planned + * + * Exactly as the nested-relation semi-join builds its subquery + * (`relation-semi-join.ts`, {@link RELATION_SCOPE_PLAN}): the related read is + * this engine's own `aggregate` on the related object, under the caller's + * context, grouped by `id` and the attributes — the read the FK-expand ran + * (`ObjectQLStrategy#resolveFkAttr`), minus its id list. Its CRUD gate, every + * read middleware (row scope, the field-level gate on a grouped field), its + * group-by doors (a virtual or JSON attribute is refused in the related + * object's words) all run. At the driver call the read is PLANNED, not run: + * its final `where` and driver options are captured, and a + * `ReadableIds` leaf carries them ({@link planRelationSemiJoinLeaf}). At the + * outer read's executor boundary the leaf is answered by + * {@link plannedRelationLeafVerdict} — the one rule that says when a planned + * scope is the related read's own statement — and handed to the driver + * composed. ⛔ No second copy of the read-scope composition lives here + * (ADR-0139 D6): the scope is whatever the related read's own pipeline put + * on its driver call. + * + * ## What the driver answers + * + * Per relation, the driver ({@link RELATION_GROUP_JOINS} on the AST) joins the + * related rows the composed leaf admits — tenant-walled with the outer read's + * options (ADR-0139 D3), which {@link plannedRelationLeafVerdict} has proved + * are the related read's own — and groups by each attribute under its alias, + * plus a `resolvedAlias` column: `1` when a readable related record joined, + * `0` when none did (the relation is empty, or names a record the caller + * cannot read, or one that does not exist). The attribute of an unresolved + * group is `NULL`; the caller tells it from a real `NULL` attribute by the + * resolved column, and so keeps its "restricted" bucket exactly. + * + * ## Declined, never half-served + * + * Every case this module cannot prove is the same read as the FK-expand's is + * DECLINED: the engine runs nothing more and writes the reason to the + * request's `outcome`, and the caller serves the dimension the way it always + * has. Declined before anything is read when the registry already answers — + * a driver outside {@link RELATION_GROUP_JOIN_COMPILING_DRIVERS} (memory keeps + * its in-process FK-expand; MongoDB and OData keep theirs), a federated + * object, a field that is not a single-valued relation to the named object, + * or a related object `relationSemiJoinServes` keeps the id read for; and + * after planning, when the related read was not provably one planned + * statement, when the outer read's driver options are not the related read's + * own, or when the aggregate itself is not one the driver answers natively + * (a bucket it cannot compute, a non-UTC zone, a measure filter it does not + * compile). A request the caller built wrong (a duplicate or colliding + * column) is a server fault, `INTERNAL_ERROR` / 500. + */ + +import { + isMultiValueField, + referenceTargetOf, + ReadableIds, + type ComposedReadableIds, + type FilterCondition, +} from '@objectstack/spec/data'; +import { readableIdsRefusalError } from './filter-comparand-shape.js'; +import { isFederatedObject } from './federated-object.js'; +import { + planRelationSemiJoinLeaf, + plannedRelationLeafVerdict, + RELATION_SCOPE_PLAN, + type RelationScopePlan, +} from './relation-semi-join.js'; + +/** + * The read-option key of a relation group request: `aggregate(object, query, + * { [RELATION_GROUP_BY]: request })`. A `Symbol.for` key — its one caller + * lives in a package that does not import this one — and a symbol, so no wire + * request can carry it. + */ +export const RELATION_GROUP_BY: unique symbol = Symbol.for('objectstack.objectql.relationGroupBy'); + +/** + * The AST key the driver reads its relation joins from + * ({@link DriverRelationGroupJoin}); `driver-sql`'s aggregate compiler reads + * the same `Symbol.for` key. Set by the engine on the composed AST it hands + * `driver.aggregate`, after every middleware has run — no middleware and no + * caller sees it. + */ +export const RELATION_GROUP_JOINS: unique symbol = Symbol.for('objectstack.driver.aggregate.relationGroupJoins'); + +/** One related attribute grouped through a relation, and the column it answers under. */ +export interface RelationGroupAttribute { + /** A stored field of the related object (`id` included). */ + readonly attr: string; + /** The output column of the aggregated row. */ + readonly alias: string; +} + +/** One relation of a {@link RelationGroupByRequest}. */ +export interface RelationGroupBy { + /** A single-valued relation field (`lookup` / `master_detail`) of the aggregated object. */ + readonly field: string; + /** The object `field` references — the request's own reading of it; a mismatch declines. */ + readonly object: string; + /** A condition the related read applies beside its own read scope (the caller's policy filter). */ + readonly where?: FilterCondition; + readonly attrs: readonly RelationGroupAttribute[]; + /** The output column that says whether a readable related record joined (`1`) or not (`0`). */ + readonly resolvedAlias: string; +} + +/** What the engine did with a {@link RelationGroupByRequest}. */ +export type RelationGroupOutcome = + | { readonly kind: 'joined' } + | { readonly kind: 'declined'; readonly reason: string }; + +/** + * The request: the relations to group by, and the slot the engine writes its + * {@link RelationGroupOutcome} to. The aggregate's answer is grouped by the + * relations only when the outcome is `joined`; on `declined` it is `[]` and + * is not an answer. + */ +export interface RelationGroupByRequest { + readonly relations: readonly RelationGroupBy[]; + outcome?: RelationGroupOutcome; +} + +/** What the driver is handed per relation, on the AST under {@link RELATION_GROUP_JOINS}. */ +export interface DriverRelationGroupJoin { + readonly field: string; + /** + * The related rows the caller may read, as a composed leaf the driver + * compiles exactly as it compiles a `ReadableIds` subquery (tenant wall + * from the outer read's options). `null` when the planned scope is the deny + * sentinel: no related record is readable, every group is unresolved. + */ + readonly parent: ComposedReadableIds | null; + readonly attrs: readonly RelationGroupAttribute[]; + readonly resolvedAlias: string; +} + +/** + * The drivers whose `aggregate` compiles {@link RELATION_GROUP_JOINS}. Named, + * as `relation-semi-join.ts` names the semi-join compilers: no + * capability bit says which drivers compile it, and an unnamed driver is + * never handed one. The Turso driver is not named: its remote transport + * compiles its own aggregates and would not read the joins. + */ +export const RELATION_GROUP_JOIN_COMPILING_DRIVERS: ReadonlySet = new Set([ + 'com.objectstack.driver.sql', + 'com.objectstack.driver.sqlite-wasm', +]); + +/** The request on a read's options, when one rides there. */ +export function relationGroupByRequestOf(options: unknown): RelationGroupByRequest | undefined { + if (options === null || typeof options !== 'object') return undefined; + const request = (options as Record)[RELATION_GROUP_BY]; + return request === undefined ? undefined : (request as RelationGroupByRequest); +} + +/** Records a decline on the request and answers `null`. */ +export function declineRelationGroup(request: RelationGroupByRequest, reason: string): null { + request.outcome = { kind: 'declined', reason }; + return null; +} + +/** A request the caller built wrong: our own plumbing, a server fault. */ +function malformed(object: string, detail: string): Error { + return readableIdsRefusalError( + object, + `aggregate('${object}'): the engine-internal relation group request is malformed: ${detail}. ` + + 'The query was NOT run and no driver was asked.', + ); +} + +/** + * Judge the request's SHAPE against the query's own output columns — every + * alias and resolved column distinct from each other and from the `groupBy` + * columns and aggregation aliases — and throw on a request built wrong. + */ +export function assertRelationGroupRequestShape( + object: string, + request: RelationGroupByRequest, + outputColumns: Iterable, +): void { + if (!Array.isArray(request.relations) || request.relations.length === 0) { + throw malformed(object, 'it names no relation'); + } + const taken = new Set(outputColumns); + const claim = (column: unknown, what: string): void => { + if (typeof column !== 'string' || column === '') throw malformed(object, `${what} is not a column name`); + if (taken.has(column)) throw malformed(object, `${what} '${column}' names a column the aggregated row already has`); + taken.add(column); + }; + const fields = new Set(); + for (const relation of request.relations) { + if (typeof relation?.field !== 'string' || fields.has(relation.field)) { + throw malformed(object, `relation '${String(relation?.field)}' is named twice or is not a field name`); + } + fields.add(relation.field); + if (!Array.isArray(relation.attrs) || relation.attrs.length === 0) { + throw malformed(object, `relation '${relation.field}' groups by no attribute`); + } + const attrs = new Set(); + for (const a of relation.attrs) { + if (typeof a?.attr !== 'string' || a.attr === '' || attrs.has(a.attr)) { + throw malformed(object, `relation '${relation.field}' names attribute '${String(a?.attr)}' twice or not at all`); + } + attrs.add(a.attr); + claim(a.alias, `the alias of '${relation.field}.${a.attr}'`); + } + claim(relation.resolvedAlias, `the resolved column of '${relation.field}'`); + } +} + +/** What {@link relationGroupRegistryDecline} reads off the engine. */ +export interface RelationGroupRegistryHost { + getObjectSchema(object: string): unknown; + getDriver(object: string): { readonly name?: unknown; readonly aggregate?: unknown } | undefined; + /** `relation-semi-join.ts`'s `relationSemiJoinServes`, bound to the engine. */ + relationSemiJoinServes(object: string, target: string): boolean; +} + +/** + * The registry half of the decline: the reason the request cannot be served + * on this read, or `undefined` when nothing in the registry declines it. + * Nothing is read. + */ +export function relationGroupRegistryDecline( + this: RelationGroupRegistryHost, + object: string, + request: RelationGroupByRequest, +): string | undefined { + const driver = this.getDriver(object); + const name = driver?.name; + if (typeof name !== 'string' || !RELATION_GROUP_JOIN_COMPILING_DRIVERS.has(name) || typeof driver?.aggregate !== 'function') { + return `the driver of '${object}' (${String(name)}) compiles no relation group join`; + } + const schema = this.getObjectSchema(object) as { fields?: Record } | undefined; + if (isFederatedObject(schema)) return `'${object}' is a federated object`; + for (const relation of request.relations) { + const def = schema?.fields?.[relation.field]; + const target = def === undefined ? undefined : referenceTargetOf(def); + if (target === undefined) return `'${object}.${relation.field}' is not a relation field`; + if (isMultiValueField(def as Parameters[0])) { + return `'${object}.${relation.field}' holds a list of ids`; + } + if (target !== relation.object) { + return `'${object}.${relation.field}' references '${target}', not '${relation.object}'`; + } + if (!this.relationSemiJoinServes(object, target)) { + return `a read of '${target}' through '${object}.${relation.field}' is not plannable as one statement`; + } + } + return undefined; +} + +/** One relation, its related read planned. */ +export interface PlannedRelationGroup { + readonly relation: RelationGroupBy; + /** The planned leaf over the related object ({@link planRelationSemiJoinLeaf}). */ + readonly leaf: object; +} + +/** What {@link planRelationGroups} reads off the engine. */ +export interface RelationGroupPlanHost { + /** The engine's own `aggregate`. */ + aggregate(object: string, query: Record, options?: Record): Promise; +} + +/** + * Plan each relation's related read: the related object's own aggregate, + * grouped by `id` and the attributes, as the caller (`context`), stopped at + * its driver call. A refusal from that read propagates — it is the refusal + * the FK-expand's read gave. Answers `null`, having recorded the decline, + * when a read is not provably one planned statement. + */ +export async function planRelationGroups( + this: RelationGroupPlanHost, + request: RelationGroupByRequest, + context: unknown, +): Promise { + const planned: PlannedRelationGroup[] = []; + for (const relation of request.relations) { + // `id` is the key already: naming it twice is a groupBy the engine refuses. + const groupBy = ['id', ...relation.attrs.map((a) => a.attr).filter((attr) => attr !== 'id')]; + const leaf = await planRelationSemiJoinLeaf( + relation.object, + (plan: RelationScopePlan) => this.aggregate( + relation.object, + { + ...(relation.where !== undefined ? { where: relation.where } : {}), + groupBy, + aggregations: [{ function: 'count', field: 'id', alias: '_c' }], + ...(context !== undefined ? { context } : {}), + }, + { [RELATION_SCOPE_PLAN]: plan }, + ), + // Never read: a planned leaf whose verdict is `read` is declined below. + () => Promise.resolve([]), + ); + if (leaf === null) { + return declineRelationGroup(request, `the read of '${relation.object}' is not provably one planned statement`); + } + planned.push({ relation, leaf }); + } + return planned; +} + +/** + * The executor boundary's answer for the planned relations, in a read whose + * driver is handed `outerDriverOptions`: the joins the driver compiles, or + * `null` (the decline recorded) when a planned scope is not the related + * read's own statement under these options. + */ +export function relationGroupJoinsAtBoundary( + request: RelationGroupByRequest, + planned: readonly PlannedRelationGroup[], + outerDriverOptions: unknown, +): DriverRelationGroupJoin[] | null { + const joins: DriverRelationGroupJoin[] = []; + for (const { relation, leaf } of planned) { + const verdict = plannedRelationLeafVerdict(leaf, outerDriverOptions); + if (verdict === undefined || verdict.kind === 'read') { + return declineRelationGroup( + request, + `the read of '${relation.object}' was planned under driver options this read does not carry`, + ); + } + joins.push({ + field: relation.field, + parent: verdict.kind === 'compose' ? ReadableIds.compose(leaf as ReadableIds, verdict.scope) : null, + attrs: relation.attrs, + resolvedAlias: relation.resolvedAlias, + }); + } + return joins; +} + +/** + * The driver's answer, checked: every row carries each relation's resolved + * column. A row without it is a driver that did not compile the joins it was + * handed — grouped by something else, so never an answer. + */ +export function assertRelationGroupRowsJoined( + object: string, + driverName: unknown, + rows: unknown, + joins: readonly DriverRelationGroupJoin[], +): void { + if (!Array.isArray(rows)) return; + for (const row of rows) { + for (const join of joins) { + if (row === null || typeof row !== 'object' || !(join.resolvedAlias in (row as object))) { + throw readableIdsRefusalError( + object, + `aggregate('${object}'): the driver ${String(driverName)} answered a relation group join without its ` + + `'${join.resolvedAlias}' column, so it did not compile the join it was handed. The answer was discarded.`, + ); + } + } + } +} From 60d7ff8a386ed54405afe129bc0dec947ad9c801 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:41:16 +0000 Subject: [PATCH 2/9] wip: driver-sql relation group join compile; analytics routes cross-object dims through it Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .../driver-sql/src/sql-driver-aggregation.ts | 116 +++++++++- .../src/analytics-service.ts | 12 + .../services/service-analytics/src/plugin.ts | 61 ++++- .../src/strategies/objectql-strategy.ts | 219 ++++++++++++++---- .../service-analytics/src/strategies/types.ts | 42 ++++ 5 files changed, 397 insertions(+), 53 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index e4522620fb2..1e090caea42 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -29,9 +29,9 @@ */ import { coreSqlDialectOf } from './sql-driver-oracle-dialect.js'; -import { emptyGroupValueFor } from '@objectstack/spec/data'; +import { emptyGroupValueFor, isComposedReadableIds } from '@objectstack/spec/data'; import type { Knex } from 'knex'; -import type { DriverOptions } from '@objectstack/spec/data'; +import type { ComposedReadableIds, DriverOptions } from '@objectstack/spec/data'; import type { DriverQuery } from '@objectstack/spec/contracts'; import { AGGREGATE_ACCUMULATION, AGGREGATE_ANSWER_KIND, aggregandOperandSql } from '@objectstack/core'; import type { AggregandColumnClass } from '@objectstack/core'; @@ -79,6 +79,10 @@ export interface AggregationHost { export class AggregationFacet { /** The body of `SqlDriver#aggregate`; the method's docblock there is its contract. */ static async aggregate(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { + // [relation group join] The related rows each relation joins, handed by + // the engine (`objectql` `relation-group-join.ts`); read once, judged + // before anything compiles. + const relationJoins = relationGroupJoinsOf(query); // [#33698] The per-measure `filter`s that carry a condition (`{}` is the // vacuous filter, same convention as `where` / `having`): each compiles // with the where compiler below, so each is primed and read like a `where`. @@ -95,6 +99,13 @@ export class AggregationFacet { // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from // the remote catalog before a comparand or a written value is bound. if (this.isOracle) await this.primeOracleRawUuidColumns(object); + // …and the same two primes for each joined related object, whose scope + // compiles against its own table. + for (const join of relationJoins ?? []) { + if (join.parent === null) continue; + if (this.isMssql) await this.primeMssqlGuidColumns(join.parent.object, join.parent.scope); + if (this.isOracle) await this.primeOracleRawUuidColumns(join.parent.object); + } const builder = this.getBuilder(object, options); // The column a FIELD names in this statement: its `external.columnMap` // remote column on a federated object, the field itself otherwise. Every @@ -240,6 +251,61 @@ export class AggregationFacet { } } + // [relation group join] Each relation the engine hands joins the related + // rows the caller may read, and groups by their attributes: + // + // LEFT JOIN (SELECT id AS __rgN_id, attr AS __rgN_aJ … FROM related + // WHERE AND ) AS __rgN + // ON fk = __rgN.__rgN_id + // … GROUP BY __rgN.__rgN_aJ, CASE WHEN __rgN.__rgN_id IS NULL THEN 0 ELSE 1 END + // + // The derived table is compiled as a composed `ReadableIds` subquery is + // (`readableIdsSubquery`): the related object's tenant wall from THIS + // read's options (ADR-0139 D3 — the engine proved them the related read's + // own) and its composed scope through this same where compiler, so it + // binds only the scope's and the wall's own parameters, never one per + // related record. Its columns are renamed so no column of the + // aggregated table is ambiguous beside them; the join's left column is + // the FK, unqualified, for the same reason. `__rgN_id` is unique in the + // derived table (it is the key), so the join multiplies no row and every + // measure aggregates the rows it would have without it. The resolved + // column is `1` where a readable related record joined, `0` where none + // did (an empty relation, or a record the caller cannot read) — the + // attribute is NULL there, and the resolved column tells it from a real + // NULL. A `null` parent is a related object nothing is readable of. + (relationJoins ?? []).forEach((join, i) => { + const at = `__rg${i}`; + const idColumn = `${at}_id`; + if (join.parent === null) { + for (const a of join.attrs) builder.select(this.knex.raw(`NULL as ${this.aliasIdentifierSql(a.alias)}`)); + builder.select(this.knex.raw(`0 as ${this.aliasIdentifierSql(join.resolvedAlias)}`)); + presentedOutput.set(join.resolvedAlias, 'number'); + return; + } + const related = join.parent.object; + const sub = this.getBuilder(related).select( + this.knex.raw(`?? as ${this.aliasIdentifierSql(idColumn)}`, [this.remoteColumn(related, 'id', 'id')]), + ); + join.attrs.forEach((a, j) => { + sub.select(this.knex.raw(`?? as ${this.aliasIdentifierSql(`${at}_a${j}`)}`, [this.remoteColumn(related, a.attr, a.attr)])); + }); + this.applyTenantScope(sub, related, options); + if (join.parent.scope !== undefined) this.applyFilters(sub, join.parent.scope, options); + const relatedTable = this.coercionKey(sub); + builder.leftJoin(sub.as(at), columnOf(join.field), `${at}.${idColumn}`); + join.attrs.forEach((a, j) => { + const ref = `${at}.${at}_a${j}`; + builder.groupBy(ref); + builder.select(this.knex.raw(`?? as ${this.aliasIdentifierSql(a.alias)}`, [ref])); + const kind = this.readPresentationKind(relatedTable, a.attr); + if (kind) presentedOutput.set(a.alias, kind); + }); + const resolved = 'CASE WHEN ?? IS NULL THEN 0 ELSE 1 END'; + builder.groupByRaw(resolved, [`${at}.${idColumn}`]); + builder.select(this.knex.raw(`${resolved} as ${this.aliasIdentifierSql(join.resolvedAlias)}`, [`${at}.${idColumn}`])); + presentedOutput.set(join.resolvedAlias, 'number'); + }); + // [#6321] Was `query.aggregations || query.aggregate` / `agg.function || // agg.func`. Neither `aggregate` nor `func` is declared anywhere in the // Query Protocol — `QueryASTSchema` declares `aggregations` and @@ -457,6 +523,52 @@ export class AggregationFacet { } } +/** + * [relation group join] The AST key the engine hands its relation joins on + * (`objectql` `relation-group-join.ts`, the same `Symbol.for` key — this + * package does not import the engine). A symbol, so no wire request and no + * JSON query can carry one; set by the engine after every middleware ran. + */ +export const RELATION_GROUP_JOINS: unique symbol = Symbol.for('objectstack.driver.aggregate.relationGroupJoins'); + +/** One relation join, as the engine hands it. */ +export interface RelationGroupJoin { + /** The single-valued relation (FK) column of the aggregated object. */ + readonly field: string; + /** The related rows the caller may read, composed by the engine; `null` = none. */ + readonly parent: ComposedReadableIds | null; + readonly attrs: ReadonlyArray<{ readonly attr: string; readonly alias: string }>; + /** The output column: `1` where a readable related record joined, `0` where none did. */ + readonly resolvedAlias: string; +} + +/** + * The joins on `query`, or `undefined` when it carries none. A parent that is + * not a leaf the engine composed is refused before anything compiles, as an + * uncomposed `ReadableIds` leaf is: its scope is the only thing that bounds + * the joined rows, and ⛔ a scope the engine did not compose is never read as + * one. + */ +function relationGroupJoinsOf(query: DriverQuery): readonly RelationGroupJoin[] | undefined { + const joins = (query as unknown as Record)[RELATION_GROUP_JOINS]; + if (joins === undefined) return undefined; + const ok = Array.isArray(joins) && joins.every((j: RelationGroupJoin) => + j !== null && typeof j === 'object' + && typeof j.field === 'string' + && (j.parent === null || isComposedReadableIds(j.parent)) + && Array.isArray(j.attrs) && j.attrs.every((a) => typeof a?.attr === 'string' && typeof a?.alias === 'string') + && typeof j.resolvedAlias === 'string'); + if (!ok) { + const err = new Error( + 'aggregate: a relation group join the engine did not compose was refused; the query was NOT run.', + ) as Error & { code?: string; status?: number }; + err.code = 'INTERNAL_ERROR'; + err.status = 500; + throw err; + } + return joins as readonly RelationGroupJoin[]; +} + /** * The aggregate operand on SQL Server — the two `@objectstack/core` operand * policies (`aggregandOperandSql`), restated for the one dialect that policy diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 9dd5c474235..54751d6ebe5 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -1346,6 +1346,15 @@ export interface AnalyticsServiceConfig { * told once, at construction, when it also wires `executeRawSql`. */ hasObjectMiddleware?: (objectName: string) => boolean | undefined; + /** + * The data engine's aggregate grouped also by related records' attributes, + * which a SQL driver answers as one `LEFT JOIN … GROUP BY`. See + * `DatasetScopedStrategyContext.executeRelationGroupAggregate` + * (`strategies/types.ts`). `AnalyticsServicePlugin` wires it only when it + * bridges `executeAggregate` itself, to the same engine; a host that wires + * nothing serves every cross-object dimension by the FK-expand, as before. + */ + executeRelationGroupAggregate?: DatasetScopedStrategyContext['executeRelationGroupAggregate']; /** Pre-defined datasets to compile + register at construction (ADR-0021). */ datasets?: Dataset[]; /** @@ -1748,6 +1757,9 @@ export class AnalyticsService implements IAnalyticsService { // `NativeSQLStrategy` declines on `true` and on `undefined`, so the // engine path serves the object and its middlewares run. hasObjectMiddleware: config.hasObjectMiddleware, + // The engine's relation group join, passed through untouched; absent, + // `ObjectQLStrategy` serves a cross-object dimension by its FK-expand. + executeRelationGroupAggregate: config.executeRelationGroupAggregate, }; // [#21080] …and a host that wires raw SQL without that answer is told so, // once: the native path then serves every object, gated ones included. diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index 78f448fbcf4..dfb07badb09 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -59,6 +59,17 @@ import { asAcceptedSqlDialect, type AcceptedSqlDialect } from './text-match-sql. * the auto-bridge probes it the same way. So is `hasObjectMiddleware` * (#21080), whose absence the bridge below reads as "cannot say". */ +/** One bridged `executeAggregate` call's input (the plugin option's own declaration). */ +type BridgedAggregateInput = Parameters>[1]; + +/** + * [relation group join] The data engine's read-option key for a relation + * group request: objectql's `RELATION_GROUP_BY` (`relation-group-join.ts`), + * the same `Symbol.for` key — this package does not import the engine at + * runtime. A symbol, so no wire request can carry one. + */ +const RELATION_GROUP_BY: unique symbol = Symbol.for('objectstack.objectql.relationGroupBy'); + type DataEngineLike = Pick & Partial> @@ -369,6 +380,7 @@ export class AnalyticsServicePlugin implements Plugin { // `new AnalyticsServicePlugin({ cubes })` // without re-implementing the bridge in every app. let executeAggregate = this.options.executeAggregate; + let executeRelationGroupAggregate: AnalyticsServiceConfig['executeRelationGroupAggregate']; let autoBridged = false; // [#19995, ruling C] The engine's judge-only `where` admission, filled below // ONLY when this plugin bridges `executeAggregate` itself, and then to the @@ -393,15 +405,9 @@ export class AnalyticsServicePlugin implements Plugin { 'will retry per-query. Register ObjectQLPlugin or pass executeAggregate.', ); } - executeAggregate = async (objectName, { groupBy, aggregations, filter, timezone, context }) => { - const engine = tryGetDataEngine(); - if (!engine) { - throw new Error( - '[Analytics] Cannot execute aggregate: no IDataEngine ("data") service is registered. ' + - 'Add ObjectQLPlugin to the kernel or supply AnalyticsServicePlugin({ executeAggregate }).', - ); - } - const rows = await engine.aggregate(objectName, { + // The engine's own query for one bridged call — the shape both the + // aggregate below and its relation group twin hand the engine. + const engineAggregateQuery = ({ groupBy, aggregations, filter, timezone, context }: BridgedAggregateInput) => ({ where: filter, groupBy, // [#10413 phase 2 / #10576] `a.filter` is the per-aggregation @@ -471,8 +477,42 @@ export class AnalyticsServicePlugin implements Plugin { // engine with no principal and plugin-security fell open (#3597). context, }); + const requireDataEngine = (): DataEngineLike => { + const engine = tryGetDataEngine(); + if (!engine) { + throw new Error( + '[Analytics] Cannot execute aggregate: no IDataEngine ("data") service is registered. ' + + 'Add ObjectQLPlugin to the kernel or supply AnalyticsServicePlugin({ executeAggregate }).', + ); + } + return engine; + }; + executeAggregate = async (objectName, input) => { + const rows = await requireDataEngine().aggregate(objectName, engineAggregateQuery(input)); return rows as Record[]; }; + // [relation group join] …and the same aggregate grouped also by related + // records' attributes, which a SQL driver answers as one `LEFT JOIN … + // GROUP BY` (objectql `relation-group-join.ts`). The request rides on a + // symbol-keyed READ option, so no wire request can carry it; the engine + // writes back whether it joined, and on a decline `ObjectQLStrategy` + // serves the dimension by its FK-expand. Same engine as the executor + // above, by construction. + executeRelationGroupAggregate = async (objectName, input, relations) => { + const request: { relations: typeof relations; outcome?: { kind: string; reason?: string } } = { relations }; + const engine = requireDataEngine(); + const aggregate = engine.aggregate as unknown as ( + object: string, query: unknown, options: Record, + ) => Promise; + const rows = await aggregate.call(engine, objectName, engineAggregateQuery(input), { + [RELATION_GROUP_BY]: request, + }); + if (request.outcome?.kind === 'joined') return { joined: true, rows: rows as Record[] }; + return { + joined: false, + reason: request.outcome?.reason ?? 'the "data" engine does not serve a relation group join', + }; + }; autoBridged = true; // [#19995, ruling C] …and the judge, resolved per call through the same @@ -1553,6 +1593,9 @@ export class AnalyticsServicePlugin implements Plugin { // [#19995, ruling C] The executing engine's own `where` admission — see // `judgeFilter` beside the `executeAggregate` auto-bridge above. judgeFilter, + // [relation group join] The executing engine's relation group join — + // see beside the `executeAggregate` auto-bridge above. + executeRelationGroupAggregate, // [#21080] The data engine's per-object middleware answer — see // `hasObjectMiddleware` above. Wired whoever executes raw SQL: the // middlewares live in the engine either way. diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index eeae9e160c9..1c2d52ad124 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -6,7 +6,7 @@ import type { AggregationFunction, Cube } from '@objectstack/spec/data'; // two merge boundaries that stamp it. import { markFilterSubtreeProvenance } from '@objectstack/spec/data'; import { StandardErrorCode } from '@objectstack/spec/api'; -import type { AnalyticsStrategy, StrategyContext, DatasetScopedStrategyContext } from './types.js'; +import type { AnalyticsStrategy, StrategyContext, DatasetScopedStrategyContext, RelationGroupAggregateRelation } from './types.js'; import { assertDatasetGroupColumnsDistinct } from '../dataset-group-column-door.js'; import { assertDatasetDateBucketsTemporal, assertDatasetGroupTargetsStored } from '../dataset-date-bucket-door.js'; import { @@ -1728,37 +1728,19 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // [#28798] The dataset refusal for a column asked twice, as on the direct path. assertDatasetGroupColumnsDistinct(baseObject, groupBy, query, (m) => this.resolveFieldName(cube, m, 'dimension')); - // Base aggregate, grouped by the FK, scoped to the base object. Threads the - // ExecutionContext for the engine-side second belt too (#3602). - const baseRows = await ctx.executeAggregate!(baseObject, { - groupBy: groupBy.length > 0 ? (groupBy as unknown as string[]) : undefined, - aggregations: aggregations.length > 0 ? aggregations : undefined, - filter: this.withReadScope(baseObject, filter, ctx), - timezone: query.timezone, - context: ctx.context, - }); - - // [#29304] A cross-object dimension over a virtual attribute, whether or - // not a base row carries a key to resolve. See {@link assertCrossObjectAttrsStored}. - assertCrossObjectAttrsStored(plan, ctx); - - // Resolve each cross-object dim's FK → attribute, SCOPED to the referenced - // object: a related record the caller cannot read never yields its - // attribute, so it buckets as RESTRICTED (no leak; ADR-0021 D-C / #3602). - const resolvedDims: CrossObjectDim[] = []; - for (const cd of plan.crossDims) { - const fkValues = [...new Set(baseRows.map((r) => r[cd.fkField]).filter((v) => v != null))]; - const fkToAttr = await this.resolveFkAttr(cd.refObject, cd.attr, fkValues, ctx); - resolvedDims.push({ outputName: cd.outputName, fkField: cd.fkField, fkToAttr }); - } - const measures: MeasureRecombine[] = (query.measures ?? []).map((m) => ({ alias: m, // planCrossObject already asserted every measure is recombinable. method: this.resolveMeasureAggregation(cube, m).method as RecombinableMethod, })); - const merged = rebucketCrossObject(baseRows, baseDimFields, resolvedDims, measures); + // [relation group join] On a driver that compiles it, one statement: the + // base aggregate LEFT JOINs each related object's readable rows and + // groups by the attribute itself — no id list, no bind-parameter ceiling. + // `null` when the host cannot run it or the engine declined: the + // FK-expand below serves the dimension as it always has. + const joined = await this.executeCrossObjectJoined(baseObject, plan, groupBy, baseDimFields, aggregations, filter, query, measures, ctx); + const merged = joined ?? await this.executeCrossObjectExpanded(baseObject, plan, groupBy, baseDimFields, aggregations, filter, query, measures, ctx); // Map resolved group keys back to the caller's dimension names. const mappedRows = merged.map((row) => { @@ -1786,6 +1768,148 @@ export class ObjectQLStrategy implements AnalyticsStrategy { return { rows: this.orderAndWindow(query, mappedRows), fields: this.buildFieldMeta(query, cube) }; } + /** + * [relation group join] Serve the cross-object dimensions as ONE aggregate + * the engine compiles to `LEFT JOIN … GROUP BY` (objectql + * `relation-group-join.ts`), through + * {@link DatasetScopedStrategyContext.executeRelationGroupAggregate}. + * + * The related read is the FK-expand's own, minus its id list: the related + * object's read scope ({@link relatedReadScope}, judged and marked exactly + * as {@link resolveFkAttr} judges it) is the condition the engine's planned + * read of that object applies beside its own pipeline. Each row comes back + * with the attribute and a resolved column; a row no readable related + * record joined buckets as RESTRICTED, exactly as an id the FK-expand's read + * did not return — the rows go through the same {@link rebucketCrossObject}, + * keyed per row, so the buckets and their measures are the FK-expand's. + * + * `null` — serve by the FK-expand — when the host wired no such hook or the + * engine declined (a driver that compiles no join: memory, MongoDB, OData; + * a read it cannot prove is one statement). + */ + private async executeCrossObjectJoined( + baseObject: string, + plan: CrossObjectPlan, + groupBy: AggregateGroupKey[], + baseDimFields: string[], + aggregations: Array<{ field: string; method: AggregationFunction; alias: string; filter?: Record }>, + filter: Record, + query: AnalyticsQuery, + measures: MeasureRecombine[], + ctx: StrategyContext, + ): Promise[] | null> { + const run = (ctx as DatasetScopedStrategyContext).executeRelationGroupAggregate; + if (typeof run !== 'function') return null; + + // [#29304] A virtual attribute is refused in the dataset door's words + // before the engine is asked, as the FK-expand refuses it. + assertCrossObjectAttrsStored(plan, ctx); + + // One relation per FK column, each attribute under its own column. + const relations: Array<{ field: string; object: string; where?: Record; attrs: Array<{ attr: string; alias: string }>; resolvedAlias: string }> = []; + const columnOf = new Map(); + for (const cd of plan.crossDims) { + let index = relations.findIndex((r) => r.field === cd.fkField); + if (index === -1) { + index = relations.length; + const where = this.relatedReadScope(cd.refObject, ctx); + relations.push({ + field: cd.fkField, + object: cd.refObject, + ...(where !== undefined ? { where } : {}), + attrs: [], + resolvedAlias: `__rg${index}_resolved`, + }); + } + const relation = relations[index]!; + let attr = relation.attrs.find((a) => a.attr === cd.attr); + if (!attr) { + attr = { attr: cd.attr, alias: `__rg${index}_a${relation.attrs.length}` }; + relation.attrs.push(attr); + } + columnOf.set(cd.outputName, { relation: index, alias: attr.alias }); + } + + // The base group keys without the FK columns the joins replace — a FK + // column a base dimension names itself (`account` beside `account.name`) + // stays. + const replaced = new Set(relations.map((r) => r.field).filter((f) => !baseDimFields.includes(f))); + const joinGroupBy = groupBy.filter((g) => typeof g !== 'string' || !replaced.has(g)); + + const answer = await run.call(ctx, baseObject, { + groupBy: joinGroupBy.length > 0 ? (joinGroupBy as unknown as string[]) : undefined, + aggregations: aggregations.length > 0 ? aggregations : undefined, + filter: this.withReadScope(baseObject, filter, ctx), + timezone: query.timezone, + context: ctx.context, + }, relations as readonly RelationGroupAggregateRelation[]); + if (!answer.joined) return null; + + // Each row is one group of the joined statement. Its key for a relation + // is the row itself when a readable related record joined, and absent + // (RESTRICTED) when none did — the FK-expand's map, one entry per row. + const keyOf = (relation: number): string => `__rg${relation}_key`; + const rows = answer.rows.map((row, i) => { + const keyed: Record = { ...row }; + relations.forEach((r, index) => { + keyed[keyOf(index)] = Number(row[r.resolvedAlias]) === 1 ? i : null; + }); + return keyed; + }); + const resolvedDims: CrossObjectDim[] = plan.crossDims.map((cd) => { + const { relation, alias } = columnOf.get(cd.outputName)!; + const fkToAttr = new Map(); + rows.forEach((row, i) => { + if (row[keyOf(relation)] === i) fkToAttr.set(i, row[alias]); + }); + return { outputName: cd.outputName, fkField: keyOf(relation), fkToAttr }; + }); + return rebucketCrossObject(rows, baseDimFields, resolvedDims, measures); + } + + /** + * Serve the cross-object dimensions by FK-expand (#3654): the base aggregate + * grouped by each FK column, each FK resolved to its attribute by a scoped + * read of the referenced object ({@link resolveFkAttr}), re-bucketed here. + */ + private async executeCrossObjectExpanded( + baseObject: string, + plan: CrossObjectPlan, + groupBy: AggregateGroupKey[], + baseDimFields: string[], + aggregations: Array<{ field: string; method: AggregationFunction; alias: string; filter?: Record }>, + filter: Record, + query: AnalyticsQuery, + measures: MeasureRecombine[], + ctx: StrategyContext, + ): Promise[]> { + // Base aggregate, grouped by the FK, scoped to the base object. Threads the + // ExecutionContext for the engine-side second belt too (#3602). + const baseRows = await ctx.executeAggregate!(baseObject, { + groupBy: groupBy.length > 0 ? (groupBy as unknown as string[]) : undefined, + aggregations: aggregations.length > 0 ? aggregations : undefined, + filter: this.withReadScope(baseObject, filter, ctx), + timezone: query.timezone, + context: ctx.context, + }); + + // [#29304] A cross-object dimension over a virtual attribute, whether or + // not a base row carries a key to resolve. See {@link assertCrossObjectAttrsStored}. + assertCrossObjectAttrsStored(plan, ctx); + + // Resolve each cross-object dim's FK → attribute, SCOPED to the referenced + // object: a related record the caller cannot read never yields its + // attribute, so it buckets as RESTRICTED (no leak; ADR-0021 D-C / #3602). + const resolvedDims: CrossObjectDim[] = []; + for (const cd of plan.crossDims) { + const fkValues = [...new Set(baseRows.map((r) => r[cd.fkField]).filter((v) => v != null))]; + const fkToAttr = await this.resolveFkAttr(cd.refObject, cd.attr, fkValues, ctx); + resolvedDims.push({ outputName: cd.outputName, fkField: cd.fkField, fkToAttr }); + } + + return rebucketCrossObject(baseRows, baseDimFields, resolvedDims, measures); + } + /** * Resolve `fkValues` (ids of `refObject`) to their `attr` values, applying the * referenced object's OWN read scope (#3654 / #3602). Reuses the aggregate @@ -1801,10 +1925,34 @@ export class ObjectQLStrategy implements AnalyticsStrategy { const map = new Map(); if (fkValues.length === 0 || typeof ctx.executeAggregate !== 'function') return map; const idFilter: Record = { id: { $in: fkValues } }; + const scope = this.relatedReadScope(refObject, ctx); + const filter = scope !== undefined ? { $and: [idFilter, scope] } : idFilter; + const rows = await ctx.executeAggregate(refObject, { + // [#28692] `.id` resolves the FK to the related record's own + // id: `id` is already the key, and naming it twice is a groupBy the + // engine refuses (`INVALID_QUERY`). + groupBy: attr === 'id' ? ['id'] : ['id', attr], + aggregations: [{ field: 'id', method: 'count', alias: '_c' }], + filter, + context: ctx.context, + }); + for (const r of rows) { + if (r.id != null) map.set(r.id, r[attr]); + } + return map; + } + + /** + * The referenced object's OWN read scope, as the related read of a + * cross-object dimension applies it — by FK-expand ({@link resolveFkAttr}) or + * as the engine's planned read of a join ({@link executeCrossObjectJoined}) — + * judged and marked as policy, or `undefined` when there is none. + */ + private relatedReadScope(refObject: string, ctx: StrategyContext): Record | undefined { const scope = typeof ctx.getReadScope === 'function' ? ctx.getReadScope(refObject) : null; // [#8220] Same boundary family as `withReadScope`: the scope arm is policy. - // `idFilter` is this method's own plumbing, not the caller's text — it - // stays unmarked, which withholds, and that is correct for a filter no + // `resolveFkAttr`'s id filter is its own plumbing, not the caller's text — + // it stays unmarked, which withholds, and that is correct for a filter no // author typed. // [#13640] The SECOND engine-bound merge on this strategy, and the same // door: the referenced object's own scope is `$and`-ed into a filter handed @@ -1829,20 +1977,7 @@ export class ObjectQLStrategy implements AnalyticsStrategy { assertReadScopeAdmittedByEngine(scope, refObject, ctx.context, ctx as DatasetScopedStrategyContext); } if (scope != null) markFilterSubtreeProvenance(scope, 'policy'); - const filter = scope != null ? { $and: [idFilter, scope] } : idFilter; - const rows = await ctx.executeAggregate(refObject, { - // [#28692] `.id` resolves the FK to the related record's own - // id: `id` is already the key, and naming it twice is a groupBy the - // engine refuses (`INVALID_QUERY`). - groupBy: attr === 'id' ? ['id'] : ['id', attr], - aggregations: [{ field: 'id', method: 'count', alias: '_c' }], - filter, - context: ctx.context, - }); - for (const r of rows) { - if (r.id != null) map.set(r.id, r[attr]); - } - return map; + return scope != null ? (scope as Record) : undefined; } /** diff --git a/packages/services/service-analytics/src/strategies/types.ts b/packages/services/service-analytics/src/strategies/types.ts index 606fd6a36f0..c8c1711a5d4 100644 --- a/packages/services/service-analytics/src/strategies/types.ts +++ b/packages/services/service-analytics/src/strategies/types.ts @@ -263,4 +263,46 @@ export interface DatasetScopedStrategyContext extends StrategyContext { * it had. */ hasObjectMiddleware?(objectName: string): boolean | undefined; + /** + * The data engine's aggregate of `objectName`, grouped ALSO by attributes of + * related records (one {@link RelationGroupAggregateRelation} per relation), + * which a SQL driver answers as one `LEFT JOIN … GROUP BY` — or `undefined` + * when the host cannot run it (no data engine bridged by this package). + * + * `ObjectQLStrategy` serves a cross-object dimension through it first, and + * by its FK-expand (`resolveFkAttr`, an `id IN (…)` read of the related + * object) only when this is absent or answers `joined: false`: the engine + * declines every read it cannot prove is the FK-expand's own read as one + * statement (a driver that compiles no join — memory, MongoDB, OData — + * among them), before it reads anything the strategy's path reads again. + * + * `AnalyticsServicePlugin` wires it only when it bridges `executeAggregate` + * itself, to the same engine. Declared HERE rather than on the spec's + * {@link StrategyContext} for the reason `getDatasetScope` is: nothing about + * it is an authorable surface. + */ + executeRelationGroupAggregate?( + objectName: string, + options: Parameters>[1], + relations: readonly RelationGroupAggregateRelation[], + ): Promise; +} + +/** One relation a {@link DatasetScopedStrategyContext.executeRelationGroupAggregate} groups through. */ +export interface RelationGroupAggregateRelation { + /** The single-valued relation (FK) field of the aggregated object. */ + readonly field: string; + /** The object it references (the hop the door admitted and scoped). */ + readonly object: string; + /** The caller's read scope of `object`, judged and marked as at `resolveFkAttr`. */ + readonly where?: Record; + /** Each related attribute, and the output column it answers under. */ + readonly attrs: ReadonlyArray<{ readonly attr: string; readonly alias: string }>; + /** The output column: `1` where a readable related record joined, `0` where none did. */ + readonly resolvedAlias: string; } + +/** The engine's answer: the grouped rows, or why it declined (the rows path then serves). */ +export type RelationGroupAggregateAnswer = + | { readonly joined: true; readonly rows: Record[] } + | { readonly joined: false; readonly reason: string }; From 5b695e9b46a7166d4866490b74306b8ec6c32376 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:45:58 +0000 Subject: [PATCH 3/9] wip: tests for the relation group join; changeset Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- .changeset/33664-analytics-lookup-join.md | 16 + .../sql-driver-relation-group-join.test.ts | 151 +++++++++ .../objectql/src/relation-group-join.test.ts | 226 +++++++++++++ .../cross-object-relation-group-join.test.ts | 300 ++++++++++++++++++ 4 files changed, 693 insertions(+) create mode 100644 .changeset/33664-analytics-lookup-join.md create mode 100644 packages/drivers/driver-sql/src/sql-driver-relation-group-join.test.ts create mode 100644 packages/objectql/src/relation-group-join.test.ts create mode 100644 packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts diff --git a/.changeset/33664-analytics-lookup-join.md b/.changeset/33664-analytics-lookup-join.md new file mode 100644 index 00000000000..4b67ee8f994 --- /dev/null +++ b/.changeset/33664-analytics-lookup-join.md @@ -0,0 +1,16 @@ +--- +'@objectstack/objectql': patch +'@objectstack/driver-sql': patch +'@objectstack/service-analytics': patch +--- + +fix(analytics): a dimension through a lookup is one `LEFT JOIN … GROUP BY` on SQL drivers, so it no longer answers 500 past the bind limit + +Clause-②: no +Metadata-protocol: none + +`POST /analytics/query` with a dimension through a lookup (`opportunity.stage` on a line-item cube) answered `500 DATABASE_ERROR` once the rows pointed at more distinct related records than the database binds parameters for: SQLite refused with `too many SQL variables`, PostgreSQL with a bind count overflow. The ObjectQL analytics path grouped the base rows by the foreign key, then read the related object with `id IN (every distinct key)` and re-bucketed the answer in the service. + +On the SQL driver (every dialect, and the WASM SQLite driver) the same query is now one statement. The base aggregate `LEFT JOIN`s the related rows the caller may read and groups by the attribute in the database, with no id list and no bound-parameter ceiling. The related rows are the related object's own aggregate, planned as the caller, the read the old path ran without its id list. Its CRUD gate, read middlewares, row scope and field-level gate all apply, and the tenant wall bounds the joined table. A line whose related record is missing, unreadable, in another tenant or not set still counts under `(restricted)`, as before. Every bucket and measure is the one the old path answered. + +The request is an engine-internal read option, so nothing a client sends changes and the public `groupBy` still refuses a dotted path. The in-memory driver, MongoDB, OData and Turso keep the old path for this dimension, unchanged. diff --git a/packages/drivers/driver-sql/src/sql-driver-relation-group-join.test.ts b/packages/drivers/driver-sql/src/sql-driver-relation-group-join.test.ts new file mode 100644 index 00000000000..7c15edef858 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-relation-group-join.test.ts @@ -0,0 +1,151 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [relation group join] `aggregate()` compiles the relation joins the engine + * hands it (objectql `relation-group-join.ts`) into one statement: + * + * … FROM child LEFT JOIN (SELECT id, attr FROM parent WHERE AND + * ) p ON child.fk = p.id GROUP BY …, p.attr, + * + * The related half is compiled the way a composed `ReadableIds` subquery is: + * the engine's composed scope through this same where compiler, the parent's + * tenant wall from the read's own options. Pinned here: the buckets and the + * resolved column (an empty FK, an FK naming no record, a parent the scope + * hides and another tenant's parent are all unresolved, attribute NULL), the + * measures unmultiplied by the join, a `null` parent (nothing readable), the + * statement binding no parameter per parent, and a parent the engine did not + * compose refused before anything compiles. + * + * Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`, + * `OS_TEST_MYSQL_URL`); SQLite always runs. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ReadableIds } from '@objectstack/spec/data'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { SqlDriver } from './sql-driver.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; +import { RELATION_GROUP_JOINS, type RelationGroupJoin } from './sql-driver-aggregation.js'; + +const PARENT = 'os_rgj_parent'; +const CHILD = 'os_rgj_child'; + +const PARENTS = [ + { id: 'p1', stage: 'won', owner: 'me', organization_id: 'org_a' }, + { id: 'p2', stage: 'lost', owner: 'me', organization_id: 'org_a' }, + { id: 'p3', stage: 'won', owner: 'other', organization_id: 'org_a' }, + { id: 'p4', stage: null, owner: 'me', organization_id: 'org_a' }, + { id: 'pb', stage: 'won', owner: 'me', organization_id: 'org_b' }, +]; +const CHILDREN = [ + { id: 'c1', parent: 'p1', g: 'x', amount: 1, organization_id: 'org_a' }, + { id: 'c2', parent: 'p1', g: 'y', amount: 2, organization_id: 'org_a' }, + { id: 'c3', parent: 'p2', g: 'x', amount: 4, organization_id: 'org_a' }, + { id: 'c4', parent: 'p3', g: 'x', amount: 8, organization_id: 'org_a' }, + { id: 'c5', parent: 'p4', g: 'x', amount: 16, organization_id: 'org_a' }, + { id: 'c6', parent: null, g: 'x', amount: 32, organization_id: 'org_a' }, + { id: 'c7', parent: 'nope', g: 'x', amount: 64, organization_id: 'org_a' }, + { id: 'c8', parent: 'pb', g: 'x', amount: 128, organization_id: 'org_a' }, +]; + +const join = (parent: RelationGroupJoin['parent']): RelationGroupJoin => ({ + field: 'parent', + parent, + attrs: [{ attr: 'stage', alias: 'rg_stage' }], + resolvedAlias: 'rg_resolved', +}); + +const query = (joins: readonly unknown[], over: Partial = {}): DriverQuery => ({ + aggregations: [ + { function: 'count', alias: 'n' }, + { function: 'sum', field: 'amount', alias: 'total' }, + ], + ...over, + [RELATION_GROUP_JOINS]: joins, +} as unknown as DriverQuery); + +/** `stage|resolved → [count, total]`, order-free. */ +const buckets = (rows: Array>) => + Object.fromEntries(rows.map((r) => [`${String(r.rg_stage)}|${String(r.rg_resolved)}`, [Number(r.n), Number(r.total)]])); + +function declareCell(cell: DialectCell): void { + describe(`[relation group join] driver-sql — aggregate LEFT JOINs the composed related rows (${cell.label})`, () => { + let driver: SqlDriver; + const OLD_POSTURE = process.env.OS_TENANCY_POSTURE; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + driver = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${CHILD}`).catch(() => {}); + await driver.execute(`drop table if exists ${PARENT}`).catch(() => {}); + await driver.initObjects([ + { name: PARENT, fields: { stage: { type: 'text' }, owner: { type: 'text' }, organization_id: { type: 'text' } } }, + { name: CHILD, fields: { parent: { type: 'lookup', reference: PARENT }, g: { type: 'text' }, amount: { type: 'number' }, organization_id: { type: 'text' } } }, + ] as never); + for (const row of PARENTS) await driver.create(PARENT, { ...row }, { bypassTenantAudit: true }); + for (const row of CHILDREN) await driver.create(CHILD, { ...row }, { bypassTenantAudit: true }); + }); + + afterAll(async () => { + await driver?.execute(`drop table if exists ${CHILD}`).catch(() => {}); + await driver?.execute(`drop table if exists ${PARENT}`).catch(() => {}); + await driver?.disconnect(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + it('the fixture is tenant-walled on both tables', () => { + const tenantField = (o: string) => (driver as unknown as { resolveTenantField(o: string): string | null }).resolveTenantField(o); + expect(tenantField(PARENT)).toBe('organization_id'); + expect(tenantField(CHILD)).toBe('organization_id'); + }); + + it('groups by the joined attribute; an empty FK, an FK naming no record, a hidden and another tenant\'s parent are unresolved — every child counted once', async () => { + const scope = { owner: 'me' }; + const rows = await driver.aggregate(CHILD, query([join(ReadableIds.compose(ReadableIds.of(PARENT), scope))]), { tenantId: 'org_a' }); + expect(buckets(rows as Array>)).toEqual({ + 'won|1': [2, 3], // p1 + 'lost|1': [1, 4], // p2 + 'null|1': [1, 16], // p4: a readable parent whose stage IS null + // p3 (outside the scope), no FK, 'nope', pb (org_b): 8 + 32 + 64 + 128. + 'null|0': [4, 232], + }); + }); + + it('beside a base group key, and with no scope (every same-tenant parent readable)', async () => { + const rows = await driver.aggregate(CHILD, query([join(ReadableIds.compose(ReadableIds.of(PARENT), undefined))], { groupBy: ['g'] }), { tenantId: 'org_a' }); + const got = Object.fromEntries((rows as Array>).map((r) => [`${String(r.g)}|${String(r.rg_stage)}|${String(r.rg_resolved)}`, Number(r.total)])); + expect(got).toEqual({ + 'x|won|1': 1 + 8, 'y|won|1': 2, 'x|lost|1': 4, 'x|null|1': 16, 'x|null|0': 32 + 64 + 128, + }); + }); + + it('a null parent (nothing readable): every group unresolved, no join', async () => { + const rows = await driver.aggregate(CHILD, query([join(null)]), { tenantId: 'org_a' }); + expect(buckets(rows as Array>)).toEqual({ 'null|0': [8, 255] }); + }); + + it('binds no parameter per related record: the scope\'s and the walls\' own only', async () => { + const knex = (driver as unknown as { knex: { on(e: string, f: (q: { bindings?: unknown[] }) => void): void; removeListener(e: string, f: unknown): void } }).knex; + const seen: number[] = []; + const listen = (q: { bindings?: unknown[] }) => { seen.push(q.bindings?.length ?? 0); }; + knex.on('query', listen); + try { + await driver.aggregate(CHILD, query([join(ReadableIds.compose(ReadableIds.of(PARENT), { owner: 'me' }))]), { tenantId: 'org_a' }); + } finally { + knex.removeListener('query', listen); + } + // child wall + parent wall + the scope's one comparand. + expect(Math.max(...seen)).toBe(3); + }); + + it('a parent the engine did not compose is refused before anything compiles: INTERNAL_ERROR / 500', async () => { + const forged = { object: PARENT, scope: undefined }; + const err = await driver.aggregate(CHILD, query([join(forged as never)]), { tenantId: 'org_a' }) + .then(() => null, (e: Error & { code?: string; status?: number }) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + }); + }); +} + +for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'aggregate relation group join', declareCell); diff --git a/packages/objectql/src/relation-group-join.test.ts b/packages/objectql/src/relation-group-join.test.ts new file mode 100644 index 00000000000..826e460a604 --- /dev/null +++ b/packages/objectql/src/relation-group-join.test.ts @@ -0,0 +1,226 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The engine-internal relation group request (`relation-group-join.ts`): an + * aggregate grouped by a related record's attribute is handed to a SQL driver + * as ONE statement whose related half is the related object's own aggregate, + * PLANNED as the caller — never an id list — and declined, with nothing read, + * wherever the engine cannot prove that. + * + * A recording driver stands in for the SQL family: it answers to a driver + * name the engine names (or not), records every call, and answers + * `aggregate` with the rows a test sets. What `driver-sql` compiles the joins + * to is pinned in that package and end to end in `service-analytics`. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { isComposedReadableIds, RLS_DENY_FILTER } from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; +import { + RELATION_GROUP_BY, + RELATION_GROUP_JOINS, + type DriverRelationGroupJoin, + type RelationGroupByRequest, +} from './relation-group-join.js'; + +const LINE = 'rgj_line'; +const OPP = 'rgj_opp'; + +const OPP_OBJECT = { + name: OPP, + label: 'Opportunity', + fields: { + stage: { name: 'stage', type: 'text' }, + owner: { name: 'owner', type: 'text' }, + score: { name: 'score', type: 'formula', expression: '1', returnType: 'number' }, + }, +}; +const LINE_OBJECT = { + name: LINE, + label: 'Line', + fields: { + amount: { name: 'amount', type: 'number' }, + region: { name: 'region', type: 'text' }, + opportunity: { name: 'opportunity', type: 'lookup', reference: OPP }, + opportunities: { name: 'opportunities', type: 'lookup', reference: OPP, multiple: true }, + }, +}; + +interface SeenCall { verb: string; object: string; ast: any } + +function makeRecordingDriver(name: string) { + const calls: SeenCall[] = []; + let answer: Array> = []; + const driver: any = { + name, version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(o: string, ast: any) { calls.push({ verb: 'find', object: o, ast }); return []; }, + async findOne(o: string, ast: any) { calls.push({ verb: 'findOne', object: o, ast }); return null; }, + async count(o: string, ast: any) { calls.push({ verb: 'count', object: o, ast }); return 0; }, + async aggregate(o: string, ast: any) { calls.push({ verb: 'aggregate', object: o, ast }); return answer; }, + async create(_o: string, data: Record) { return { ...data }; }, + async update(_o: string, id: string, data: Record) { return { ...data, id }; }, + async delete() { return true; }, + async beginTransaction() { return {}; }, + async commit() {}, async rollback() {}, + }; + return { driver, calls, answer: (rows: Array>) => { answer = rows; } }; +} + +type Thrown = (Error & { code?: string; status?: number }) | null; +const refusalOf = async (p: Promise): Promise => p.then(() => null, (e: any) => e); + +const request = (over: Partial = {}): RelationGroupByRequest => ({ + relations: [{ + field: 'opportunity', + object: OPP, + attrs: [{ attr: 'stage', alias: '__rg0_a0' }], + resolvedAlias: '__rg0_resolved', + ...over, + }], +}); + +const BASE_QUERY = { groupBy: ['region'], aggregations: [{ function: 'sum' as const, field: 'amount', alias: 'total' }] }; + +async function makeEngine(driverName: string) { + const rec = makeRecordingDriver(driverName); + const engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + engine.registry.registerObject(OPP_OBJECT as any, 'test'); + engine.registry.registerObject(LINE_OBJECT as any, 'test'); + return { engine, rec }; +} + +describe('relation group join — served as one driver statement whose related half is the planned related read', () => { + let engine: ObjectQL; + let rec: ReturnType; + + beforeEach(async () => { + ({ engine, rec } = await makeEngine('com.objectstack.driver.sql')); + }); + + it('one driver call: the base aggregate carries the join, its parent the related read\'s planned where — the request\'s condition AND what the related read\'s middleware injected', async () => { + // A read middleware on the related object's read, as row-level security + // injects one: it runs on the PLANNED read, so its condition is in the + // join's scope. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === OPP) op.ast.where = op.ast.where ? { $and: [op.ast.where, { owner: 'u_me' }] } : { owner: 'u_me' }; + await next(); + }); + rec.answer([{ region: 'emea', __rg0_a0: 'won', __rg0_resolved: 1, total: 10 }]); + const req = request({ where: { stage: { $ne: 'lost' } } }); + const rows = await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + + expect(req.outcome).toEqual({ kind: 'joined' }); + expect(rows).toEqual([{ region: 'emea', __rg0_a0: 'won', __rg0_resolved: 1, total: 10 }]); + // No read of the related object reached the driver: it was planned. + expect(rec.calls.map((c) => `${c.verb}:${c.object}`)).toEqual([`aggregate:${LINE}`]); + const ast = rec.calls[0]!.ast; + expect(ast.groupBy).toEqual(['region']); + const joins = ast[RELATION_GROUP_JOINS] as DriverRelationGroupJoin[]; + expect(joins).toHaveLength(1); + expect(joins[0]!.field).toBe('opportunity'); + expect(joins[0]!.attrs).toEqual([{ attr: 'stage', alias: '__rg0_a0' }]); + expect(joins[0]!.resolvedAlias).toBe('__rg0_resolved'); + expect(isComposedReadableIds(joins[0]!.parent)).toBe(true); + expect(joins[0]!.parent!.object).toBe(OPP); + expect(joins[0]!.parent!.scope).toEqual({ $and: [{ stage: { $ne: 'lost' } }, { owner: 'u_me' }] }); + }); + + it('a related read whose planned scope is the deny sentinel hands a null parent: nothing of the related object is readable', async () => { + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === OPP) op.ast.where = RLS_DENY_FILTER; + await next(); + }); + rec.answer([{ region: 'emea', __rg0_a0: null, __rg0_resolved: 0, total: 10 }]); + const req = request(); + await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome).toEqual({ kind: 'joined' }); + expect((rec.calls[0]!.ast[RELATION_GROUP_JOINS] as DriverRelationGroupJoin[])[0]!.parent).toBeNull(); + }); + + it('a refusal of the related read propagates — a virtual attribute is refused by the related object\'s own group-by door, and no driver is asked', async () => { + const req = request({ attrs: [{ attr: 'score', alias: '__rg0_a0' }] }); + const err = await refusalOf(engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_FIELD', status: 400 }); + expect(rec.calls).toEqual([]); + }); + + it('a driver that answers without the resolved column did not compile the join: INTERNAL_ERROR / 500, the rows discarded', async () => { + rec.answer([{ region: 'emea', total: 10 }]); + const err = await refusalOf(engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: request() } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + }); + + it('a request that names a column the row already has is a server fault, judged before anything is read', async () => { + const err = await refusalOf(engine.aggregate(LINE, BASE_QUERY, { + [RELATION_GROUP_BY]: request({ attrs: [{ attr: 'stage', alias: 'total' }] }), + } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + expect(rec.calls).toEqual([]); + }); + + it('without the request, the aggregate is the one it always was: no join on the AST', async () => { + rec.answer([{ region: 'emea', total: 10 }]); + await engine.aggregate(LINE, BASE_QUERY); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0]!.ast[RELATION_GROUP_JOINS]).toBeUndefined(); + }); +}); + +describe('relation group join — DECLINED, with nothing read, wherever it is not provably the FK-expand\'s read', () => { + for (const name of ['com.objectstack.driver.memory', 'com.objectstack.driver.mongodb', 'com.objectstack.driver.odata', 'com.objectstack.driver.turso']) { + it(`a driver that compiles no join (${name}): declined, no driver call — the caller's own path serves it`, async () => { + const { engine, rec } = await makeEngine(name); + const req = request(); + const rows = await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + expect(rows).toEqual([]); + expect(req.outcome?.kind).toBe('declined'); + expect(rec.calls).toEqual([]); + }); + } + + it('a multi-valued relation: declined', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + const req = request({ field: 'opportunities' }); + await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome?.kind).toBe('declined'); + expect(rec.calls).toEqual([]); + }); + + it('a relation the request reads as another object than it references: declined', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + const req = request({ object: LINE }); + await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome?.kind).toBe('declined'); + expect(rec.calls).toEqual([]); + }); + + it('a middleware that answers the related read without its driver: the related read is not one planned statement, declined', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === OPP) { op.result = [{ id: 'x' }]; return; } + await next(); + }); + const req = request(); + await engine.aggregate(LINE, BASE_QUERY, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome?.kind).toBe('declined'); + expect(rec.calls).toEqual([]); + }); + + it('an aggregate the driver does not answer natively (a non-UTC date bucket): declined, no driver call', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + engine.registry.registerObject({ + ...LINE_OBJECT, fields: { ...LINE_OBJECT.fields, closed_on: { name: 'closed_on', type: 'date' } }, + } as any, 'test'); + const req = request(); + await engine.aggregate(LINE, { + groupBy: [{ field: 'closed_on', dateGranularity: 'month' }], + aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }], + timezone: 'Asia/Shanghai', + } as never, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome?.kind).toBe('declined'); + expect(rec.calls).toEqual([]); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts new file mode 100644 index 00000000000..b3eba642c5d --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts @@ -0,0 +1,300 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A cross-object dimension (`opportunity.stage` on `line`) on the ObjectQL + * face is served by ONE statement on a SQL driver — the engine's relation + * group join, `LEFT JOIN … GROUP BY` (objectql `relation-group-join.ts`) — + * and answers exactly what the FK-expand answered (`resolveFkAttr`: the base + * aggregate grouped by the FK, an `id IN (every FK)` read of the related + * object, re-bucketed here), without that read's id list. + * + * The composition is the plugin's, over a real `ObjectQL` and a real + * `SqliteWasmDriver`, under a walled tenancy posture. The FK-expand reference + * is the SAME composition with the engine's `aggregate` reached through a + * door that drops its read options: the engine never sees the request, the + * strategy is told the join was not served, and serves the dimension the way + * it did before the join existed. + * + * - parity: identical buckets and measures for an admin, for a member whose + * read scope hides parents (a policy scope through `getReadScope` AND a + * read middleware on the related object), for another tenant, with null, + * orphaned and cross-tenant FKs, several dimensions through one relation, + * and the FK column beside its own attribute; + * - the read scope and the tenant wall hold on the joined parent: a hidden + * parent never contributes its attribute, another tenant's parent never + * joins; + * - the bind limit: 33,000 distinct FKs answered `DATABASE_ERROR` / 500 on the + * FK-expand (`too many SQL variables`) and answer 200 joined. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import type { AnalyticsQuery } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { DatasetSchema } from '@objectstack/spec/ui'; + +import { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; + +const LINE = 'zz_rgj_line'; +const OPP = 'zz_rgj_opp'; +const RELATION_GROUP_BY = Symbol.for('objectstack.objectql.relationGroupBy'); + +const OPP_FIELDS: Record> = { + name: { type: 'text', name: 'name' }, + stage: { type: 'text', name: 'stage' }, + owner: { type: 'text', name: 'owner' }, +}; +const LINE_FIELDS: Record> = { + region: { type: 'text', name: 'region' }, + amount: { type: 'number', name: 'amount' }, + opportunity: { type: 'lookup', name: 'opportunity', reference: OPP }, +}; + +const dataset = DatasetSchema.parse({ + name: 'rgj_lines', + label: 'Lines by opportunity', + object: LINE, + include: ['opportunity'], + dimensions: [ + { name: 'stage', field: 'opportunity.stage', type: 'string' }, + { name: 'opp_name', field: 'opportunity.name', type: 'string' }, + { name: 'region', field: 'region', type: 'string' }, + { name: 'opportunity', field: 'opportunity', type: 'string' }, + ], + measures: [ + { name: 'line_count', aggregate: 'count' }, + { name: 'amount_sum', aggregate: 'sum', field: 'amount' }, + { name: 'amount_min', aggregate: 'min', field: 'amount' }, + { name: 'amount_max', aggregate: 'max', field: 'amount' }, + ], +}); + +const ADMIN_A = { userId: 'u_admin', tenantId: 'org_A' } as ExecutionContext; +const MEMBER_A = { userId: 'u_member', tenantId: 'org_A' } as ExecutionContext; +const ADMIN_B = { userId: 'u_admin', tenantId: 'org_B' } as ExecutionContext; + +const OPPS = [ + { id: 'o1', name: 'One', stage: 'won', owner: 'u_member', organization_id: 'org_A' }, + { id: 'o2', name: 'Two', stage: 'lost', owner: 'u_member', organization_id: 'org_A' }, + { id: 'o3', name: 'Three', stage: 'open', owner: 'u_other', organization_id: 'org_A' }, + { id: 'o4', name: 'Four', stage: 'won', owner: 'u_other', organization_id: 'org_A' }, + { id: 'b1', name: 'Bee', stage: 'won', owner: 'u_member', organization_id: 'org_B' }, +]; +const LINES = [ + { id: 'l1', opportunity: 'o1', region: 'emea', amount: 10, organization_id: 'org_A' }, + { id: 'l2', opportunity: 'o1', region: 'apac', amount: 20, organization_id: 'org_A' }, + { id: 'l3', opportunity: 'o2', region: 'emea', amount: 5, organization_id: 'org_A' }, + { id: 'l4', opportunity: 'o3', region: 'emea', amount: 7, organization_id: 'org_A' }, + { id: 'l5', opportunity: 'o4', region: 'apac', amount: 3, organization_id: 'org_A' }, + { id: 'l6', opportunity: null, region: 'emea', amount: 11, organization_id: 'org_A' }, + // A FK naming no record at all, and one naming ANOTHER tenant's record. + { id: 'l7', opportunity: 'o_missing', region: 'apac', amount: 13, organization_id: 'org_A' }, + { id: 'l8', opportunity: 'b1', region: 'emea', amount: 17, organization_id: 'org_A' }, + { id: 'l9', opportunity: 'o3', region: 'amer', amount: 2, organization_id: 'org_A' }, + { id: 'lb1', opportunity: 'b1', region: 'emea', amount: 100, organization_id: 'org_B' }, + { id: 'lb2', opportunity: 'o1', region: 'apac', amount: 50, organization_id: 'org_B' }, +]; + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; + +function pluginContext(services: Record) { + const registered: Record = {}; + return { + registered, + ctx: { + getService: (name: string) => services[name] ?? registered[name], + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + logger: quiet, + }, + }; +} + +/** The member's policy scope of the related object: only the opportunities they own. */ +const getReadScope = (object: string, context?: ExecutionContext) => + (object === OPP && context?.userId === 'u_member' ? { owner: 'u_member' } : undefined) as never; + +/** + * The plugin's own composition over `engine`. `joined: false` reaches the + * engine through a door that drops `aggregate`'s read options — the + * FK-expand reference. `outcomes` records what the engine did with each + * relation group request it was handed. + */ +async function pluginService(engine: ObjectQL, joined: boolean, outcomes: unknown[] = []): Promise { + const data = new Proxy(engine, { + get(target, prop) { + if (prop === 'aggregate') { + return async (object: string, query: unknown, options?: Record) => { + if (!joined) return target.aggregate(object, query as never); + const rows = await target.aggregate(object, query as never, options as never); + const request = options?.[RELATION_GROUP_BY] as { outcome?: unknown } | undefined; + if (request) outcomes.push(request.outcome); + return rows; + }; + } + const value = (target as unknown as Record)[prop]; + return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value; + }, + }); + const { ctx, registered } = pluginContext({ data }); + await new AnalyticsServicePlugin({ + queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), + getReadScope, + }).init(ctx as never); + const service = registered.analytics as AnalyticsService; + service.registerDataset(dataset); + return service; +} + +/** Rows order-free: each row's dimension values joined into one sort key. */ +function sorted(rows: Record[]): Record[] { + return [...rows].sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))); +} + +const OLD_POSTURE = process.env.OS_TENANCY_POSTURE; + +async function bootEngine(): Promise<{ engine: ObjectQL; driver: SqliteWasmDriver }> { + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + (driver as unknown as { logger: unknown }).logger = quiet; + const engine = new ObjectQL({ logger: quiet }); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerObject({ name: OPP, label: 'Opportunity', fields: OPP_FIELDS } as never); + engine.registerObject({ name: LINE, label: 'Line', fields: LINE_FIELDS } as never); + await engine.syncSchemas(); + return { engine, driver }; +} + +describe('a cross-object dimension on a SQL driver is ONE joined statement, with the FK-expand\'s buckets', () => { + let driver: SqliteWasmDriver; + let engine: ObjectQL; + let joined: AnalyticsService; + let expanded: AnalyticsService; + const outcomes: unknown[] = []; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + ({ engine, driver } = await bootEngine()); + for (const row of OPPS) await driver.create(OPP, { ...row }, { bypassTenantAudit: true } as never); + for (const row of LINES) await driver.create(LINE, { ...row }, { bypassTenantAudit: true } as never); + // A read middleware on the related object, as row-level security injects + // one: it hides `o2` from the member. It runs on the joined path's PLANNED + // read of the related object and on the FK-expand's id read alike. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === OPP && op.context?.userId === 'u_member') { + op.ast.where = op.ast.where ? { $and: [op.ast.where, { id: { $ne: 'o2' } }] } : { id: { $ne: 'o2' } }; + } + await next(); + }); + joined = await pluginService(engine, true, outcomes); + expanded = await pluginService(engine, false); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + it('the fixture is tenant-walled: the driver resolves the tenant column of both objects', () => { + expect((driver as unknown as { resolveTenantField(o: string): string | null }).resolveTenantField(OPP)).toBe('organization_id'); + expect((driver as unknown as { resolveTenantField(o: string): string | null }).resolveTenantField(LINE)).toBe('organization_id'); + }); + + const MEASURES = ['line_count', 'amount_sum', 'amount_min', 'amount_max']; + const SHAPES: ReadonlyArray = [ + ['stage'], + ['region', 'stage'], + ['stage', 'opp_name'], + ['opportunity', 'stage'], + ]; + const CALLERS: ReadonlyArray = [ + ['admin of org_A', ADMIN_A], + ['member of org_A (policy scope + read middleware hide parents)', MEMBER_A], + ['admin of org_B', ADMIN_B], + ]; + + for (const [who, context] of CALLERS) { + for (const dims of SHAPES) { + it(`parity — ${who}, dimensions [${dims.join(', ')}]: joined, and identical to the FK-expand`, async () => { + const query = { cube: dataset.name, dimensions: [...dims], measures: MEASURES } as AnalyticsQuery; + outcomes.length = 0; + const viaJoin = await joined.query(query, context); + expect(outcomes, 'the engine joined the request').toEqual([{ kind: 'joined' }]); + const viaExpand = await expanded.query(query, context); + expect(sorted(viaJoin.rows)).toEqual(sorted(viaExpand.rows)); + expect(viaJoin.rows.length).toBeGreaterThan(0); + }); + } + } + + const byStage = (rows: Record[]) => + Object.fromEntries(rows.map((r) => [String(r.stage), [Number(r.line_count), Number(r.amount_sum)]])); + + it('the buckets themselves (admin of org_A): a null, an orphaned and a cross-tenant FK are (restricted); every line counted once', async () => { + const { rows } = await joined.query({ cube: dataset.name, dimensions: ['stage'], measures: MEASURES } as AnalyticsQuery, ADMIN_A); + expect(byStage(rows)).toEqual({ + won: [3, 33], + lost: [1, 5], + open: [2, 9], + // l6 (null FK), l7 (no such record), l8 (org_B's record): 11 + 13 + 17. + '(restricted)': [3, 41], + }); + }); + + it('the read scope holds on the joined parent: the member sees only o1\'s stage — o2 (hidden by the middleware) and o3/o4 (outside the policy scope) are (restricted)', async () => { + const { rows } = await joined.query({ cube: dataset.name, dimensions: ['stage'], measures: MEASURES } as AnalyticsQuery, MEMBER_A); + expect(byStage(rows)).toEqual({ won: [2, 30], '(restricted)': [7, 58] }); + // The hidden parents' attributes never appear. + const named = await joined.query({ cube: dataset.name, dimensions: ['opp_name'], measures: ['line_count'] } as AnalyticsQuery, MEMBER_A); + expect(named.rows.map((r) => r.opp_name).sort()).toEqual(['(restricted)', 'One']); + }); + + it('the tenant wall holds on the joined parent: org_B\'s line pointing at org_A\'s o1 never joins it', async () => { + const { rows } = await joined.query({ cube: dataset.name, dimensions: ['stage'], measures: MEASURES } as AnalyticsQuery, ADMIN_B); + expect(byStage(rows)).toEqual({ won: [1, 100], '(restricted)': [1, 50] }); + }); +}); + +describe('the bind limit: a lookup dimension over more distinct FKs than the dialect binds', () => { + const N = 33_000; + let driver: SqliteWasmDriver; + let engine: ObjectQL; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + ({ engine, driver } = await bootEngine()); + const STAGES = ['won', 'lost', 'open']; + const knex = (driver as unknown as { knex: { batchInsert(t: string, rows: unknown[], n: number): Promise } }).knex; + const opps = Array.from({ length: N }, (_, i) => ({ id: `o${i}`, name: `O${i}`, stage: STAGES[i % 3], owner: 'u_other', organization_id: 'org_A' })); + const lines = Array.from({ length: N }, (_, i) => ({ id: `l${i}`, opportunity: `o${i}`, region: 'emea', amount: 1, organization_id: 'org_A' })); + await knex.batchInsert(OPP, opps, 1000); + await knex.batchInsert(LINE, lines, 1000); + }, 60_000); + + afterAll(async () => { + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + const QUERY = { cube: dataset.name, dimensions: ['stage'], measures: ['line_count'] } as AnalyticsQuery; + + it(`${N} distinct FKs: the FK-expand's id read is refused by the database (DATABASE_ERROR / 500)`, async () => { + const expanded = await pluginService(engine, false); + const err = await expanded.query(QUERY, ADMIN_A).then(() => null, (e: Error & { code?: string; status?: number }) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'DATABASE_ERROR', status: 500 }); + }); + + it(`${N} distinct FKs: joined, one statement, every line in its stage`, async () => { + const outcomes: unknown[] = []; + const service = await pluginService(engine, true, outcomes); + const { rows } = await service.query(QUERY, ADMIN_A); + expect(outcomes).toEqual([{ kind: 'joined' }]); + expect(Object.fromEntries(rows.map((r) => [String(r.stage), Number(r.line_count)]))).toEqual({ + won: N / 3, lost: N / 3, open: N / 3, + }); + }); +}); From 1440b7c158ad8358396f5b9492a2680c1b9947ad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:50:09 +0000 Subject: [PATCH 4/9] test: relation group join pins pass (objectql unit, driver-sql sqlite+pg, analytics parity and bind limit) Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw Co-authored-by: Claude --- packages/objectql/src/relation-group-join.test.ts | 6 +++++- .../src/__tests__/cross-object-relation-group-join.test.ts | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/relation-group-join.test.ts b/packages/objectql/src/relation-group-join.test.ts index 826e460a604..60844d39997 100644 --- a/packages/objectql/src/relation-group-join.test.ts +++ b/packages/objectql/src/relation-group-join.test.ts @@ -125,7 +125,11 @@ describe('relation group join — served as one driver statement whose related h expect(joins[0]!.resolvedAlias).toBe('__rg0_resolved'); expect(isComposedReadableIds(joins[0]!.parent)).toBe(true); expect(joins[0]!.parent!.object).toBe(OPP); - expect(joins[0]!.parent!.scope).toEqual({ $and: [{ stage: { $ne: 'lost' } }, { owner: 'u_me' }] }); + // The request's condition as the related read's own doors lowered it + // (`$ne` is null-safe), AND the middleware's. + expect(joins[0]!.parent!.scope).toEqual({ + $and: [{ $and: [{ $or: [{ stage: { $null: true } }, { stage: { $ne: 'lost' } }] }] }, { owner: 'u_me' }], + }); }); it('a related read whose planned scope is the deny sentinel hands a null parent: nothing of the related object is readable', async () => { diff --git a/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts index b3eba642c5d..e9335f8dd2e 100644 --- a/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts +++ b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts @@ -270,8 +270,8 @@ describe('the bind limit: a lookup dimension over more distinct FKs than the dia const knex = (driver as unknown as { knex: { batchInsert(t: string, rows: unknown[], n: number): Promise } }).knex; const opps = Array.from({ length: N }, (_, i) => ({ id: `o${i}`, name: `O${i}`, stage: STAGES[i % 3], owner: 'u_other', organization_id: 'org_A' })); const lines = Array.from({ length: N }, (_, i) => ({ id: `l${i}`, opportunity: `o${i}`, region: 'emea', amount: 1, organization_id: 'org_A' })); - await knex.batchInsert(OPP, opps, 1000); - await knex.batchInsert(LINE, lines, 1000); + await knex.batchInsert(OPP, opps, 400); + await knex.batchInsert(LINE, lines, 400); }, 60_000); afterAll(async () => { From c382972e7e347137c7ac273a08553e30813e8f34 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:13:19 +0000 Subject: [PATCH 5/9] test(objectql): the relation group join's federated seams have their disposition rows Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../src/federated-injected-column-readers.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index f5c9639bf9c..5a9fe8bb3f3 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -232,6 +232,17 @@ const READERS: Record = { disposition: 'exempt', why: 'a federated related object keeps the id read, so no subquery is compiled against it; it reads no row', }, + // The relation group join: a federated base object declines (its caller + // keeps the FK-expand), and a federated related object declines through + // `relationSemiJoinServes`, so no join is compiled against either. + 'relation-group-join.ts#relationGroupRegistryDecline :: isFederatedObject()': { + disposition: 'exempt', + why: 'a federated base object declines the join, so no statement is compiled against it; it reads no row', + }, + 'relation-group-join.ts#relationGroupRegistryDecline :: referenceTargetOf()': { + disposition: 'exempt', + why: 'names the related object only to judge the join beside the federated test; it reads no row', + }, // [#24197] The one-hop loader moved out of `resolvePredicateRelated` so // validation predicates and formula fields share it; a formula's hop is read // as the caller outright, so its federated answer is the caller's own read. From c87aab92dc10611ce68b48d85d021b5e5182545c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:49:02 +0000 Subject: [PATCH 6/9] fix(analytics): a 4xx on the joined path is re-derived by the FK-expand, so the refusal envelope stays today's Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../src/strategies/objectql-strategy.ts | 49 ++++++++++++++----- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index 1c2d52ad124..132270287f5 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -1785,7 +1785,9 @@ export class ObjectQLStrategy implements AnalyticsStrategy { * * `null` — serve by the FK-expand — when the host wired no such hook or the * engine declined (a driver that compiles no join: memory, MongoDB, OData; - * a read it cannot prove is one statement). + * a read it cannot prove is one statement), and when anything on the way + * refused with a 4xx: the FK-expand re-derives that refusal, so its order + * and its envelope stay today's. */ private async executeCrossObjectJoined( baseObject: string, @@ -1801,9 +1803,15 @@ export class ObjectQLStrategy implements AnalyticsStrategy { const run = (ctx as DatasetScopedStrategyContext).executeRelationGroupAggregate; if (typeof run !== 'function') return null; - // [#29304] A virtual attribute is refused in the dataset door's words - // before the engine is asked, as the FK-expand refuses it. - assertCrossObjectAttrsStored(plan, ctx); + // [#29304] A virtual attribute is the FK-expand's to refuse, in the + // dataset door's words and after its base read's own doors: this path + // only declines, before the engine is asked. + try { + assertCrossObjectAttrsStored(plan, ctx); + } catch (error) { + if (isClientRefusal(error)) return null; + throw error; + } // One relation per FK column, each attribute under its own column. const relations: Array<{ field: string; object: string; where?: Record; attrs: Array<{ attr: string; alias: string }>; resolvedAlias: string }> = []; @@ -1836,13 +1844,26 @@ export class ObjectQLStrategy implements AnalyticsStrategy { const replaced = new Set(relations.map((r) => r.field).filter((f) => !baseDimFields.includes(f))); const joinGroupBy = groupBy.filter((g) => typeof g !== 'string' || !replaced.has(g)); - const answer = await run.call(ctx, baseObject, { - groupBy: joinGroupBy.length > 0 ? (joinGroupBy as unknown as string[]) : undefined, - aggregations: aggregations.length > 0 ? aggregations : undefined, - filter: this.withReadScope(baseObject, filter, ctx), - timezone: query.timezone, - context: ctx.context, - }, relations as readonly RelationGroupAggregateRelation[]); + // A 4xx refusal is not this path's to word: the base query here is not + // the FK-expand's (its FK columns are gone, so a refusal citing a group + // key's position names another one), and the related read is judged even + // over an empty base set, which the FK-expand never reads. The FK-expand + // re-derives it, so the envelope a client sees, and the dry run it + // matches, stays today's field for field. A 5xx is the join's own + // fault and surfaces. + let answer: Awaited>; + try { + answer = await run.call(ctx, baseObject, { + groupBy: joinGroupBy.length > 0 ? (joinGroupBy as unknown as string[]) : undefined, + aggregations: aggregations.length > 0 ? aggregations : undefined, + filter: this.withReadScope(baseObject, filter, ctx), + timezone: query.timezone, + context: ctx.context, + }, relations as readonly RelationGroupAggregateRelation[]); + } catch (error) { + if (isClientRefusal(error)) return null; + throw error; + } if (!answer.joined) return null; // Each row is one group of the joined statement. Its key for a relation @@ -2826,3 +2847,9 @@ export class ObjectQLStrategy implements AnalyticsStrategy { return fields; } } + +/** [relation group join] A declared 4xx: a verdict the FK-expand re-derives in its own order and words. */ +function isClientRefusal(error: unknown): boolean { + const status = (error as { status?: unknown } | null | undefined)?.status; + return typeof status === 'number' && status >= 400 && status < 500; +} From 1f25ced8293e4c3ccab25837f5c364b4ba60f49a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:44:39 +0000 Subject: [PATCH 7/9] fix(objectql): the base relation field stays a group key to every door on the relation group join The FK-expand groups the base read by the relation field, so the field-level gate on an aggregate's group keys judges it. The joined path replaced that key before any middleware ran. The engine now hands the chain the base read grouped by each relation field the join replaces, and takes those keys out only at the driver call. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../src/engine-delete-and-aggregate.ts | 17 ++++-- packages/objectql/src/relation-group-join.ts | 53 ++++++++++++++++++- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index b0a0b59401b..7c7aad63c3f 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -82,8 +82,8 @@ import type { EngineReadOptions, OperationContext } from './engine-top-level.js' import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; import { assertRelationGroupRequestShape, assertRelationGroupRowsJoined, declineRelationGroup, planRelationGroups, - RELATION_GROUP_JOINS, relationGroupByRequestOf, relationGroupJoinsAtBoundary, relationGroupRegistryDecline, - type PlannedRelationGroup, + RELATION_GROUP_JOINS, relationFieldsJudgedAsGroupKeys, relationGroupByRequestOf, relationGroupJoinsAtBoundary, + relationGroupRegistryDecline, withoutJudgedRelationFields, type PlannedRelationGroup, } from './relation-group-join.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; @@ -1292,6 +1292,14 @@ export class DeleteAndAggregateFacet { ); if (plannedRelationGroups === null) return []; } + // [relation group join] The base read is judged as grouped by each + // relation field the join replaces, exactly as the FK-expand's base read + // is: those keys ride the AST every middleware sees (the field-level + // gate on an aggregate's group keys among them) and leave it only at the + // driver call below, where the join takes their place. + const judgedRelationFields = relationGroup === undefined + ? [] + : relationFieldsJudgedAsGroupKeys(relationGroup, query.groupBy); const opCtx: OperationContext = { object, @@ -1302,7 +1310,7 @@ export class DeleteAndAggregateFacet { ast: { object, where: query.where, - groupBy: query.groupBy, + groupBy: judgedRelationFields.length > 0 ? [...(query.groupBy ?? []), ...judgedRelationFields] : query.groupBy, aggregations: query.aggregations, // ENFORCED since #4286 (step 3). On the ast so the FLS predicate // guard walks its references (predicate-guard.ts) and a future @@ -1445,7 +1453,8 @@ export class DeleteAndAggregateFacet { } const joins = relationGroupJoinsAtBoundary(relationGroup, plannedRelationGroups, aggregateOptions); if (joins === null) return []; - const joined = await drv.aggregate(object, { ...ast, [RELATION_GROUP_JOINS]: joins }, aggregateOptions); + const statement = withoutJudgedRelationFields(ast, judgedRelationFields, query.groupBy); + const joined = await drv.aggregate(object, { ...statement, [RELATION_GROUP_JOINS]: joins }, aggregateOptions); assertRelationGroupRowsJoined(object, drv.name, joined, joins); relationGroup.outcome = { kind: 'joined' }; return applyHaving(joined, ast.having, havingColumnClasses); diff --git a/packages/objectql/src/relation-group-join.ts b/packages/objectql/src/relation-group-join.ts index f95723674a0..eb0ce9bb2f9 100644 --- a/packages/objectql/src/relation-group-join.ts +++ b/packages/objectql/src/relation-group-join.ts @@ -19,7 +19,22 @@ * (`ObjectQLStrategy`), through its plugin's engine bridge; it is a * `Symbol.for` key because that package does not depend on this one at * runtime. Holding the key grants nothing: the engine plans the related read - * itself, as the caller, below. + * itself, as the caller, below, and judges the base read as grouped by each + * relation field. + * + * ## The base relation field is a group key to every door + * + * The FK-expand groups the base read by the relation field (`opportunity`), + * so every guard that judges a group key — the field-level read gate on an + * aggregate's inputs first among them — judges that field for the caller. + * The join replaces that group key, but not that verdict: the AST the + * middleware chain sees is grouped by each relation field `groupBy` does not + * already name ({@link relationFieldsJudgedAsGroupKeys}), and only after + * the chain has run does the engine take those keys back out of the + * statement it hands the driver ({@link withoutJudgedRelationFields}), the + * join taking their place. So a caller who may not read the relation field + * is refused on this path by the same gate, in the same words, as on the + * FK-expand — ⛔ no second copy of any field gate lives here. * * ## How the related half is built: the related object's own read, planned * @@ -228,6 +243,42 @@ export function assertRelationGroupRequestShape( } } +/** The field a `groupBy` entry names: a plain string, or a structured `{ field }` item. */ +function groupKeyField(entry: unknown): string | undefined { + if (typeof entry === 'string') return entry; + const field = (entry as { field?: unknown } | null | undefined)?.field; + return typeof field === 'string' ? field : undefined; +} + +/** + * The relation fields the base read is judged as grouped by: each relation + * field of the request that `groupBy` does not already name (a base + * dimension that names the FK column itself keeps its own entry). The engine + * adds them to the AST the middleware chain sees, so every guard that judges + * a group key judges them as it does on the FK-expand's base read. + */ +export function relationFieldsJudgedAsGroupKeys(request: RelationGroupByRequest, groupBy: unknown): string[] { + const named = new Set((Array.isArray(groupBy) ? groupBy : []).map(groupKeyField)); + return [...new Set(request.relations.map((r) => r.field))].filter((field) => !named.has(field)); +} + +/** + * The statement the driver is handed: the chain's final AST without the + * relation fields {@link relationFieldsJudgedAsGroupKeys} added for it — the + * join replaces them as group keys. An AST whose own `groupBy` was absent + * stays absent when nothing else is left in it. + */ +export function withoutJudgedRelationFields( + ast: T, + judged: readonly string[], + ownGroupBy: unknown, +): T { + if (judged.length === 0 || !Array.isArray(ast.groupBy)) return ast; + const drop = new Set(judged); + const kept = (ast.groupBy as unknown[]).filter((entry) => !(typeof entry === 'string' && drop.has(entry))); + return { ...ast, groupBy: kept.length === 0 && !Array.isArray(ownGroupBy) ? undefined : kept }; +} + /** What {@link relationGroupRegistryDecline} reads off the engine. */ export interface RelationGroupRegistryHost { getObjectSchema(object: string): unknown; From 546a3bc86346e6ac26513276811964099d0ae423 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:46:01 +0000 Subject: [PATCH 8/9] test(analytics): the base relation field's field read and the related object's exposure on the relation group join Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .../second-object-read-exposure.pin.test.ts | 14 +- .../cross-object-relation-group-join.test.ts | 171 +++++++++++++++++- 2 files changed, 181 insertions(+), 4 deletions(-) diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 42e0280147d..a71a20b79de 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -97,7 +97,7 @@ type Classification = /** The read, in words. */ read: string; /** The operation the target is judged as. */ - operation: 'get' | 'list'; + operation: 'get' | 'list' | 'aggregate'; /** The function that asks the decision, and the file it lives in. */ decision: { file: string; fn: string }; /** Where the read takes its answer from that function: a call site that must exist. */ @@ -195,6 +195,17 @@ const CALLERS: Record = { wiring: { file: 'packages/plugins/plugin-audit/src/audit-writers.ts', call: 'servesSummaryTitleTarget(objectName' }, pin: 'packages/plugins/plugin-audit/src/audit-lookup-summary.test.ts', }, + // The engine's relation group join: an analytics cross-object dimension as one `LEFT JOIN … GROUP BY`. + 'packages/objectql/src/relation-group-join.ts': { + kind: 'decided', + read: + "the engine's relation group join (an analytics dimension through a lookup grouped by the related record's " + + 'attribute in one statement; `referenceTargetOf` checks that the relation points at the object the request names)', + operation: 'aggregate', + decision: { file: 'packages/services/service-analytics/src/api-exposure-door.ts', fn: 'assertObjectsExposed' }, + wiring: { file: 'packages/services/service-analytics/src/analytics-service.ts', call: 'assertObjectsExposed(objects, provider' }, + pin: 'packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts', + }, 'packages/core/src/utils/relation-condition-sites.ts': { kind: 'not-a-served-read', reason: @@ -489,6 +500,7 @@ describe('[#22661] every read that reaches a second object asks that object its (c): c is Extract => c.kind === 'decided', ); expect(decided.map((d) => d.decision.fn).sort()).toEqual([ + 'assertObjectsExposed', 'refuseUnservedRelationTarget', 'servesExpansionTarget', 'servesLabelTarget', diff --git a/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts index e9335f8dd2e..6a24abe3d36 100644 --- a/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts +++ b/packages/services/service-analytics/src/__tests__/cross-object-relation-group-join.test.ts @@ -24,7 +24,16 @@ * parent never contributes its attribute, another tenant's parent never * joins; * - the bind limit: 33,000 distinct FKs answered `DATABASE_ERROR` / 500 on the - * FK-expand (`too many SQL variables`) and answer 200 joined. + * FK-expand (`too many SQL variables`) and answer 200 joined; + * - the base relation field's field-level read: a caller who may not read + * `line.opportunity` is refused the same 403 with the join wired as without + * it, and the engine itself refuses that caller a relation group request + * handed to it directly, past the analytics door, as it refuses the + * FK-expand's base read grouped by the field; + * - the related object's API exposure: a related object whose `enable` block + * denies the aggregate operation is refused with the data door's code on + * the joined path exactly as on the FK-expand, before the engine is handed + * any relation group request (#22661). */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -122,7 +131,12 @@ const getReadScope = (object: string, context?: ExecutionContext) => * FK-expand reference. `outcomes` records what the engine did with each * relation group request it was handed. */ -async function pluginService(engine: ObjectQL, joined: boolean, outcomes: unknown[] = []): Promise { +async function pluginService( + engine: ObjectQL, + joined: boolean, + outcomes: unknown[] = [], + services: Record = {}, +): Promise { const data = new Proxy(engine, { get(target, prop) { if (prop === 'aggregate') { @@ -138,7 +152,7 @@ async function pluginService(engine: ObjectQL, joined: boolean, outcomes: unknow return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value; }, }); - const { ctx, registered } = pluginContext({ data }); + const { ctx, registered } = pluginContext({ ...services, data }); await new AnalyticsServicePlugin({ queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), getReadScope, @@ -298,3 +312,154 @@ describe('the bind limit: a lookup dimension over more distinct FKs than the dia }); }); }); + +/** A refusal's envelope: what a client branches on. */ +const envelopeOf = (e: unknown) => ({ code: (e as { code?: unknown })?.code, status: (e as { status?: unknown })?.status }); + +async function seeded(): Promise<{ engine: ObjectQL; driver: SqliteWasmDriver }> { + const booted = await bootEngine(); + for (const row of OPPS) await booted.driver.create(OPP, { ...row }, { bypassTenantAudit: true } as never); + for (const row of LINES) await booted.driver.create(LINE, { ...row }, { bypassTenantAudit: true } as never); + return booted; +} + +describe('the base relation field\'s field-level read is judged on the joined path as on the FK-expand', () => { + /** A caller whose field permissions hide `line.opportunity`, and nothing else. */ + const FLS_HIDDEN = { userId: 'u_fls', tenantId: 'org_A' } as ExecutionContext; + const HIDDEN = new Set(['opportunity']); + let driver: SqliteWasmDriver; + let engine: ObjectQL; + + /** + * The security service's field answers, as the analytics door asks them: + * `u_fls` reads every field of the line but `opportunity`; every other + * answer is "no answer" (nothing judged). + */ + const security = { + canReadObject: async () => true, + getReadableFields: async (object: string, context?: ExecutionContext) => + object === LINE && context?.userId === 'u_fls' + ? ['id', 'organization_id', ...Object.keys(LINE_FIELDS)].filter((f) => !HIDDEN.has(f)) + : undefined, + getQueryableFields: async (object: string, context?: ExecutionContext) => + object === LINE && context?.userId === 'u_fls' + ? ['id', 'organization_id', ...Object.keys(LINE_FIELDS)].filter((f) => !HIDDEN.has(f)) + : undefined, + }; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + ({ engine, driver } = await seeded()); + // The field-level read gate on an aggregate's inputs, as plugin-security's + // step 2.5b judges them: every `groupBy` / `aggregations` field of the AST + // the chain sees, a hidden one refused 403 PERMISSION_DENIED. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.operation === 'aggregate' && op.object === LINE && op.context?.userId === 'u_fls') { + const referenced = [ + ...(op.ast?.groupBy ?? []).map((g: unknown) => (typeof g === 'string' ? g : (g as { field?: string })?.field)), + ...(op.ast?.aggregations ?? []).map((a: { field?: string }) => a?.field), + ]; + const forbidden = referenced.filter((f) => typeof f === 'string' && HIDDEN.has(f)); + if (forbidden.length > 0) { + throw Object.assign(new Error(`[Security] Field read denied: not permitted to aggregate [${forbidden.join(', ')}] on '${LINE}'`), { + code: 'PERMISSION_DENIED', status: 403, + }); + } + } + await next(); + }); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + const QUERY = { cube: dataset.name, dimensions: ['stage'], measures: ['line_count', 'amount_sum'] } as AnalyticsQuery; + + it('through the analytics door: the same 403 with the join wired as without it, and the engine is handed no relation group request', async () => { + const outcomes: unknown[] = []; + const joined = await pluginService(engine, true, outcomes, { security }); + const expanded = await pluginService(engine, false, [], { security }); + const viaJoin = await joined.query(QUERY, FLS_HIDDEN).then(() => null, (e: unknown) => e); + const viaExpand = await expanded.query(QUERY, FLS_HIDDEN).then(() => null, (e: unknown) => e); + expect(envelopeOf(viaJoin)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(envelopeOf(viaJoin)).toEqual(envelopeOf(viaExpand)); + expect(outcomes).toEqual([]); + // Control: the same composition joins for a caller who may read the field. + await joined.query(QUERY, ADMIN_A); + expect(outcomes).toEqual([{ kind: 'joined' }]); + }); + + /** The engine-internal request the plugin bridge hands, built by hand: no analytics door in front. */ + const request = () => ({ + relations: [{ field: 'opportunity', object: OPP, attrs: [{ attr: 'stage', alias: 'opp_stage' }], resolvedAlias: 'opp_resolved' }], + }) as { relations: unknown[]; outcome?: unknown }; + const AGGREGATIONS = [{ function: 'count', field: 'id', alias: 'n' }]; + + it('at the engine, past the analytics door: the relation group request is refused for that caller as the FK-expand\'s base read is', async () => { + const handed = request(); + const viaJoin = await engine.aggregate( + LINE, + { groupBy: ['region'], aggregations: AGGREGATIONS, context: FLS_HIDDEN } as never, + { [RELATION_GROUP_BY]: handed } as never, + ).then(() => null, (e: unknown) => e); + expect(envelopeOf(viaJoin)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(handed.outcome, 'nothing was joined').toBeUndefined(); + // The FK-expand's base read of the same dimension: grouped by the field itself. + const viaExpand = await engine.aggregate( + LINE, + { groupBy: ['region', 'opportunity'], aggregations: AGGREGATIONS, context: FLS_HIDDEN } as never, + ).then(() => null, (e: unknown) => e); + expect(envelopeOf(viaExpand)).toEqual(envelopeOf(viaJoin)); + }); + + it('control: a caller who may read the field is joined, and the statement is grouped by the join, not by the field', async () => { + const handed = request(); + const rows = await engine.aggregate( + LINE, + { groupBy: ['region'], aggregations: AGGREGATIONS, context: ADMIN_A } as never, + { [RELATION_GROUP_BY]: handed } as never, + ) as Record[]; + expect(handed.outcome).toEqual({ kind: 'joined' }); + expect(rows.every((r) => !('opportunity' in r))).toBe(true); + const lines = rows.reduce((n, r) => n + Number(r.n), 0); + expect(lines).toBe(LINES.filter((l) => l.organization_id === 'org_A').length); + }); +}); + +describe('[#22661] the related object\'s API exposure: the joined path answers it as the FK-expand does', () => { + const ENABLES: ReadonlyArray, { code: string; status: number }]> = [ + ['apiEnabled: false', { apiEnabled: false }, { code: 'OBJECT_API_DISABLED', status: 404 }], + ['an apiMethods whitelist that does not grant the aggregate read', { apiMethods: ['get'] }, { code: 'OBJECT_API_METHOD_NOT_ALLOWED', status: 405 }], + ]; + + for (const [declared, enable, refusal] of ENABLES) { + it(`a related object declaring ${declared}: ${refusal.status} ${refusal.code} on both paths, and the engine is handed no relation group request`, async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + const { engine, driver } = await seeded(); + try { + const outcomes: unknown[] = []; + // Registered while the related object is served, then re-declared: the + // query face asks the declaration at every query. + const joined = await pluginService(engine, true, outcomes); + const expanded = await pluginService(engine, false); + const QUERY = { cube: dataset.name, dimensions: ['stage'], measures: ['line_count'] } as AnalyticsQuery; + await joined.query(QUERY, ADMIN_A); + expect(outcomes, 'control: served while the related object is exposed').toEqual([{ kind: 'joined' }]); + outcomes.length = 0; + engine.registerObject({ name: OPP, label: 'Opportunity', fields: OPP_FIELDS, enable } as never); + const viaJoin = await joined.query(QUERY, ADMIN_A).then(() => null, (e: unknown) => e); + const viaExpand = await expanded.query(QUERY, ADMIN_A).then(() => null, (e: unknown) => e); + expect(envelopeOf(viaJoin)).toEqual(refusal); + expect(envelopeOf(viaJoin)).toEqual(envelopeOf(viaExpand)); + expect(outcomes, 'the related object was never read through the join').toEqual([]); + } finally { + await driver.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + } + }); + } +}); From 2f6eef1ff7e0e8914b948b6f8fe1019245f71b81 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:46:31 +0000 Subject: [PATCH 9/9] test(objectql): the chain sees the relation field as a group key, the driver's statement does not Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5nNrLRm8ssuwWcBVcw --- .changeset/33664-analytics-lookup-join.md | 2 +- .../objectql/src/relation-group-join.test.ts | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/.changeset/33664-analytics-lookup-join.md b/.changeset/33664-analytics-lookup-join.md index 4b67ee8f994..47335998f61 100644 --- a/.changeset/33664-analytics-lookup-join.md +++ b/.changeset/33664-analytics-lookup-join.md @@ -11,6 +11,6 @@ Metadata-protocol: none `POST /analytics/query` with a dimension through a lookup (`opportunity.stage` on a line-item cube) answered `500 DATABASE_ERROR` once the rows pointed at more distinct related records than the database binds parameters for: SQLite refused with `too many SQL variables`, PostgreSQL with a bind count overflow. The ObjectQL analytics path grouped the base rows by the foreign key, then read the related object with `id IN (every distinct key)` and re-bucketed the answer in the service. -On the SQL driver (every dialect, and the WASM SQLite driver) the same query is now one statement. The base aggregate `LEFT JOIN`s the related rows the caller may read and groups by the attribute in the database, with no id list and no bound-parameter ceiling. The related rows are the related object's own aggregate, planned as the caller, the read the old path ran without its id list. Its CRUD gate, read middlewares, row scope and field-level gate all apply, and the tenant wall bounds the joined table. A line whose related record is missing, unreadable, in another tenant or not set still counts under `(restricted)`, as before. Every bucket and measure is the one the old path answered. +On the SQL driver (every dialect, and the WASM SQLite driver) the same query is now one statement. The base aggregate `LEFT JOIN`s the related rows the caller may read and groups by the attribute in the database, with no id list and no bound-parameter ceiling. The related rows are the related object's own aggregate, planned as the caller, the read the old path ran without its id list. Its CRUD gate, read middlewares, row scope and field-level gate all apply, and the tenant wall bounds the joined table. The base read is still judged as grouped by the lookup field itself, so a caller who may not read that field is refused exactly as before. A line whose related record is missing, unreadable, in another tenant or not set still counts under `(restricted)`, as before. Every bucket and measure is the one the old path answered. The request is an engine-internal read option, so nothing a client sends changes and the public `groupBy` still refuses a dotted path. The in-memory driver, MongoDB, OData and Turso keep the old path for this dimension, unchanged. diff --git a/packages/objectql/src/relation-group-join.test.ts b/packages/objectql/src/relation-group-join.test.ts index 60844d39997..eb222cfc666 100644 --- a/packages/objectql/src/relation-group-join.test.ts +++ b/packages/objectql/src/relation-group-join.test.ts @@ -132,6 +132,32 @@ describe('relation group join — served as one driver statement whose related h }); }); + it('the base read is grouped by the relation field for every middleware, and only the driver\'s statement drops it', async () => { + // What the base read's chain sees, as a group-key guard reads it. + const seen: unknown[] = []; + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === LINE) seen.push(op.ast.groupBy); + await next(); + }); + rec.answer([{ region: 'emea', __rg0_a0: 'won', __rg0_resolved: 1, total: 10 }]); + const cases: Array<[unknown, unknown, unknown]> = [ + // [the request's groupBy, what the chain sees, what the driver is handed] + [['region'], ['region', 'opportunity'], ['region']], + [undefined, ['opportunity'], undefined], + // A base dimension naming the FK column itself keeps its one entry. + [['opportunity'], ['opportunity'], ['opportunity']], + ]; + for (const [groupBy, chain, statement] of cases) { + seen.length = 0; + rec.calls.length = 0; + const req = request(); + await engine.aggregate(LINE, { ...BASE_QUERY, groupBy } as never, { [RELATION_GROUP_BY]: req } as never); + expect(req.outcome).toEqual({ kind: 'joined' }); + expect(seen).toEqual([chain]); + expect(rec.calls.map((c) => c.ast.groupBy)).toEqual([statement]); + } + }); + it('a related read whose planned scope is the deny sentinel hands a null parent: nothing of the related object is readable', async () => { engine.registerMiddleware(async (op: any, next: () => Promise) => { if (op.object === OPP) op.ast.where = RLS_DENY_FILTER;