From 6f8c1651b9b1578b6e656094e5a0899acfa9de39 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:39:53 +0000 Subject: [PATCH 1/8] test(runtime): aggregate grouped by a relation path over the MCP bridge (red on main) Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- ...p-aggregate-relation-path-group-by.test.ts | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts diff --git a/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts b/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts new file mode 100644 index 00000000000..5515d7b61e4 --- /dev/null +++ b/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts @@ -0,0 +1,129 @@ +/** + * [#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. + * 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') }, + }, +]; +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): Promise { + 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' }); + await driver.create(LINE, { id: 'l2', amount: 5, purchase_order: 'po1' }); + await driver.create(LINE, { id: 'l3', amount: 7, purchase_order: 'po2' }); + (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(grouped(), 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(grouped(), 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 }).toEqual({ code: 'INVALID_FIELD', status: 400, field: FOUR_HOPS }); + expect(grouped(), 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); + }); +}); From b4aea12bb2a0ba1841e2c3c966992fee3bfd70a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:49:09 +0000 Subject: [PATCH 2/8] fix(objectql): aggregate refuses a groupBy path through relations before any driver Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .../src/aggregate-query-shape-door.ts | 67 ++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/packages/objectql/src/aggregate-query-shape-door.ts b/packages/objectql/src/aggregate-query-shape-door.ts index 99b3bf59e3c..4a2b032cd9f 100644 --- a/packages/objectql/src/aggregate-query-shape-door.ts +++ b/packages/objectql/src/aggregate-query-shape-door.ts @@ -16,6 +16,13 @@ * 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 a + * dotted path through relations (`purchase_order.requisition.name`): `groupBy` + * serves the object's own columns, 0 hops deep. Measured on `origin/main` + * `b3247ddbdc` through the HTTP MCP bridge over `SqlDriver` on SQLite: 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. + * * ## What ran before this door, measured on `origin/main` `cb0a2fcf4f` * * Through `findData` (the `POST /api/v1/data/:object/query` door) over three @@ -98,7 +105,7 @@ */ import { StandardErrorCode } from '@objectstack/spec/api'; -import { isVirtualSearchField } from '@objectstack/spec/data'; +import { isVirtualSearchField, referenceTargetOf } from '@objectstack/spec/data'; import { declaredFieldClasses } from './having-filter.js'; type ShapeRefusal = Error & { @@ -154,11 +161,53 @@ function virtualGroupMessage(object: string, path: string, field: string, type: + 'while the answer looked served.'; } +/** + * The object a declared field references, or `undefined` — read only to word a + * refusal, so a reference carrier the spec cannot read words it as a + * non-relation instead of replacing the refusal with the reader's own throw. + */ +function relationTargetOf(declared: unknown): string | undefined { + try { + return referenceTargetOf(declared); + } catch { + return undefined; + } +} + +/** + * [#34886] The refusal of a `groupBy` entry naming a path through relations + * (`purchase_order.requisition.name`): the position, the path and its depth, + * the depth `groupBy` serves (0 hops: the aggregated object's own columns), + * then the two ways to ask instead. + */ +function relationPathGroupMessage( + object: string, position: string, path: string, head: string, headIsRelation: boolean, +): string { + const hops = path.split('.').length - 1; + return `aggregate('${object}'): ${position} groups by '${path}', a path ${hops} relation ` + + `hop${hops === 1 ? '' : 's'} deep, but groupBy groups by the columns of '${object}' itself — ` + + 'the deepest path it serves is 0 hops, so a related record\'s column cannot be a grouping target. ' + + 'The query was NOT run. ' + + (headIsRelation + ? `Group by the relation field '${head}' itself (one group per related record), or aggregate ` + + 'the related object and group by its own field there.' + : `'${head}' is not a relation field of '${object}': name a field of '${object}' itself.`) + + ' A dotted path reached the database as a qualified column name that no table here has: a ' + + 'backend refused it as a missing column or as a statement it could not run, and an engine that ' + + 'aggregates in memory put every row into one null group.'; +} + /** * 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 a DOTTED path the object does not + * declare (a path through relations): `groupBy` serves the object's own + * columns, 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, @@ -174,7 +223,21 @@ 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)[head] + : undefined; + const headIsRelation = headField !== undefined && relationTargetOf(headField) !== undefined; + throw refusal( + 'INVALID_FIELD', + relationPathGroupMessage(object, position, field, head, headIsRelation), + { field, fields: [field], object, param: 'groupBy', path: position }, + ); + } + if (!Object.prototype.hasOwnProperty.call(fields, field)) continue; const declared = (fields as Record)[field]; if (!isVirtualSearchField(declared as never)) continue; const type = String(declared?.type); From 12e7094169ed20d2086edbd151fbead45b392520 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:53:01 +0000 Subject: [PATCH 3/8] fix(objectql): word a dotted group path whose head is no relation as a dotted path Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- packages/objectql/src/aggregate-query-shape-door.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/objectql/src/aggregate-query-shape-door.ts b/packages/objectql/src/aggregate-query-shape-door.ts index 4a2b032cd9f..3543e1b39cb 100644 --- a/packages/objectql/src/aggregate-query-shape-door.ts +++ b/packages/objectql/src/aggregate-query-shape-door.ts @@ -184,8 +184,8 @@ function relationPathGroupMessage( object: string, position: string, path: string, head: string, headIsRelation: boolean, ): string { const hops = path.split('.').length - 1; - return `aggregate('${object}'): ${position} groups by '${path}', a path ${hops} relation ` - + `hop${hops === 1 ? '' : 's'} deep, but groupBy groups by the columns of '${object}' itself — ` + const depth = headIsRelation ? `a path ${hops} relation hop${hops === 1 ? '' : 's'} deep` : 'a dotted path'; + return `aggregate('${object}'): ${position} groups by '${path}', ${depth}, but groupBy groups by the columns of '${object}' itself — ` + 'the deepest path it serves is 0 hops, so a related record\'s column cannot be a grouping target. ' + 'The query was NOT run. ' + (headIsRelation From 338e378846e8448bbb87897a335e054fe4cefe18 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:59:46 +0000 Subject: [PATCH 4/8] fix(objectql): read a group path's head as a relation by its declared type Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .../objectql/src/aggregate-query-shape-door.ts | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/packages/objectql/src/aggregate-query-shape-door.ts b/packages/objectql/src/aggregate-query-shape-door.ts index 3543e1b39cb..003067de8d5 100644 --- a/packages/objectql/src/aggregate-query-shape-door.ts +++ b/packages/objectql/src/aggregate-query-shape-door.ts @@ -105,7 +105,7 @@ */ import { StandardErrorCode } from '@objectstack/spec/api'; -import { isVirtualSearchField, referenceTargetOf } from '@objectstack/spec/data'; +import { isVirtualSearchField, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; import { declaredFieldClasses } from './having-filter.js'; type ShapeRefusal = Error & { @@ -161,19 +161,6 @@ function virtualGroupMessage(object: string, path: string, field: string, type: + 'while the answer looked served.'; } -/** - * The object a declared field references, or `undefined` — read only to word a - * refusal, so a reference carrier the spec cannot read words it as a - * non-relation instead of replacing the refusal with the reader's own throw. - */ -function relationTargetOf(declared: unknown): string | undefined { - try { - return referenceTargetOf(declared); - } catch { - return undefined; - } -} - /** * [#34886] The refusal of a `groupBy` entry naming a path through relations * (`purchase_order.requisition.name`): the position, the path and its depth, @@ -230,7 +217,8 @@ export function assertGroupByTargetsAreStored( const headField = Object.prototype.hasOwnProperty.call(fields, head) ? (fields as Record)[head] : undefined; - const headIsRelation = headField !== undefined && relationTargetOf(headField) !== undefined; + const headType = (headField as { type?: unknown } | undefined)?.type; + const headIsRelation = typeof headType === 'string' && REFERENCE_VALUE_TYPES.has(headType); throw refusal( 'INVALID_FIELD', relationPathGroupMessage(object, position, field, head, headIsRelation), From b3531dac689749cb194d2d788a752e896e2ce01c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 10:03:11 +0000 Subject: [PATCH 5/8] chore(changeset): objectql refuses a groupBy relation path Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .changeset/34886-group-by-relation-path-refusal.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/34886-group-by-relation-path-refusal.md diff --git a/.changeset/34886-group-by-relation-path-refusal.md b/.changeset/34886-group-by-relation-path-refusal.md new file mode 100644 index 00000000000..d1c4343191d --- /dev/null +++ b/.changeset/34886-group-by-relation-path-refusal.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): `aggregate` refuses a `groupBy` path through relations with `INVALID_FIELD` / 400, before any driver runs + +Clause-②: no +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 such an entry, 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, its depth in relation hops and the depth `groupBy` serves (0 hops). No statement reaches the database. When the path starts at a relation field, the refusal says to group by that field itself (one group per related record) or to aggregate the related object. + +**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. From 874d01cae499de151b1d58c4993048873639bc7a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:13:54 +0000 Subject: [PATCH 6/8] chore(changeset): declare the groupBy relation-path refusal a narrowing Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .changeset/34886-group-by-relation-path-refusal.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.changeset/34886-group-by-relation-path-refusal.md b/.changeset/34886-group-by-relation-path-refusal.md index d1c4343191d..a2479683e09 100644 --- a/.changeset/34886-group-by-relation-path-refusal.md +++ b/.changeset/34886-group-by-relation-path-refusal.md @@ -4,11 +4,15 @@ fix(objectql): `aggregate` refuses a `groupBy` path through relations with `INVALID_FIELD` / 400, before any driver runs -Clause-②: no +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 such an entry, 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, its depth in relation hops and the depth `groupBy` serves (0 hops). No statement reaches the database. When the path starts at a relation field, the refusal says to group by that field itself (one group per related record) or to aggregate the related object. +**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 where it used to answer: an engine that aggregates in memory served it as one null group under 200, and a SQL driver ran the statement. It ships `patch` because no metadata an author writes changes (`Metadata-protocol: none`): the refused input is a runtime query that never had a defined answer, and the REST query door already refused the same entry. The fix for a caller that hits it is in the refusal: group by the relation field itself, or aggregate the related object. + **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. + + From ce0a9509e5332723e148c7c34a7341a2748b8141 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:13:53 +0000 Subject: [PATCH 7/8] fix(objectql): word a dotted group name by its head, and pin the non-relation arm Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb Co-authored-by: Claude --- .../src/aggregate-query-shape-door.ts | 83 ++++++++++++------- ...p-aggregate-relation-path-group-by.test.ts | 41 +++++++-- 2 files changed, 83 insertions(+), 41 deletions(-) diff --git a/packages/objectql/src/aggregate-query-shape-door.ts b/packages/objectql/src/aggregate-query-shape-door.ts index 003067de8d5..196c1d384d3 100644 --- a/packages/objectql/src/aggregate-query-shape-door.ts +++ b/packages/objectql/src/aggregate-query-shape-door.ts @@ -16,12 +16,17 @@ * 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 a - * dotted path through relations (`purchase_order.requisition.name`): `groupBy` - * serves the object's own columns, 0 hops deep. Measured on `origin/main` - * `b3247ddbdc` through the HTTP MCP bridge over `SqlDriver` on SQLite: 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. + * [#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` * @@ -105,7 +110,7 @@ */ import { StandardErrorCode } from '@objectstack/spec/api'; -import { isVirtualSearchField, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; +import { isMultiValueField, isVirtualSearchField, REFERENCE_VALUE_TYPES } from '@objectstack/spec/data'; import { declaredFieldClasses } from './having-filter.js'; type ShapeRefusal = Error & { @@ -162,26 +167,36 @@ function virtualGroupMessage(object: string, path: string, field: string, type: } /** - * [#34886] The refusal of a `groupBy` entry naming a path through relations - * (`purchase_order.requisition.name`): the position, the path and its depth, - * the depth `groupBy` serves (0 hops: the aggregated object's own columns), - * then the two ways to ask instead. + * [#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). */ -function relationPathGroupMessage( - object: string, position: string, path: string, head: string, headIsRelation: boolean, +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; - const depth = headIsRelation ? `a path ${hops} relation hop${hops === 1 ? '' : 's'} deep` : 'a dotted path'; - return `aggregate('${object}'): ${position} groups by '${path}', ${depth}, but groupBy groups by the columns of '${object}' itself — ` - + 'the deepest path it serves is 0 hops, so a related record\'s column cannot be a grouping target. ' - + 'The query was NOT run. ' - + (headIsRelation - ? `Group by the relation field '${head}' itself (one group per related record), or aggregate ` - + 'the related object and group by its own field there.' - : `'${head}' is not a relation field of '${object}': name a field of '${object}' itself.`) - + ' A dotted path reached the database as a qualified column name that no table here has: a ' - + 'backend refused it as a missing column or as a statement it could not run, and an engine that ' - + 'aggregates in memory put every row into one null group.'; + 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.'); } /** @@ -190,11 +205,13 @@ function relationPathGroupMessage( * VIRTUAL (`formula`; the spec's `isVirtualSearchField`), `INVALID_FIELD` / * 400 at the position it names. See the module header. * - * [#34886] …and, first, an entry naming a DOTTED path the object does not - * declare (a path through relations): `groupBy` serves the object's own - * columns, 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`. + * [#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, @@ -217,11 +234,13 @@ export function assertGroupByTargetsAreStored( const headField = Object.prototype.hasOwnProperty.call(fields, head) ? (fields as Record)[head] : undefined; - const headType = (headField as { type?: unknown } | undefined)?.type; - const headIsRelation = typeof headType === 'string' && REFERENCE_VALUE_TYPES.has(headType); + 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', - relationPathGroupMessage(object, position, field, head, headIsRelation), + dottedGroupMessage(object, position, field, head, kind), { field, fields: [field], object, param: 'groupBy', path: position }, ); } diff --git a/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts b/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts index 5515d7b61e4..b535d7db9bf 100644 --- a/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts +++ b/packages/runtime/src/mcp-aggregate-relation-path-group-by.test.ts @@ -17,7 +17,10 @@ * 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. + * 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`. @@ -43,7 +46,11 @@ const OBJECTS = [ { name: 'rp_po_line', label: 'Purchase order line', - fields: { amount: { name: 'amount', label: 'Amount', type: 'number' }, purchase_order: lookup('purchase_order', 'rp_purchase_order') }, + 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'; @@ -71,9 +78,9 @@ describe('[#34886] aggregate_records grouped by a relation path, over a real SQL 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' }); - await driver.create(LINE, { id: 'l2', amount: 5, purchase_order: 'po1' }); - await driver.create(LINE, { id: 'l3', amount: 7, purchase_order: 'po2' }); + 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), @@ -99,7 +106,22 @@ describe('[#34886] aggregate_records grouped by a relation path, over a real SQL 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(grouped(), statements.join('\n')).toHaveLength(0); + 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 () => { @@ -107,7 +129,7 @@ describe('[#34886] aggregate_records grouped by a relation path, over a real SQL 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(grouped(), statements.join('\n')).toHaveLength(0); + expect(statements, statements.join('\n')).toHaveLength(0); }); it('the ordered and cut member (an orderBy or a limit) is refused the same way', async () => { @@ -115,8 +137,9 @@ describe('[#34886] aggregate_records grouped by a relation path, over a real SQL 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 }).toEqual({ code: 'INVALID_FIELD', status: 400, field: FOUR_HOPS }); - expect(grouped(), statements.join('\n')).toHaveLength(0); + 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 () => { From e8b311e4c0576d7e386d974889d82f98d9a4dcb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 14:06:43 +0000 Subject: [PATCH 8/8] docs(changeset): name the whole refused groupBy set in the BREAKING line The refusal covers a relation path, a JSON sub-path and the object's own name as a qualifier; the BREAKING paragraph now names all three and what each answered before, without a null-group claim for the last two. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .changeset/34886-group-by-relation-path-refusal.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/34886-group-by-relation-path-refusal.md b/.changeset/34886-group-by-relation-path-refusal.md index a2479683e09..6f1c027ec59 100644 --- a/.changeset/34886-group-by-relation-path-refusal.md +++ b/.changeset/34886-group-by-relation-path-refusal.md @@ -2,17 +2,17 @@ '@objectstack/objectql': patch --- -fix(objectql): `aggregate` refuses a `groupBy` path through relations with `INVALID_FIELD` / 400, before any driver runs +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 such an entry, 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, its depth in relation hops and the depth `groupBy` serves (0 hops). No statement reaches the database. When the path starts at a relation field, the refusal says to group by that field itself (one group per related record) or to aggregate the related object. +`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 where it used to answer: an engine that aggregates in memory served it as one null group under 200, and a SQL driver ran the statement. It ships `patch` because no metadata an author writes changes (`Metadata-protocol: none`): the refused input is a runtime query that never had a defined answer, and the REST query door already refused the same entry. The fix for a caller that hits it is in the refusal: group by the relation field itself, or aggregate the related object. +**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. - +