Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/34886-group-by-relation-path-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/objectql': patch
---

fix(objectql): `aggregate` refuses a dotted `groupBy` entry with `INVALID_FIELD` / 400, before any driver runs

Clause-②: no (narrowing)
Metadata-protocol: none

`groupBy` groups by the columns of the aggregated object itself. The REST query door already refused a dotted entry such as `purchase_order.name` at ingress, but a caller that reaches `engine.aggregate` past that door — the MCP `aggregate_records` tool, a flow, a hook — handed the dotted name to the driver as a qualified column. On SQLite a path of one or two hops came back as the driver's missing-column refusal (advising a schema sync that cannot help), and three or four hops (`purchase_order.requisition.requester.department.name`) came back `500 DATABASE_ERROR`; an engine that aggregates in memory put every row into one null group.

`engine.aggregate` now refuses any dotted `groupBy` entry that is not itself a field of the object, in either form (`'a.b'` or `{ field: 'a.b' }`, a date bucket included), with `INVALID_FIELD` / 400 at its position (`groupBy.N` or `groupBy.N.field`), naming the path and the depth `groupBy` serves (0 hops, the object's own columns by their bare names). No statement reaches the database. The refused set has three shapes: a path through a relation field (`purchase_order.requisition.requester.department.name`), a sub-path into a stored value (`address.city` on a JSON field), and the object's own name used as a qualifier (`po_line.amount`). For a relation path the refusal counts the hops and says to group by the relation field itself (one group per related record) or to aggregate the related object; for a multi-value relation it says to aggregate the related object; for the other two shapes it says to name the field without a qualifier, or to store the part in a field of its own.

**BREAKING**: a dotted `groupBy` entry that reaches `engine.aggregate` past the REST query door (the MCP `aggregate_records` tool, a flow, a hook) is now refused `INVALID_FIELD` / 400 before any statement runs, for all three shapes. What they answered before: a relation path, on SQLite, the driver's missing-column refusal (one or two hops) or `500 DATABASE_ERROR` (three or four), and on an engine that aggregates in memory one null group under 200; a JSON sub-path, on SQLite, the driver's own `INVALID_FIELD` / 400 after the statement ran, and in memory groups by the nested value; the object's own name as a qualifier, on SQLite, an answer under 200 grouped by the bare column. A caller that relied on either of the last two now gets a 400 and must drop the qualifier or store the part in a field of its own. It ships `patch` because no metadata an author writes changes (`Metadata-protocol: none`): the refused input is a runtime query that the REST query door already refused in the same three shapes, and the fix for a caller that hits it is in the refusal.

**Unchanged.** A `groupBy` naming the relation field itself (`purchase_order`), every other `groupBy` entry, an alias that contains a dot, and the REST door's own refusal of a dotted entry. A genuine database fault still answers `DATABASE_ERROR` / 500.

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: what moved is that engine.aggregate refuses a dotted groupBy entry (a relation path, a JSON sub-path, the object's own name as a qualifier), which the REST query door already refused. There is nothing for a migration to rewrite and no tombstone; the one-line fix for a refused query is in the refusal: group by the relation field itself, aggregate the related object, or drop the qualifier. -->
74 changes: 72 additions & 2 deletions packages/objectql/src/aggregate-query-shape-door.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@
* a name, `{ field }`, or a bucket — naming a VIRTUAL field, which no driver
* stores a column for — {@link assertGroupByTargetsAreStored}.
*
* [#34886] …and, in the same walk and ahead of it, a `groupBy` entry naming
* any dotted name the object does not declare: a path through relations
* (`purchase_order.requisition.name`), a path into a stored value
* (`address.city`), or the object's own name as a qualifier. `groupBy` serves
* the object's own columns by their exact names, 0 hops deep. Measured on
* `origin/main` `b3247ddbdc` through the HTTP MCP bridge over `SqlDriver` on
* SQLite, for a relation path: one or two hops came back as the driver's
* missing-column backstop (400, advising a schema sync), three or four hops as
* `DATABASE_ERROR` / 500. The other two shapes had answers of their own before:
* driver-memory grouped a path into a stored value by its nested value, and a
* SQL driver grouped by the object's own column under its qualifier.
*
* ## What ran before this door, measured on `origin/main` `cb0a2fcf4f`
*
* Through `findData` (the `POST /api/v1/data/:object/query` door) over three
Expand Down Expand Up @@ -98,7 +110,7 @@
*/

import { StandardErrorCode } from '@objectstack/spec/api';
import { isVirtualSearchField } from '@objectstack/spec/data';
import { isMultiValueField, isVirtualSearchField, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data';
import { declaredFieldClasses } from './having-filter.js';

type ShapeRefusal = Error & {
Expand Down Expand Up @@ -154,11 +166,52 @@ function virtualGroupMessage(object: string, path: string, field: string, type:
+ 'while the answer looked served.';
}

/**
* [#34886] How the head of a dotted `groupBy` name reads on the object: a
* single-valued relation, a multi-value one (which the multi-value group door
* refuses as a key of its own), or not a relation at all — a field of another
* kind (`address.city` into a stored value), or no field (`OBJECT.field`, the
* object's own name as a qualifier).
*/
type DottedHead = 'relation' | 'multi-relation' | 'not-relation';

/**
* [#34886] The refusal of a `groupBy` entry naming an undeclared dotted name:
* the position and the name, the rule (the object's own columns, by their bare
* names, 0 hops deep), then a way to ask instead that holds for the head.
* Only a relation head is described in hops.
*/
function dottedGroupMessage(
object: string, position: string, path: string, head: string, kind: DottedHead,
): string {
const rule = `groupBy groups by the columns of '${object}' itself, by their bare names (0 hops deep). `
+ 'The query was NOT run. ';
if (kind === 'not-relation') {
return `aggregate('${object}'): ${position} groups by '${path}', a dotted name that is not a field of `
+ `'${object}': ${rule}Name the field without a qualifier; to group by part of a stored value, `
+ 'store that part in a field of its own.';
}
const hops = path.split('.').length - 1;
return `aggregate('${object}'): ${position} groups by '${path}', a path ${hops} relation `
+ `hop${hops === 1 ? '' : 's'} deep: ${rule}`
+ (kind === 'relation'
? `Group by '${head}' itself (one group per related record), or aggregate the related object.`
: 'Aggregate the related object and group by its own field there.');
}

/**
* Refuse a `groupBy` entry of any form — a name, `{ field }`, or a
* `{ field, dateGranularity }` bucket — naming a field the object declares
* VIRTUAL (`formula`; the spec's `isVirtualSearchField`), `INVALID_FIELD` /
* 400 at the position it names. See the module header.
*
* [#34886] …and, first, an entry naming ANY dotted name the object does not
* declare — a path through relations, a path into a stored value
* (`address.city`), or the object's own name as a qualifier: `groupBy` serves
* the object's own columns by their exact names, 0 hops deep — the REST query
* door's rule at ingress, held here for the callers that reach the engine
* past that door (the MCP bridge, a flow, a hook). `INVALID_FIELD` / 400 at
* `groupBy.N` or `groupBy.N.field`.
*/
export function assertGroupByTargetsAreStored(
object: string,
Expand All @@ -174,7 +227,24 @@ export function assertGroupByTargetsAreStored(
const { field, dateGranularity } = named
? { field: entry, dateGranularity: undefined }
: entry as { field?: unknown; dateGranularity?: unknown };
if (typeof field !== 'string' || !Object.prototype.hasOwnProperty.call(fields, field)) continue;
if (typeof field !== 'string') continue;
if (field.includes('.') && !Object.prototype.hasOwnProperty.call(fields, field)) {
const position = named ? `groupBy.${i}` : `groupBy.${i}.field`;
const head = field.split('.')[0];
const headField = Object.prototype.hasOwnProperty.call(fields, head)
? (fields as Record<string, unknown>)[head]
: undefined;
const headDef = headField as { type?: unknown; multiple?: unknown } | undefined;
const kind: DottedHead = typeof headDef?.type !== 'string' || !REFERENCE_VALUE_TYPES.has(headDef.type)
? 'not-relation'
: isMultiValueField(headDef as never) ? 'multi-relation' : 'relation';
throw refusal(
'INVALID_FIELD',
dottedGroupMessage(object, position, field, head, kind),
{ field, fields: [field], object, param: 'groupBy', path: position },
);
}
if (!Object.prototype.hasOwnProperty.call(fields, field)) continue;
const declared = (fields as Record<string, { type?: unknown }>)[field];
if (!isVirtualSearchField(declared as never)) continue;
const type = String(declared?.type);
Expand Down
152 changes: 152 additions & 0 deletions packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* [#34886] `aggregate_records` grouped by a path through relations — the
* card's `purchase_order.requisition.requester.department.name`, four hops
* from a purchase-order line — over the HTTP MCP bridge (`buildMcpBridge`,
* `domains/mcp.ts`), the real `ObjectQL` engine and a real SQLite database.
*
* `groupBy` groups by the columns of the aggregated object itself: the REST
* query door refuses a dotted entry at ingress ("a related record's column
* cannot be a grouping target"), but the MCP bridge reaches `engine.aggregate`
* through `callData`, past that door. Measured on `origin/main` `b3247ddbdc`
* with `SqlDriver` on SQLite, before the engine door below: a path of one or
* two hops reached the database and came back as the driver's missing-column
* backstop (`INVALID_FIELD` / 400, advising a schema sync); three or four hops
* came back `DATABASE_ERROR` / 500, which an agent cannot read as "change the
* approach".
*
* Pinned: the engine refuses a relation path in `groupBy` at any depth with
* `INVALID_FIELD` / 400, naming the path at its position, before the driver
* runs any statement — on both bridge members `aggregate_records` calls (the
* uncut aggregate and the ordered-and-cut one), in both `groupBy` forms. The
* same arm refuses every other dotted name the object does not declare: a path
* into a stored value (`address.city` on a json field) and the object's own
* name as a qualifier, each worded without relation hops.
* CONTROL: grouping by the relation field itself (the supported depth) is
* served by the database. The tool's rendering of a 4xx refusal (code, status
* and message kept) is pinned in `@objectstack/mcp`.
*/

import { afterAll, beforeAll, describe, expect, it } from 'vitest';
// The bridge's module graph reaches a dynamic `import('@objectstack/metadata')`;
// paid here, at collection, never inside a clocked case.
import '@objectstack/metadata';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { buildMcpBridge } from './domains/mcp.js';
import type { HttpProtocolContext } from './http-dispatcher.js';

const lookup = (name: string, reference: string) => ({ name, label: name, type: 'lookup', reference });
const text = (name: string) => ({ name, label: name, type: 'text' });

const OBJECTS = [
{ name: 'rp_department', label: 'Department', fields: { name: text('name') } },
{ name: 'rp_requester', label: 'Requester', fields: { name: text('name'), department: lookup('department', 'rp_department') } },
{ name: 'rp_requisition', label: 'Requisition', fields: { name: text('name'), requester: lookup('requester', 'rp_requester') } },
{ name: 'rp_purchase_order', label: 'Purchase order', fields: { name: text('name'), requisition: lookup('requisition', 'rp_requisition') } },
{
name: 'rp_po_line',
label: 'Purchase order line',
fields: {
amount: { name: 'amount', label: 'Amount', type: 'number' },
purchase_order: lookup('purchase_order', 'rp_purchase_order'),
address: { name: 'address', label: 'Address', type: 'json' },
},
},
];
const LINE = 'rp_po_line';
const FOUR_HOPS = 'purchase_order.requisition.requester.department.name';
const SUM = [{ function: 'sum' as const, field: 'amount', alias: 'total' }];

async function caught(run: () => Promise<unknown>): Promise<any> {
return run().then(() => expect.fail('expected the aggregate to be refused, but it answered'), (e: unknown) => e);
}

describe('[#34886] aggregate_records grouped by a relation path, over a real SQLite database', () => {
let driver: SqlDriver;
let bridge: any;
const statements: string[] = [];

beforeAll(async () => {
driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
await driver.initObjects(OBJECTS as never);
const engine = new ObjectQL();
engine.registerDriver(driver, true);
await engine.init();
for (const def of OBJECTS) engine.registry.registerObject(def as any);
await driver.create('rp_department', { id: 'd1', name: 'Ops' });
await driver.create('rp_requester', { id: 'u1', name: 'Ann', department: 'd1' });
await driver.create('rp_requisition', { id: 'r1', name: 'R-1', requester: 'u1' });
await driver.create('rp_purchase_order', { id: 'po1', name: 'PO-1', requisition: 'r1' });
await driver.create('rp_purchase_order', { id: 'po2', name: 'PO-2', requisition: 'r1' });
await driver.create(LINE, { id: 'l1', amount: 10, purchase_order: 'po1', address: { city: 'Oslo' } });
await driver.create(LINE, { id: 'l2', amount: 5, purchase_order: 'po1', address: { city: 'Oslo' } });
await driver.create(LINE, { id: 'l3', amount: 7, purchase_order: 'po2', address: { city: 'Bergen' } });
(driver as unknown as { knex: { on: Function } }).knex.on('query', (q: { sql: string }) => { statements.push(q.sql); });
const deps = {
resolveService: async (_ctx: unknown, name: string) => (name === 'objectql' ? engine : undefined),
getObjectQL: async () => engine,
};
const context = { request: {}, executionContext: { isSystem: true } } as unknown as HttpProtocolContext;
bridge = buildMcpBridge(deps as any, context) as any;
});

afterAll(async () => {
await driver?.disconnect?.();
});

const grouped = () => statements.filter((s) => /group by/i.test(s));

it.each([
['four hops (the card)', FOUR_HOPS],
['three hops', 'purchase_order.requisition.requester.name'],
['one hop', 'purchase_order.name'],
])('%s: refused INVALID_FIELD / 400 naming the path, and no statement reaches the database', async (_label, path) => {
statements.length = 0;
const err = await caught(() => bridge.aggregate(LINE, { groupBy: [path], aggregations: SUM }));
expect({ code: err?.code, status: err?.status, field: err?.field, path: err?.path })
.toEqual({ code: 'INVALID_FIELD', status: 400, field: path, path: 'groupBy.0' });
expect(String(err.message)).toContain(path);
expect(statements, statements.join('\n')).toHaveLength(0);
});

// [#34886] The arm refuses ANY dotted name the object does not declare, not
// only a relation path; for a head that is no relation the words name no hops.
it.each([
['a path into a stored value (a json head)', 'address.city'],
["the object's own name as a qualifier (no field by that name)", `${LINE}.amount`],
])('%s: refused INVALID_FIELD / 400 at groupBy.0, worded without relation hops, and no statement runs', async (_label, path) => {
statements.length = 0;
const err = await caught(() => bridge.aggregate(LINE, { groupBy: [path], aggregations: SUM }));
expect({ code: err?.code, status: err?.status, field: err?.field, path: err?.path })
.toEqual({ code: 'INVALID_FIELD', status: 400, field: path, path: 'groupBy.0' });
expect(String(err.message)).toContain(path);
expect(String(err.message)).not.toMatch(/relation hop/);
expect(statements, statements.join('\n')).toHaveLength(0);
});

it('the object form is refused at its field position, after a plain key it keeps', async () => {
statements.length = 0;
const err = await caught(() => bridge.aggregate(LINE, { groupBy: ['purchase_order', { field: FOUR_HOPS }], aggregations: SUM }));
expect({ code: err?.code, status: err?.status, field: err?.field, path: err?.path })
.toEqual({ code: 'INVALID_FIELD', status: 400, field: FOUR_HOPS, path: 'groupBy.1.field' });
expect(statements, statements.join('\n')).toHaveLength(0);
});

it('the ordered and cut member (an orderBy or a limit) is refused the same way', async () => {
statements.length = 0;
const err = await caught(() => bridge.aggregateGroups(LINE, {
groupBy: [FOUR_HOPS], aggregations: SUM, orderBy: [{ field: 'total', order: 'desc' }], limit: 5,
}));
expect({ code: err?.code, status: err?.status, field: err?.field, path: err?.path })
.toEqual({ code: 'INVALID_FIELD', status: 400, field: FOUR_HOPS, path: 'groupBy.0' });
expect(statements, statements.join('\n')).toHaveLength(0);
});

it('CONTROL — grouping by the relation field itself is answered by the database', async () => {
statements.length = 0;
const rows = await bridge.aggregate(LINE, { groupBy: ['purchase_order'], aggregations: SUM });
expect([...rows].sort((a: any, b: any) => String(a.purchase_order).localeCompare(String(b.purchase_order))))
.toEqual([{ purchase_order: 'po1', total: 15 }, { purchase_order: 'po2', total: 7 }]);
expect(grouped(), statements.join('\n')).toHaveLength(1);
});
});
Loading