diff --git a/.changeset/35145-mcp-latest-per.md b/.changeset/35145-mcp-latest-per.md new file mode 100644 index 00000000000..557bee83708 --- /dev/null +++ b/.changeset/35145-mcp-latest-per.md @@ -0,0 +1,23 @@ +--- +'@objectstack/mcp': patch +'@objectstack/objectql': patch +'@objectstack/driver-sql': patch +'@objectstack/driver-turso': patch +'@objectstack/metadata-protocol': patch +'@objectstack/runtime': patch +--- + +feat(mcp): "each X with its latest Y" in one `query_records` call — `latestPer` + +Clause-②: yes (widening): a new read form on the published MCP tool surface. Judged from the card content; the build confirms it +Metadata-protocol: none + +`query_records` takes `latestPer: { by, orderBy }`: one row per group, the group's first row in the given order. `by` names 1 to 3 fields, `orderBy` 1 to 3 keys (`asc` / `desc`); a tie goes to the record id in the direction of the last key, and an empty order value ranks last. "Each account with its latest deal" is `{ objectName: 'crm_opportunity', latestPer: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] } }`. + +- The row is chosen among the rows the caller may read and the `where` admits: a group whose newest row is hidden from the caller answers its newest readable row, never the hidden one and never nothing. The organization wall holds inside the choice. Field masking still applies to the returned rows. +- A partition or order field the caller may not read is refused as it is in `orderBy`; a computed, JSON or multi-value field, or a dotted path, is refused as a partition or order field. +- `limit` counts groups, capped at the tool's `maxLimit` like any list. The answer is `{ object, records, hasMore }` and never a `total`; when more groups exist than came back it carries `truncated: true`. +- Served by the SQL driver (Postgres, MySQL, SQLite) and by `driver-sqlite-wasm` and the Turso driver on a local or embedded-replica database: the driver compiles a `ROW_NUMBER()` window over the read's own scoped selection. Every other driver (in-memory, Turso's remote connection, MongoDB), an object with an `afterFind` hook and an object with object-scoped read middleware refuse with `INVALID_QUERY` / 400 before anything is read. The Turso driver's remote face refuses the directive itself too. +- New exports: `LATEST_PER`, `LATEST_PER_MAX_KEYS` and the `LatestPerRequest` / `LatestPerOrder` / `LatestPerOutcome` types from `@objectstack/objectql`; `LATEST_PER_DIRECTIVE`, `latestPerDirectiveOf` and the `LatestPerDirective` / `LatestPerDirectiveOrder` types from `@objectstack/driver-sql`; `McpLatestPer` from `@objectstack/mcp`. The request rides an in-process read option, never a wire or query key; `@objectstack/spec` is unchanged. + +Without `latestPer`, `query_records` and every read are unchanged. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 486bae3cf60..7e40de20c5c 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -280,6 +280,39 @@ service is installed: | `list_datasets` | List the governed datasets (business metrics) you may query: their measures and dimensions with business labels, descriptions and synonyms, and which of the question's words each one matches exactly | | `query_dataset` | Compute a governed metric by the names `list_datasets` gives; the answer carries its provenance (the dataset and measures used) | +### Each X with its latest Y: `latestPer` + +"Each account with its latest deal" is one `query_records` call. `latestPer` +names the groups and the order that picks each group's row: + +```json +{ + "objectName": "crm_opportunity", + "where": { "stage": { "$ne": "closed_won" } }, + "latestPer": { "by": ["account"], "orderBy": [{ "field": "close_date", "order": "desc" }] } +} +``` + +- `by` takes 1 to 3 fields; `orderBy` takes 1 to 3 keys, each `asc` or `desc`. + The answer is one row per group: the group's first row in that order. A tie + goes to the record id, in the direction of the last key; an empty order value + ranks last. +- The row is chosen among the rows the caller may read and the `where` admits: + a group whose newest row is hidden from the caller answers its newest row the + caller can read. Your own `orderBy`, `fields` and `offset` apply to the + answered rows. +- `limit` counts groups (capped at 50, like any list). The answer is + `{ object, records, hasMore }` with no `total`; when more groups exist than + came back it also carries `truncated: true`. +- A partition or order field the caller may not read is refused, as it is in + `orderBy`. A computed, JSON or multi-value field, or a dotted path, is refused + as a partition or order field. +- The SQL drivers serve it (Postgres, MySQL, SQLite, and Turso on a local or + embedded-replica database). Elsewhere (the in-memory driver, Turso's remote + connection, MongoDB) the call is refused with `INVALID_QUERY` before anything + is read, as it is for an object with an `afterFind` hook or object-scoped read + middleware. + ### Governed metrics and the `initialize` instructions `list_datasets` and `query_dataset` are registered with the `data:read` scope, diff --git a/packages/drivers/driver-sql/src/index.ts b/packages/drivers/driver-sql/src/index.ts index 78aa5d325f0..720ac0767f9 100644 --- a/packages/drivers/driver-sql/src/index.ts +++ b/packages/drivers/driver-sql/src/index.ts @@ -46,6 +46,10 @@ export { UnsupportedDialectEmissionError, renderDialectEmissionRefusal, } from './dialect-emission-refusal.js'; +// [latest per group] The window directive `find` compiles, so a subclass that +// answers `find` on another transport (Turso's remote face) can tell it rode in. +export { LATEST_PER_DIRECTIVE, latestPerDirectiveOf } from './sql-driver-latest-per.js'; +export type { LatestPerDirective, LatestPerDirectiveOrder } from './sql-driver-latest-per.js'; // [ADR-0131 D9] The autonumber counter's refusal of an organization-less row on // a tenant table — exported for the same reason: a caller recognises it by `code`. export { diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 8650d66a611..ddd18cc8471 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -41,6 +41,7 @@ import { import type { SqlDriver } from './sql-driver.js'; import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js'; import { StandardErrorCode } from '@objectstack/spec/api'; +import { latestPerDirectiveOf, latestPerIdSubquery } from './sql-driver-latest-per.js'; /** * [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its @@ -154,7 +155,7 @@ export class CrudFacet { * cited that as agreement, which it was not; objectstack#4419.) The * obligation the contract states is on `find`, and this keeps it there. */ - static async findRows(this: Pick, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise { + static async findRows(this: Pick, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise { // [#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); @@ -169,6 +170,10 @@ export class CrudFacet { // whether the statement HAS a sort to drop, instead of asking whether the // caller supplied one — since #4363 those are different questions. const orderKeys = this.orderKeysFor(object, query, { singleRowLookup }); + // [latest per group] One row per group, when the engine handed the window + // directive (`sql-driver-latest-per.ts`): one more predicate on the same + // statement, so every clause below holds for it unchanged. + const latestPer = latestPerDirectiveOf(query); // Build everything EXCEPT the SELECT list, so the unknown-column retry // below can rebuild without re-deriving where/order/pagination. @@ -181,6 +186,12 @@ export class CrudFacet { if (query.where) { this.applyFilters(b, query.where, options); } + if (latestPer !== undefined) { + b.whereIn( + this.remoteColumn(object, 'id', 'id'), + latestPerIdSubquery.call(this, object, query.where, latestPer, options), + ); + } // ORDER BY if (withOrderBy) { diff --git a/packages/drivers/driver-sql/src/sql-driver-latest-per.test.ts b/packages/drivers/driver-sql/src/sql-driver-latest-per.test.ts new file mode 100644 index 00000000000..66a740dad27 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-latest-per.test.ts @@ -0,0 +1,144 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [latest per group] `find()` compiles the window directive the engine hands + * it (objectql `latest-per.ts`) into its own statement: one more predicate, + * `id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY … + * ORDER BY …, id) rn FROM t WHERE AND ) w WHERE rn = 1)`. + * + * Pinned here: one row per group, the order's first row, ties broken by id in + * the last key's direction, a NULL order value ranked last; the window chosen + * among the rows the read's `where` admits (a group whose newest row the + * `where` hides answers its newest admitted row) and inside the tenant wall + * (another tenant's newer row never wins a group); the read's own ORDER BY, + * limit, offset and projection applied to the groups; no helper column on the + * rows; and a malformed directive 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 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 { LATEST_PER_DIRECTIVE, type LatestPerDirective } from './sql-driver-latest-per.js'; + +const TABLE = 'os_latest_per_deal'; + +/** + * Deals by account and owner. Account `a1`: d3 is newest; `a2`: d5 and d6 tie + * on the date (d6 wins on id, descending); `a3`: d8 has no date and ranks last + * whatever the direction; `ab` is another tenant's account, and `a1` carries + * one more deal, newer than all, in another tenant (xb). + */ +const DEALS = [ + { id: 'd1', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-01-10', amount: 10, organization_id: 'org_a' }, + { id: 'd2', account: 'a1', owner: 'u2', stage: 'lost', close_date: '2026-02-10', amount: 20, organization_id: 'org_a' }, + { id: 'd3', account: 'a1', owner: 'u1', stage: 'hidden', close_date: '2026-03-10', amount: 30, organization_id: 'org_a' }, + { id: 'd4', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-01-05', amount: 40, organization_id: 'org_a' }, + { id: 'd5', account: 'a2', owner: 'u1', stage: 'won', close_date: '2026-04-01', amount: 50, organization_id: 'org_a' }, + { id: 'd6', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-04-01', amount: 60, organization_id: 'org_a' }, + { id: 'd7', account: 'a3', owner: 'u1', stage: 'won', close_date: '2026-01-01', amount: 70, organization_id: 'org_a' }, + { id: 'd8', account: 'a3', owner: 'u1', stage: 'won', close_date: null, amount: 80, organization_id: 'org_a' }, + { id: 'xb', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-12-31', amount: 90, organization_id: 'org_b' }, + { id: 'yb', account: 'ab', owner: 'u9', stage: 'won', close_date: '2026-06-01', amount: 99, organization_id: 'org_b' }, +]; + +const latestBy = (by: string[], orderBy: LatestPerDirective['orderBy']): LatestPerDirective => ({ by, orderBy }); +const NEWEST_PER_ACCOUNT = latestBy(['account'], [{ field: 'close_date', order: 'desc' }]); + +const query = (directive: unknown, over: Partial = {}): DriverQuery => ({ + orderBy: [{ field: 'account', order: 'asc' }], + ...over, + [LATEST_PER_DIRECTIVE]: directive, +} as unknown as DriverQuery); + +const ids = (rows: Array>) => rows.map((r) => String(r.id)); + +function declareCell(cell: DialectCell): void { + describe(`[latest per group] driver-sql — find answers one row per group (${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 ${TABLE}`).catch(() => {}); + await driver.initObjects([ + { + name: TABLE, + fields: { + account: { type: 'text' }, owner: { type: 'text' }, stage: { type: 'text' }, + close_date: { type: 'date' }, amount: { type: 'number' }, organization_id: { type: 'text' }, + }, + }, + ] as never); + for (const row of DEALS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true }); + }); + + afterAll(async () => { + await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + it('one row per group: the newest; a tie goes to the larger id; a NULL date ranks last', async () => { + const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); + expect(ids(rows)).toEqual(['d3', 'd6', 'd7']); + }); + + it('ascending: the earliest per group, a tie to the smaller id, NULL still last', async () => { + const rows = await driver.find(TABLE, query(latestBy(['account'], [{ field: 'close_date', order: 'asc' }])), { tenantId: 'org_a' }); + expect(ids(rows)).toEqual(['d1', 'd4', 'd7']); + }); + + it('a group whose newest row the where hides answers its newest ADMITTED row, never nothing', async () => { + const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { where: { stage: { $ne: 'hidden' } } }), { tenantId: 'org_a' }); + expect(ids(rows)).toEqual(['d2', 'd6', 'd7']); + }); + + it('inside the tenant wall: another tenant\'s newer row never wins, its groups never appear', async () => { + const a = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); + expect(ids(a)).not.toContain('xb'); + expect(ids(a)).not.toContain('yb'); + const b = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_b' }); + expect(ids(b)).toEqual(['xb', 'yb']); + }); + + it('several partition fields: one row per (account, owner)', async () => { + const rows = await driver.find(TABLE, query(latestBy(['account', 'owner'], [{ field: 'close_date', order: 'desc' }]), { + orderBy: [{ field: 'id', order: 'asc' }], + }), { tenantId: 'org_a' }); + expect(ids(rows)).toEqual(['d2', 'd3', 'd5', 'd6', 'd7']); + }); + + it('the read\'s own ORDER BY, limit, offset and projection apply to the groups; no helper column', async () => { + const page = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { + orderBy: [{ field: 'amount', order: 'desc' }], + limit: 2, + offset: 1, + fields: ['id', 'amount'], + }), { tenantId: 'org_a' }); + // Groups by amount desc: d7 (70), d6 (60), d3 (30) → offset 1, limit 2. + expect(ids(page)).toEqual(['d6', 'd3']); + for (const row of page) expect(Object.keys(row).sort()).toEqual(['amount', 'id']); + const full = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' }); + for (const row of full) expect(Object.keys(row).some((k) => k.startsWith('__os_latest_per'))).toBe(false); + }); + + it('control: the same read without the directive answers every row', async () => { + const rows = await driver.find(TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery, { tenantId: 'org_a' }); + expect(ids(rows)).toEqual(['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8']); + }); + + it('a malformed directive is refused before anything compiles', async () => { + const err = await driver.find(TABLE, query({ by: [], orderBy: [] }), { tenantId: 'org_a' }) + .then(() => null, (e: Error) => e); + expect(err?.message).toMatch(/latest-per directive is malformed/); + }); + }); +} + +for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'find latest per group', declareCell); diff --git a/packages/drivers/driver-sql/src/sql-driver-latest-per.ts b/packages/drivers/driver-sql/src/sql-driver-latest-per.ts new file mode 100644 index 00000000000..2427b4e357f --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-latest-per.ts @@ -0,0 +1,139 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * One row per group, compiled into `find`'s own statement. + * + * The engine (`@objectstack/objectql`, `latest-per.ts`) hands `find` an AST + * carrying {@link LATEST_PER_DIRECTIVE}: the fields that form a group and the + * order whose first row is the group's answer. `find` keeps every clause it + * always builds — the tenant wall, the read's final `where`, its ORDER BY, + * paging, projection and presentation — and adds ONE predicate: + * + * ```sql + * id IN (SELECT id FROM ( + * SELECT id, ROW_NUMBER() OVER ( + * PARTITION BY p1, p2 + * ORDER BY CASE WHEN o1 IS NULL THEN 1 ELSE 0 END, o1 DESC, …, id DESC) AS rn + * FROM table + * WHERE AND ) w + * WHERE rn = 1) + * ``` + * + * - **The window runs over the fully scoped read.** The inner statement is + * scoped by {@link SqlDriver.applyTenantScope} with the read's own options, + * and filtered by the same final `where` the outer statement carries — the + * one the engine composed with every row-level scope. So a group's answer is + * its first row among the rows this read may return, never a row the read + * would have hidden. + * - **Ties are broken by `id`**, in the direction of the last order key, so the + * answer is deterministic whatever the data. + * - **A NULL order value ranks last** in either direction, on every dialect + * (the CASE key), so "latest" never means "the one with no date". + * - **No helper column reaches the rows**: the row number lives inside the + * subquery; the outer statement selects what `find` always selects. + * + * ⛔ Never `findWithWindowFunctions`: it is a different door with a different + * contract, and the window here is part of `find`'s statement so that `find`'s + * every rule holds for it. + */ + +import type { Knex } from 'knex'; +import type { DriverOptions, FilterCondition } from '@objectstack/spec/data'; +import type { SqlDriver } from './sql-driver.js'; + +/** + * The AST key `find` reads the window from. The engine sets the same + * `Symbol.for` key on the composed AST it hands the driver, after every + * middleware has run. + */ +export const LATEST_PER_DIRECTIVE: unique symbol = Symbol.for('objectstack.driver.find.latestPer'); + +/** One key of the order that decides which row of a group is the answer. */ +export interface LatestPerDirectiveOrder { + readonly field: string; + readonly order: 'asc' | 'desc'; +} + +/** What the engine hands `find` under {@link LATEST_PER_DIRECTIVE}. */ +export interface LatestPerDirective { + readonly by: readonly string[]; + readonly orderBy: readonly LatestPerDirectiveOrder[]; +} + +/** The derived table's alias and its row-number column: never a row key. */ +const WINDOW_ALIAS = '__os_latest_per'; +const ROW_NUMBER_COLUMN = '__os_latest_per_rn'; + +const isFieldName = (v: unknown): v is string => typeof v === 'string' && v !== ''; + +/** + * The directive on `query`, checked — or `undefined` when none rides there. A + * directive built wrong is our own plumbing, refused rather than half-read. + */ +export function latestPerDirectiveOf(query: unknown): LatestPerDirective | undefined { + if (query === null || typeof query !== 'object') return undefined; + const directive = (query as Record)[LATEST_PER_DIRECTIVE]; + if (directive === undefined) return undefined; + const by = (directive as { by?: unknown } | null)?.by; + const orderBy = (directive as { orderBy?: unknown } | null)?.orderBy; + const wellFormed = Array.isArray(by) && by.length > 0 && by.every(isFieldName) + && Array.isArray(orderBy) && orderBy.length > 0 + && orderBy.every((k) => isFieldName((k as { field?: unknown } | null)?.field) + && ((k as { order?: unknown }).order === 'asc' || (k as { order?: unknown }).order === 'desc')); + if (!wellFormed) { + throw new Error('find(): the engine-internal latest-per directive is malformed; the query was NOT run.'); + } + return directive as LatestPerDirective; +} + +/** What {@link latestPerIdSubquery} reads off the driver. */ +export interface LatestPerHost { + applyFilters: SqlDriver['applyFilters']; + applyTenantScope: SqlDriver['applyTenantScope']; + getBuilder: SqlDriver['getBuilder']; + readonly knex: SqlDriver['knex']; + mapSortField: SqlDriver['mapSortField']; + remoteColumn: SqlDriver['remoteColumn']; +} + +/** + * The ids of each group's first row, as one subquery `find` embeds as + * `id IN (…)`. Tenant-walled with the read's own options and filtered by the + * read's own final `where`; it carries no transaction of its own — it is part + * of the outer statement, which does. + */ +export function latestPerIdSubquery( + this: Pick, + object: string, + where: FilterCondition | undefined, + directive: LatestPerDirective, + options?: DriverOptions, +): Knex.QueryBuilder { + const column = (field: string): string => this.remoteColumn(object, field, this.mapSortField(field)); + const idColumn = this.remoteColumn(object, 'id', 'id'); + const bindings: string[] = []; + const partition = directive.by.map((field) => { bindings.push(column(field)); return '??'; }).join(', '); + const order: string[] = []; + for (const key of directive.orderBy) { + const physical = column(key.field); + bindings.push(physical, physical); + order.push(`CASE WHEN ?? IS NULL THEN 1 ELSE 0 END, ?? ${key.order === 'desc' ? 'DESC' : 'ASC'}`); + } + const last = directive.orderBy[directive.orderBy.length - 1]; + bindings.push(idColumn); + order.push(`?? ${last.order === 'desc' ? 'DESC' : 'ASC'}`); + bindings.push(ROW_NUMBER_COLUMN); + const rowNumber = this.knex.raw( + `ROW_NUMBER() OVER (PARTITION BY ${partition} ORDER BY ${order.join(', ')}) AS ??`, + bindings, + ); + + const windowed = this.getBuilder(object).select(idColumn, rowNumber); + this.applyTenantScope(windowed, object, options); + if (where) this.applyFilters(windowed, where, options); + + return this.knex + .select(idColumn) + .from(windowed.as(WINDOW_ALIAS)) + .where(ROW_NUMBER_COLUMN, 1); +} diff --git a/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-latest-per.test.ts b/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-latest-per.test.ts new file mode 100644 index 00000000000..58562103eb5 --- /dev/null +++ b/packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-latest-per.test.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [latest per group] This driver is on the engine's list of drivers that + * compile the one-row-per-group window (objectql `latest-per.ts`), because it + * inherits `driver-sql`'s `find` and runs it on its own sql.js dialect. Pinned + * here on that dialect: one row per group, a tie to the id, NULL last, the + * tenant wall inside the choice, and no helper column on the rows. The full + * conformance table is `driver-sql`'s `sql-driver-latest-per.test.ts`. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { LATEST_PER_DIRECTIVE } from '@objectstack/driver-sql'; +import { SqliteWasmDriver } from '../src/index.js'; + +const DEALS = [ + { id: 'd1', account: 'a1', close_date: '2026-01-10', organization_id: 'org_a' }, + { id: 'd2', account: 'a1', close_date: '2026-03-10', organization_id: 'org_a' }, + { id: 'd3', account: 'a2', close_date: '2026-04-01', organization_id: 'org_a' }, + { id: 'd4', account: 'a2', close_date: '2026-04-01', organization_id: 'org_a' }, + { id: 'd5', account: 'a3', close_date: '2026-01-01', organization_id: 'org_a' }, + { id: 'd6', account: 'a3', close_date: null, organization_id: 'org_a' }, + { id: 'xb', account: 'a1', close_date: '2026-12-31', organization_id: 'org_b' }, +]; + +describe('[latest per group] driver-sqlite-wasm serves the window', () => { + let driver: SqliteWasmDriver; + + beforeAll(async () => { + driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.initObjects([ + { name: 'deal', fields: { account: { type: 'string' }, close_date: { type: 'date' }, organization_id: { type: 'string' } } }, + ]); + for (const row of DEALS) await driver.create('deal', { ...row }); + }); + + afterAll(async () => { + await driver.disconnect(); + }); + + it('one row per group: the newest, a tie to the larger id, NULL last, inside the tenant wall', async () => { + const rows = await driver.find('deal', { + orderBy: [{ field: 'account', order: 'asc' }], + [LATEST_PER_DIRECTIVE]: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] }, + } as never, { tenantId: 'org_a' }); + expect(rows.map((r) => r.id)).toEqual(['d2', 'd4', 'd5']); + for (const row of rows) expect(Object.keys(row).some((k) => k.startsWith('__os_latest_per'))).toBe(false); + }); + + it('control: without the directive, every row', async () => { + const rows = await driver.find('deal', {} as never, { tenantId: 'org_a' }); + expect(rows).toHaveLength(6); + }); +}); diff --git a/packages/drivers/driver-turso/src/remote-transport-latest-per-refusal.test.ts b/packages/drivers/driver-turso/src/remote-transport-latest-per-refusal.test.ts new file mode 100644 index 00000000000..0bd54591440 --- /dev/null +++ b/packages/drivers/driver-turso/src/remote-transport-latest-per-refusal.test.ts @@ -0,0 +1,53 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [latest per group] The remote face compiles its own reads and no window, so + * a `find` handed the engine's one-row-per-group directive is refused with + * `INVALID_QUERY` / 400 before a statement goes out — never answered as an + * ordinary read (every row instead of one per group). The engine refuses this + * face first (`packages/objectql/src/latest-per.test.ts`); this is the driver's + * own word for a caller that reaches it directly. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { LATEST_PER_DIRECTIVE } from '@objectstack/driver-sql'; +import { TursoDriver } from './turso-driver.js'; + +const DEAL = { name: 'deal', fields: { account: { type: 'text' }, close_date: { type: 'date' } } }; + +async function remoteDriver() { + const statements: string[] = []; + const record = (stmt: any) => { + statements.push(String(stmt?.sql ?? stmt)); + return { rows: [], columns: [], rowsAffected: 0 }; + }; + const client = { + execute: vi.fn(async (stmt: any) => record(stmt)), + batch: vi.fn(async (stmts: any[]) => stmts.map(record)), + close: vi.fn(), + }; + const driver = new TursoDriver({ url: 'libsql://latest-per.turso.io', client: client as never }); + await driver.connect(); + expect(driver.transportMode).toBe('remote'); + await driver.syncSchema(DEAL.name, DEAL); + statements.length = 0; + return { driver, statements }; +} + +describe('[latest per group] driver-turso remote face', () => { + it('refuses the directive with INVALID_QUERY / 400 and sends no statement', async () => { + const { driver, statements } = await remoteDriver(); + const query = { + [LATEST_PER_DIRECTIVE]: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] }, + } as never; + const err: any = await driver.find('deal', query).then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(statements).toEqual([]); + }); + + it('control: the same read without the directive goes out', async () => { + const { driver, statements } = await remoteDriver(); + await driver.find('deal', {} as never); + expect(statements.some((s) => /select/i.test(s))).toBe(true); + }); +}); diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index 828ee38d631..f6397b9db9c 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -36,6 +36,7 @@ import { isIndexDriftOp, parseIndexDdl, planDeclaredRenames, + latestPerDirectiveOf, type DeclaredRenameCarry, type DeclaredRenamePlan, type DriftOp, @@ -2504,6 +2505,20 @@ export class TursoDriver extends SqlDriver { override async find(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { this.assertRemoteTransactionUnsupported(options, 'find'); if (this.isRemote) { + // [latest per group] The remote transport compiles its own reads and no + // window: a read handed the directive is refused before anything is + // read, never answered as an ordinary read. The engine refuses it first; + // this is the driver's own word for a caller that reaches it directly. + if (latestPerDirectiveOf(query) !== undefined) { + const err = new Error( + `find('${object}'): one row per group cannot run on the remote face of this driver, whose transport ` + + 'compiles no window. The query was NOT run and nothing was read. A local or replica database serves it.', + ) as Error & { code?: string; status?: number; httpStatus?: number }; + err.code = StandardErrorCode.enum.INVALID_QUERY; + err.status = 400; + err.httpStatus = 400; + throw err; + } const table = this.remoteTableFor(object, 'find'); const remoteQuery = this.toRemoteReadQuery(object, query, undefined, options); // [#21226] The caller's tenant scope, as the local face scopes `findRows`. diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts index 663bb7c4f48..aa00f6fcdce 100644 --- a/packages/mcp/src/index.ts +++ b/packages/mcp/src/index.ts @@ -38,6 +38,9 @@ export type { McpPrincipalKind, } from './types.js'; export type { McpCallerExecutionContext } from './tool-call-interceptor.js'; +// The capped-list truncation flag the read tools share, and `query_records`' +// one-row-per-group form a bridge receives. +export type { McpLatestPer } from './types.js'; export { registerObjectTools, registerActionTools, diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 17a976e9531..78b37347743 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -126,6 +126,7 @@ import { // [#30892] The file seam and what `read_file` renders from it. import { READ_FILE_MAX_BYTES, ReadFileExtractionBusyError, renderReadFile, type McpFileBridge } from './file-content.js'; import { actionConfirmationElicitorFor, type McpActionCallDoor } from './action-confirmation-elicitation.js'; +import type { McpLatestPer } from './types.js'; export interface McpObjectSummary { name: string; @@ -226,6 +227,14 @@ export interface McpDataBridge { limit?: number; offset?: number; orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + /** + * One row per group (`query_records`' `latestPer`): the bridge hands it + * to the engine's read as the engine's own read option, never as a query + * key, and answers `{ object, records, hasMore }` — at most `limit` + * groups, `hasMore` from a read of one row more, and no `total` (a row + * count is no group count). A bridge that cannot serve it refuses. + */ + latestPer?: McpLatestPer; }, ): Promise; /** @@ -547,6 +556,38 @@ export interface RegisterActionToolsOptions { const DEFAULT_MAX_LIMIT = 50; +/** The most partition fields, and the most order keys, one `latestPer` may name (the engine's own bound). */ +const LATEST_PER_MAX_KEYS = 3; + +/** + * [latest per group] `query_records`' answer under `latestPer`, from the + * bridge's `{ object, records, hasMore }`: the records (at most `limit` + * groups) and `hasMore`, which {@link servedQueryPage} turns into + * `truncated: true` as for any capped page. No `total`: a row count is no + * group count. An answer that is not that shape — a bridge that served the + * read as an ordinary list — is no answer, and is refused. + */ +function latestPerAnswer( + objectName: string, + result: unknown, +): { object: unknown; records: unknown[]; hasMore: boolean } { + const answer = result as { object?: unknown; records?: unknown; hasMore?: unknown; total?: unknown } | null; + if (!answer || !Array.isArray(answer.records) || typeof answer.hasMore !== 'boolean' || answer.total !== undefined) { + const err = new Error( + `query_records on '${objectName}' with latestPer: this host's data bridge did not serve one record per group, ` + + 'so its rows are not the answer and none is returned.', + ) as Error & { code?: string; status?: number }; + err.code = StandardErrorCode.enum.INTERNAL_ERROR; + err.status = 500; + throw err; + } + return { + object: answer.object ?? objectName, + records: answer.records, + hasMore: answer.hasMore, + }; +} + /** A `sys_`-prefixed object is a system table — off-limits to external agents. */ function isSystemObject(name: string): boolean { return /^sys_/i.test(name); @@ -2975,7 +3016,11 @@ export function registerObjectTools( // Names repeat (ruling 6867150851), so the text says to tell // namesakes apart by email. 'To fill a person field, find the colleague\'s id: objectName "sys_user", where {"email":"..."} for exactly ' + - 'one person, or {"name":{"$contains":"..."}}; names repeat, so tell people who share a name apart by email.', + 'one person, or {"name":{"$contains":"..."}}; names repeat, so tell people who share a name apart by email. ' + + // [latest per group] "each X with its latest Y" in one call. + 'For "each X with its latest Y", pass latestPer: one record per group, e.g. each account\'s latest deal: ' + + 'latestPer {"by":["account"],"orderBy":[{"field":"close_date","order":"desc"}]}; ties go by record id. ' + + 'where filters the records first; limit counts groups; truncated: true means more groups exist than came back.', inputSchema: strictToolInput( { surface: 'this query_records call', @@ -3016,29 +3061,51 @@ export function registerObjectTools( .array(z.object({ field: z.string(), order: z.enum(['asc', 'desc']) })) .optional() .describe('Sort order'), + latestPer: z + .object({ + by: z.array(z.string().min(1)).min(1).max(LATEST_PER_MAX_KEYS) + .describe('The fields that form a group, e.g. ["account"] or ["owner_id"]'), + orderBy: z + .array(z.object({ field: z.string().min(1), order: z.enum(['asc', 'desc']) }).strict()) + .min(1) + .max(LATEST_PER_MAX_KEYS) + .describe('The order whose first record is each group\'s answer, e.g. [{"field":"close_date","order":"desc"}]'), + }) + .strict() + .optional() + .describe('One record per group: each group\'s first record in orderBy, ties broken by id. limit counts groups.'), }, ), annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, where, fields, limit, offset, orderBy }) => { + async ({ objectName, where, fields, limit, offset, orderBy, latestPer }) => { const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { // [#35138] A capped page says so: one row past the page is asked // for, and its coming back is the cap (`servedQueryPage`). const page = Math.min(limit ?? maxLimit, maxLimit); - const probed = queryPageProbeFits(page, offset); - const result = servedQueryPage( - await bridge.query(objectName, { - where, - fields, - limit: probed ? page + 1 : page, - offset, - orderBy, - }), - page, - probed, - ); + // [latest per group] One record per group: the door reads its own + // probe group and answers `hasMore`, so the page is served unprobed + // here and `truncated` is the same key, set the same way. + const probed = latestPer === undefined && queryPageProbeFits(page, offset); + const result = latestPer !== undefined + ? servedQueryPage( + latestPerAnswer(objectName, await bridge.query(objectName, { where, fields, limit: page, offset, orderBy, latestPer })), + page, + false, + ) + : servedQueryPage( + await bridge.query(objectName, { + where, + fields, + limit: probed ? page + 1 : page, + offset, + orderBy, + }), + page, + probed, + ); // [ADR-0090 D10 — ruling 2026-09-08, consequence 2] A delegated read // the agent ceiling NARROWED is served with the narrowing stated. The // rows are still served — a partial answer is the most useful true diff --git a/packages/mcp/src/mcp-query-records-latest-per.test.ts b/packages/mcp/src/mcp-query-records-latest-per.test.ts new file mode 100644 index 00000000000..332b79cb0e6 --- /dev/null +++ b/packages/mcp/src/mcp-query-records-latest-per.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [latest per group] `query_records`' `latestPer`: "each X with its latest Y" + * in one call. + * + * The tool half: the argument is bounded at the door (1 to 3 partition fields, + * 1 to 3 order keys, no other member), handed to the bridge as `latestPer` + * with the capped `limit`, and answered `{ object, records, hasMore }` plus the + * shared truncation flag (`truncated: true`) when more groups exist than came + * back — never a `total`. A bridge answer that is not one row per group is no + * answer. Without `latestPer` the tool is unchanged. + * + * The stdio bridge half: the request rides to `engine.find` on the engine's own + * read option, never as a query key; the read takes one row more than `limit` + * and serves `limit`; the partition and order fields meet the bridge's sort + * verdicts; an engine that did not serve the window is no answer. + * + * The whole read over MCP, under real row, field and tenant security, is in + * the dogfood harness (`latest-per-over-mcp.dogfood.test.ts`). + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; + +const OBJECT = 'crm_opportunity'; +const LATEST_PER_KEY = Symbol.for('objectstack.objectql.latestPer'); +const NEWEST = { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] }; + +function makeBridge(answer: unknown) { + const queries: Array<{ object: string; opts: any }> = []; + const bridge: any = { + async listObjects() { return [{ name: OBJECT, label: 'Opportunity' }]; }, + async describeObject(name: string) { return { name }; }, + async query(object: string, opts: any) { queries.push({ object, opts }); return answer; }, + async get(object: string, id: string) { return { object, id }; }, + async create(object: string, data: any) { return { object, data }; }, + async update(object: string, id: string) { return { object, id }; }, + async remove(object: string, id: string) { return { object, id, success: true }; }, + }; + return { bridge, queries }; +} + +async function call(bridge: any, args: Record): Promise<{ isError: boolean; payload: any; text: string }> { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'query_records', arguments: { objectName: OBJECT, ...args } } }; + const req = new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); + const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body }); + const json: any = await res.json(); + const text = String(json.result?.content?.[0]?.text ?? json.error?.message ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: json.result?.isError === true || json.error !== undefined, payload, text }; +} + +describe('query_records latestPer — the tool', () => { + it('hands latestPer and the capped limit to the bridge; one page of groups, no total, no truncated flag', async () => { + const { bridge, queries } = makeBridge({ object: OBJECT, records: [{ id: 'd3' }, { id: 'd6' }], hasMore: false }); + const answer = await call(bridge, { latestPer: NEWEST, where: { stage: 'open' } }); + expect(answer.isError, answer.text).toBe(false); + expect(queries).toHaveLength(1); + expect(queries[0].opts).toMatchObject({ where: { stage: 'open' }, limit: 50, latestPer: NEWEST }); + expect(answer.payload).toEqual({ object: OBJECT, records: [{ id: 'd3' }, { id: 'd6' }], hasMore: false }); + }); + + it('more groups than came back: truncated: true', async () => { + const { bridge } = makeBridge({ object: OBJECT, records: [{ id: 'd3' }], hasMore: true }); + const answer = await call(bridge, { latestPer: NEWEST, limit: 1 }); + expect(answer.payload).toEqual({ object: OBJECT, records: [{ id: 'd3' }], hasMore: true, truncated: true }); + }); + + it('a bridge that answered an ordinary list (a row total) is no answer: a coded server fault, no rows', async () => { + const { bridge } = makeBridge({ object: OBJECT, records: [{ id: 'd1' }, { id: 'd2' }], total: 2 }); + const answer = await call(bridge, { latestPer: NEWEST }); + expect(answer.isError).toBe(true); + expect(answer.payload?.error?.code).toBe('INTERNAL_ERROR'); + expect(answer.text).not.toMatch(/"d1"/); + }); + + for (const [label, latestPer] of [ + ['four partition fields', { ...NEWEST, by: ['a', 'b', 'c', 'd'] }], + ['no order key', { ...NEWEST, orderBy: [] }], + ['an unknown member', { ...NEWEST, partitionBy: ['account'] }], + ['an order that is neither asc nor desc', { ...NEWEST, orderBy: [{ field: 'close_date', order: 'newest' }] }], + ] as const) { + it(`refused at the door before the bridge is asked: ${label}`, async () => { + const { bridge, queries } = makeBridge({ object: OBJECT, records: [], hasMore: false }); + const answer = await call(bridge, { latestPer }); + expect(answer.isError).toBe(true); + expect(queries).toHaveLength(0); + }); + } + + it('control: without latestPer the tool answers the bridge\'s list unchanged, total and all', async () => { + const list = { object: OBJECT, records: [{ id: 'd1' }], total: 7 }; + const { bridge, queries } = makeBridge(list); + const answer = await call(bridge, { limit: 1 }); + expect(answer.payload).toEqual(list); + expect('latestPer' in queries[0].opts).toBe(false); + }); +}); + +describe('query_records latestPer — the stdio bridge', () => { + const PRINCIPAL = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; + const DEF = { name: OBJECT, fields: { account: { type: 'lookup' }, close_date: { type: 'date' }, note: { type: 'text', sortable: false } } }; + + function makeStdio(served: boolean, rows: Array>) { + const engine = { + find: vi.fn(async (_object: string, _query: any, options: any) => { + const request = options?.[LATEST_PER_KEY]; + if (served && request) request.outcome = { kind: 'served' }; + return rows; + }), + }; + const metadataService = { getObject: vi.fn(async (name: string) => (name === OBJECT ? DEF : undefined)) }; + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: metadataService as unknown as IMetadataService, + resolvePrincipal: async () => PRINCIPAL, + }); + return { bridge, engine }; + } + + it('rides the engine\'s read option, reads limit + 1, serves limit, says hasMore; never a query key', async () => { + const { bridge, engine } = makeStdio(true, [{ id: 'd1' }, { id: 'd2' }, { id: 'd3' }]); + const answer: any = await bridge.query(OBJECT, { limit: 2, latestPer: NEWEST as any }); + expect(answer).toEqual({ object: OBJECT, records: [{ id: 'd1' }, { id: 'd2' }], hasMore: true }); + const [, query, options] = engine.find.mock.calls[0]!; + expect(query.limit).toBe(3); + expect('latestPer' in query).toBe(false); + expect(options[LATEST_PER_KEY]).toMatchObject(NEWEST); + expect(options.context).toBe(PRINCIPAL); + }); + + it('an engine that did not serve the window is no answer', async () => { + const { bridge } = makeStdio(false, [{ id: 'd1' }]); + const err = await bridge.query(OBJECT, { limit: 2, latestPer: NEWEST as any }).then(() => null, (e: Error) => e); + expect(err?.message).toMatch(/not served as one row per group/); + }); + + it('a partition field the author declared sortable: false meets the sort verdict, before the engine', async () => { + const { bridge, engine } = makeStdio(true, []); + const err: any = await bridge.query(OBJECT, { limit: 2, latestPer: { by: ['note'], orderBy: NEWEST.orderBy } as any }) + .then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status, field: err?.field }).toEqual({ code: 'INVALID_SORT', status: 400, field: 'note' }); + expect(engine.find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index 985e31f0310..b66daa3c159 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -490,10 +490,12 @@ const BRIDGE_MEMBERS: Record = { * call at all. */ const ENGINE_READ_SITES: Record> = { - // findById (get, and the update / remove existence probes) and query; aggregate. + // findById (get, and the update / remove existence probes) and query; the + // query's one-row-per-group read (`latestPer`), behind the same stored-body, + // hash and sort refusals with its partition and order fields judged; aggregate. // [#35138] `count(object)`: `query`'s page total, a number and never a row, // counted under the `where` the stored-body and hash refusals already judged. - 'stdio-data-bridge.ts': { 'find(object)': 2, 'aggregate(object)': 1, 'count(object)': 1 }, + 'stdio-data-bridge.ts': { 'find(object)': 3, 'aggregate(object)': 1, 'count(object)': 1 }, // The ADR-0101 record resource reader. 'plugin.ts': { 'find(objectName)': 1 }, // [#30891] NOT an engine read: `delete_records` counting its selection diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 847ac8aaef7..6715d710635 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -311,6 +311,13 @@ interface ObjectDef { * spelling the existing stdio reader already accepts, kept identical so the two * readers on this transport cannot disagree about what a row list is. */ +/** + * The engine's one-row-per-group read option (`@objectstack/objectql`, + * `latest-per.ts`), spelled `Symbol.for` because this package does not depend + * on the engine at runtime. A symbol, so no tool argument can carry it. + */ +const STDIO_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); + function unwrapRows(res: unknown): Array> { const rows = res && typeof res === 'object' && 'value' in (res as Record) @@ -1345,17 +1352,26 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge await enforceApiExposure(reads, object, GATED_ACTIONS.query, context); // [#22777] …and each nested-relation condition's target, before the engine reads it. await enforceRelationTargetExposure(reads, object, opts?.where, context); + // [latest per group] The partition and order fields are sort keys to + // every sort verdict below, as the engine judges them. + const latestPerKeys = opts?.latestPer + ? [ + ...opts.latestPer.by.map((field) => ({ field, order: 'asc' as const })), + ...opts.latestPer.orderBy, + ] + : []; + const judgedOrderBy = latestPerKeys.length > 0 ? [...(opts?.orderBy ?? []), ...latestPerKeys] : opts?.orderBy; // [#21207] After the exposure gate, before the engine: a filter or sort // on a stored metadata body is refused rather than evaluated. - const bodyRefusal = storedMetadataBodyRefusal(object, { where: opts?.where, orderBy: opts?.orderBy }); + const bodyRefusal = storedMetadataBodyRefusal(object, { where: opts?.where, orderBy: judgedOrderBy }); if (bodyRefusal) throw bodyRefusal; // [#21207] …and the same for a stored content-hash column. - const hashRefusal = storedMetadataHashRefusal(object, { where: opts?.where, orderBy: opts?.orderBy }); + const hashRefusal = storedMetadataHashRefusal(object, { where: opts?.where, orderBy: judgedOrderBy }); if (hashRefusal) throw hashRefusal; // [#29896] …and a sort on a field its author declared `sortable: false`, // the list door's fourth sort verdict, judged by the served projection. - if (opts?.orderBy && opts.orderBy.length > 0) { - const sortRefusal = unofferedSortRefusal(object, await objectView.getObject(object), opts.orderBy); + if (judgedOrderBy && judgedOrderBy.length > 0) { + const sortRefusal = unofferedSortRefusal(object, await objectView.getObject(object), judgedOrderBy); if (sortRefusal) throw sortRefusal; } // A filter or sort on an `internal: true` field is refused by the engine @@ -1370,6 +1386,31 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge if (typeof opts?.offset === 'number') query.offset = opts.offset; // [#21207] The content-hash columns are served keyed, or not at all. const digest = keyedDigest?.(); + if (opts?.latestPer) { + // [latest per group] One row per group, on the engine's own read + // option: at most `limit` groups, read with one row more so the answer + // says whether more groups exist; no `total`, since a row count is no + // group count. The engine sets the outcome when its driver served the + // window; a read that comes back without it is no answer. + const limit = typeof opts.limit === 'number' ? opts.limit : undefined; + if (limit === undefined) throw new Error(`query_records on '${object}' with latestPer needs a limit.`); + const latestPer: { by: string[]; orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; outcome?: { kind?: unknown } } = { + by: opts.latestPer.by, + orderBy: opts.latestPer.orderBy, + }; + const found = unwrapRows(await engine.find(object, { ...query, limit: limit + 1 }, { + context, + [STDIO_LATEST_PER]: latestPer, + } as Parameters[2])); + if (latestPer.outcome?.kind !== 'served') { + throw new Error(`query_records on '${object}' with latestPer: the read was not served as one row per group.`); + } + const page = found.slice(0, limit); + const latestRecords = await Promise.all( + serveStoredMetadataRows(object, page, { dropType: read.addedType }).map((row) => serveStoredMetadataHashes(object, row, digest)), + ); + return { object, records: latestRecords, hasMore: found.length > limit }; + } const records = await Promise.all( serveStoredMetadataRows(object, unwrapRows(await engine.find(object, query, { context })), { dropType: read.addedType, diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 5a09a38d0a1..079a45f1313 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -286,3 +286,13 @@ export type McpToolInterceptor = ( call: McpToolCallContext, next: () => Promise, ) => Promise; + +/** + * `query_records`' one-row-per-group form (`latestPer`): the fields that form a + * group, and the order whose first record is each group's answer; ties are + * broken by the record `id`. The tool's input schema bounds both lists. + */ +export interface McpLatestPer { + by: string[]; + orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; +} diff --git a/packages/metadata-protocol/src/protocol-data-crud.ts b/packages/metadata-protocol/src/protocol-data-crud.ts index b9351aa7d10..af1feb89cb3 100644 --- a/packages/metadata-protocol/src/protocol-data-crud.ts +++ b/packages/metadata-protocol/src/protocol-data-crud.ts @@ -26,7 +26,7 @@ import { recordNotFoundError } from '@objectstack/core'; import { staleSummaryRefusalOrThrow, withEarnedAnswer } from '@objectstack/types'; import type { SummaryRecomputeRefusal } from '@objectstack/types'; import { omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js'; -import type { DroppedFieldsEvent, EngineQueryOptions, ValidationAdvisoryEvent } from '@objectstack/spec/data'; +import type { BaseEngineOptions, DroppedFieldsEvent, EngineQueryOptions, ValidationAdvisoryEvent } from '@objectstack/spec/data'; import { redactStoredMetadataRow, redactStoredMetadataRows, @@ -63,6 +63,47 @@ import { } from './protocol-list-query-params.js'; import type { ProtocolHost } from './protocol-host.js'; +/** + * The engine's latest-per read option (`@objectstack/objectql`, `latest-per.ts`): + * one row per group. An in-process door hands it to {@link + * ProtocolDataCrudFacet.findData} on the REQUEST object under this key, beside + * `object` / `query` / `context`, and `findData` hands it on to `engine.find` + * as that same option. A `Symbol.for` key — this package does not depend on + * the engine — and a symbol, so no wire request, JSON body or spread author + * input can carry it: every ingress gate below judges the query exactly as it + * judges any other. + */ +const FIND_DATA_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); + +/** The request's partition and order fields as sort nodes, for the sort gates; well-formed entries only — the engine judges the shape. */ +function latestPerSortNodes(request: unknown): Array<{ field: string; order: 'asc' | 'desc' }> { + const by = (request as { by?: unknown } | null)?.by; + const orderBy = (request as { orderBy?: unknown } | null)?.orderBy; + const nodes: Array<{ field: string; order: 'asc' | 'desc' }> = []; + if (Array.isArray(by)) { + for (const field of by) if (typeof field === 'string' && field !== '') nodes.push({ field, order: 'asc' }); + } + if (Array.isArray(orderBy)) { + for (const key of orderBy) { + const field = (key as { field?: unknown } | null)?.field; + const order = (key as { order?: unknown } | null)?.order; + if (typeof field === 'string' && field !== '') nodes.push({ field, order: order === 'desc' ? 'desc' : 'asc' }); + } + } + return nodes; +} + +/** A latest-per read this door cannot serve as asked: `INVALID_QUERY` / 400, nothing read. */ +function latestPerQueryRefusal(object: string, detail: string): Error { + const err: any = new Error(`findData('${object}') with latestPer: ${detail} The query was NOT run and nothing was read.`); + err.code = 'INVALID_QUERY'; + err.status = 400; + err.httpStatus = 400; + err.object = object; + err.param = 'latestPer'; + return err; +} + export class ProtocolDataCrudFacet { /** The body of `ObjectStackProtocolImplementation#findData`; the method's docblock there is its contract. */ static async findData(host: Pick, request: { object: string, query?: any, context?: any }): Promise<{ @@ -75,6 +116,11 @@ export class ProtocolDataCrudFacet { // query parameter is even parsed, so an unknown name can never be // probed for query-shape validity (nor reach the driver as a table). host.assertObjectRegistered(request.object); + // [latest per group] The engine-internal one-row-per-group request, when + // an in-process door carried one (see {@link FIND_DATA_LATEST_PER}). + const latestPer = (request as unknown as Record)[FIND_DATA_LATEST_PER] as + { outcome?: { kind?: unknown } } | undefined; + const latestPerNodes = latestPer !== undefined ? latestPerSortNodes(latestPer) : []; const options: any = { ...request.query }; // The execution context is SERVER-DERIVED and never caller input. // @@ -229,6 +275,10 @@ export class ProtocolDataCrudFacet { if (orderBy.length > 0) options.orderBy = orderBy; else delete options.orderBy; } + // [latest per group] The partition and order fields are sort keys to + // this door too: an unknown, dotted or computed one is refused here in + // the sort axis' own words, as the engine judges them as sort keys. + if (latestPerNodes.length > 0) host.assertSortFieldsExist(request.object, latestPerNodes, 'latestPer'); // Filter: the folded slot value → a usable `FilterCondition` on // `where`, or a rejection. The four spellings of this slot @@ -527,9 +577,12 @@ export class ProtocolDataCrudFacet { // names it below the ingress collector's depth backstop, is refused like // a direct one. `[]` outside the family. const filterFields = collectStoredMetadataFilterFields(request.object, options); - const sortFields = Array.isArray(options.orderBy) - ? (options.orderBy as ReadonlyArray<{ field?: unknown }>).map((e) => e?.field) - : []; + const sortFields = [ + ...(Array.isArray(options.orderBy) + ? (options.orderBy as ReadonlyArray<{ field?: unknown }>).map((e) => e?.field) + : []), + ...latestPerNodes.map((n) => n.field), + ]; const bodyPredicateRefusal = storedMetadataBodyPredicateRefusal(request.object, { filterFields, sortFields }); if (bodyPredicateRefusal) throw bodyPredicateRefusal; // [#21207] The same three shapes on the stored CONTENT-HASH columns @@ -555,7 +608,12 @@ export class ProtocolDataCrudFacet { // Internal fields in a `$search` set are handled on their own axes: the // auto-default never scans one (engine), an explicit `$searchFields` // naming one is refused (the gate above, #4254 posture). - host.assertNoInternalFieldEvaluated(request.object, options); + host.assertNoInternalFieldEvaluated( + request.object, + latestPerNodes.length > 0 + ? { ...options, orderBy: [...(Array.isArray(options.orderBy) ? options.orderBy : []), ...latestPerNodes] } + : options, + ); // Route to engine.aggregate() when the query has GROUP BY / aggregations. // engine.find() does not do in-memory aggregation fallback, so without @@ -570,6 +628,9 @@ export class ProtocolDataCrudFacet { // every shape gate and before the engine, so a refusal leaves the // driver unasked. All three unset returns the caller's own `limit`. const readLimits = resolveQueryReadLimits(); + if (latestPer !== undefined && (hasGroupBy || hasAggregations)) { + throw latestPerQueryRefusal(request.object, 'one row per group is a list read; it does not combine with groupBy or aggregations.'); + } if (hasGroupBy || hasAggregations) { // The grouped branch slices in memory and never reads `offset`, so // the window it is judged on is the groups it returns. @@ -709,6 +770,9 @@ export class ProtocolDataCrudFacet { // is served in keyed form — never the stored value, which beside the // projected body confirms a guess at the withheld material offline — // under the provider's key, or the process-scoped ephemeral one. + if (latestPer !== undefined) { + return ProtocolDataCrudFacet.findLatestPer(host, request.object, findQuery, latestPer, bodyProjection.addedType === true); + } const found = await host.engine.find(request.object, findQuery); if (listPlan.probe) { assertQueryReadRows(listRead, listPlan, found.length, console); @@ -822,6 +886,54 @@ export class ProtocolDataCrudFacet { }; } + /** + * [latest per group] The list read of {@link findData} under a latest-per + * request: one row per group, at most `limit` groups. + * + * - The page is read with ONE row more than it serves (a `limit + 1` + * probe): a read that returns it says more groups exist (`hasMore`), and + * the extra row is not served. + * - `total` is omitted. The count read the list path runs counts ROWS, and + * a row count is no group count; no cheap and correct group count is run. + * - The request comes back from the engine with its outcome set, or the + * read was not served as one row per group: a layer between this door + * and the engine dropped the option, and its rows are no answer. + */ + static async findLatestPer( + host: Pick, + object: string, + findQuery: EngineQueryOptions, + latestPer: { outcome?: { kind?: unknown } }, + dropType: boolean, + ): Promise<{ object: string; records: any[]; hasMore: boolean }> { + const limit = findQuery.limit; + if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 0) { + throw latestPerQueryRefusal(object, 'it needs a limit: the number of groups to return.'); + } + // The request rides on a symbol member of the engine's read options, never a declared key. + const readOptions: BaseEngineOptions = {}; + (readOptions as Record)[FIND_DATA_LATEST_PER] = latestPer; + const found = await host.engine.find(object, { ...findQuery, limit: limit + 1 }, readOptions); + if (latestPer.outcome?.kind !== 'served') { + const err: any = new Error( + `findData('${object}') with latestPer: the read came back without being served as one row per group, ` + + 'so its rows are not the answer and none is returned.', + ); + err.code = 'INTERNAL_ERROR'; + err.status = 500; + err.httpStatus = 500; + throw err; + } + const rows = Array.isArray(found) ? found : []; + const page = rows.slice(0, limit); + const records = await serveStoredMetadataHashColumnRows( + object, + redactStoredMetadataRows(object, page, { dropType }), + host.storedHashDigest(), + ); + return { object, records, hasMore: rows.length > limit }; + } + /** The body of `ObjectStackProtocolImplementation#getData`; the method's docblock there is its contract. */ static async getData(host: Pick, request: { object: string, id: string, expand?: string | string[], select?: string | string[], context?: any }): Promise<{ object: string; diff --git a/packages/metadata-protocol/src/protocol.find-data-latest-per.test.ts b/packages/metadata-protocol/src/protocol.find-data-latest-per.test.ts new file mode 100644 index 00000000000..785426f673f --- /dev/null +++ b/packages/metadata-protocol/src/protocol.find-data-latest-per.test.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [latest per group] `findData` carrying the in-process one-row-per-group + * request (the `Symbol.for('objectstack.objectql.latestPer')` member an + * in-process door sets — never a wire key). + * + * Pinned: the request rides to `engine.find` on the engine's read option, not + * in the query; the read takes one row more than the limit and serves the + * limit, answering `hasMore` from the probe and never a `total` (no COUNT is + * issued — rows are not groups); an engine that did not serve the window is a + * coded server fault, never an ordinary list; a partition or order field the + * object does not declare is refused before the engine is asked; and the + * request does not combine with `groupBy`. + */ + +import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a clocked case: the protocol's diagnostics load it lazily. +import '@objectstack/lint'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +const LATEST_PER = Symbol.for('objectstack.objectql.latestPer'); +const SCHEMA = { + name: 'deal', + nameField: 'name', + fields: { + name: { name: 'name', type: 'text' }, + account: { name: 'account', type: 'text' }, + close_date: { name: 'close_date', type: 'date' }, + }, +}; +const request = () => ({ by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' as const }] }) as { + by: string[]; + orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; + outcome?: { kind: string }; +}; + +function makeProtocol(rows: Array>, served: boolean) { + const find = vi.fn(async (_object: string, _query: any, options: any) => { + const req = options?.[LATEST_PER]; + if (served && req) req.outcome = { kind: 'served' }; + return rows; + }); + const count = vi.fn(async () => 999); + const engine = { + registry: { getObject: (n: string) => (n === 'deal' ? SCHEMA : undefined) }, + find, + count, + aggregate: vi.fn(async () => [] as unknown[]), + }; + return { p: new ObjectStackProtocolImplementation(engine as any), find, count }; +} + +describe('[latest per group] findData with the in-process request', () => { + it('reads limit + 1 on the engine option, serves limit, says hasMore; no total, no COUNT', async () => { + const { p, find, count } = makeProtocol([{ id: 'd1' }, { id: 'd2' }, { id: 'd3' }], true); + const latestPer = request(); + const result: any = await p.findData({ object: 'deal', query: { limit: 2 }, [LATEST_PER]: latestPer } as never); + expect(result.records.map((r: any) => r.id)).toEqual(['d1', 'd2']); + expect(result.hasMore).toBe(true); + expect('total' in result).toBe(false); + expect(count).not.toHaveBeenCalled(); + const [, query, options] = find.mock.calls[0]!; + expect(query.limit).toBe(3); + expect(Object.getOwnPropertySymbols(query)).toEqual([]); + expect('latestPer' in query).toBe(false); + expect(options[LATEST_PER]).toBe(latestPer); + expect(latestPer.outcome).toEqual({ kind: 'served' }); + }); + + it('an engine that did not serve the window is a coded server fault, never an ordinary list', async () => { + const { p } = makeProtocol([{ id: 'd1' }], false); + const err: any = await p.findData({ object: 'deal', query: { limit: 2 }, [LATEST_PER]: request() } as never) + .then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status ?? err?.statusCode }).toEqual({ code: 'INTERNAL_ERROR', status: 500 }); + }); + + it('a partition field the object does not declare is refused before the engine is asked', async () => { + const { p, find } = makeProtocol([], true); + const latestPer = { ...request(), by: ['no_such_field'] }; + const err: any = await p.findData({ object: 'deal', query: { limit: 2 }, [LATEST_PER]: latestPer } as never) + .then(() => null, (e: unknown) => e); + expect(err?.status ?? err?.statusCode).toBe(400); + expect(find).not.toHaveBeenCalled(); + }); + + it('does not combine with groupBy: INVALID_QUERY / 400, nothing read', async () => { + const { p, find } = makeProtocol([], true); + const err: any = await p.findData({ + object: 'deal', + query: { limit: 2, groupBy: ['account'] }, + [LATEST_PER]: request(), + } as never).then(() => null, (e: unknown) => e); + expect({ code: err?.code, status: err?.status ?? err?.statusCode }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(find).not.toHaveBeenCalled(); + }); + + it('control: without the request, an ordinary list with its total', async () => { + const { p, find } = makeProtocol([{ id: 'd1' }], true); + const result: any = await p.findData({ object: 'deal', query: { limit: 2 } } as never); + expect(result.total).toBe(999); + expect(LATEST_PER in (find.mock.calls[0]![2] ?? {})).toBe(false); + }); +}); diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index a877ad7b65a..0122b4b25ed 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -33,6 +33,10 @@ import { SortNodeSchema, lowerFilterCondition, resolveSearchFieldResolution } fr import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data'; import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js'; import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; +import { + assertLatestPerShape, latestPerFieldRefusal, latestPerJudgedSortKeys, latestPerRegistryRefusal, latestPerRequestOf, + withLatestPerDirective, type LatestPerOrder, +} from './latest-per.js'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { collectCredentialFields, collectInternalReadFields } from './secret-fields.js'; @@ -78,6 +82,7 @@ export interface FindHost { formulaFaultSink: ObjectQL['formulaFaultSink']; formulaOptionLabels: ObjectQL['formulaOptionLabels']; getDriver: ObjectQL['getDriver']; + hasHooksFor: ObjectQL['hasHooksFor']; readonly logger: ObjectQL['logger']; lowerRelationConditions: ObjectQL['lowerRelationConditions']; maskSecretFields: ObjectQL['maskSecretFields']; @@ -417,7 +422,7 @@ export class FindFacet { } /** The body of `ObjectQL#find`; the method's docblock there is its contract. */ - static async find(this: Pick, object: string, query?: EngineQueryOptions, options?: EngineReadOptions): Promise { + static async find(this: Pick, object: string, query?: EngineQueryOptions, options?: EngineReadOptions): Promise { object = this.resolveObjectName(object); // Normalize the alias spellings (`filter`→`where`, `top`→`limit`) by the // spec's slot table — the driver AST only understands the canonical keys, @@ -434,6 +439,23 @@ export class FindFacet { query = lowerWhereFilterArray(object, 'find', query, this._registry.getObject(object), this.relatedSchemaOf); this.logger.debug('Find operation starting', { object, query }); const driver = this.getDriver(object); + // [latest per group] The engine-internal request for one row per group + // (`latest-per.ts`). Its shape, the registry facts and its fields are + // judged first, before anything is read: a driver that does not compile + // the window, an object whose rows can be narrowed after the driver call, + // or a field no driver can group or order by is refused here. + const latestPer = latestPerRequestOf(options); + if (latestPer !== undefined) { + assertLatestPerShape(object, latestPer); + const latestPerSchema = this._registry.getObject(object); + const refused = latestPerRegistryRefusal(object, { + driver: driver as { readonly name?: unknown; readonly find?: unknown } | undefined, + schema: latestPerSchema, + hasAfterFindHook: this.hasHooksFor('afterFind', object), + hasObjectMiddleware: this.facade.hasObjectMiddleware(object), + }) ?? latestPerFieldRefusal(object, latestPerSchema, latestPer); + if (refused !== undefined) throw refused; + } // `object` LAST: the resolved name must win. Spread-first used to let a // stray `query.object` overwrite it, splitting the AST's object from the // table actually queried (#4371 option-2 survey) — every middleware and @@ -446,6 +468,12 @@ export class FindFacet { // schemas declare are filled here, before anything downstream reads the AST. const { context: _findContext, ...findQuery } = query ?? {}; const ast: QueryAST = { ...this.fillQueryAstDefaults(findQuery), object }; + // [latest per group] The partition and order fields are sort keys to + // every door from here on: appended to the AST the doors and the + // middleware chain judge, taken back out at the executor boundary below. + const _latestPerOwnOrderBy = ast.orderBy; + const _latestPerJudged: LatestPerOrder[] = latestPer !== undefined ? latestPerJudgedSortKeys(latestPer, ast.orderBy) : []; + if (_latestPerJudged.length > 0) ast.orderBy = [...(ast.orderBy ?? []), ..._latestPerJudged]; // [ADR-0100] A `secret` / `password` column is never a filter or sort key // for a non-system caller — judged on the caller's own `where` / `orderBy` // / `expand`, before the search term is expanded into `where` and before @@ -546,7 +574,13 @@ export class FindFacet { // [ADR-0139 D2] The executor boundary: the AST is final here — after the // doors, the middleware chain and `beforeFind` — so every `ReadableIds` // leaf is composed (or refused) on it, immediately before the driver. - const driverAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context, driverOptions); + const composedAst = await this.composeReadableIdsAtBoundary(object, 'find', hookContext.input.ast as QueryAST, opCtx.context, driverOptions); + // [latest per group] The window directive goes on HERE, on the final + // AST whose `where` carries every composed scope, and the judged sort + // keys come back off it — so the window runs over the caller's own rows. + const driverAst = latestPer !== undefined + ? withLatestPerDirective(composedAst, _latestPerJudged, _latestPerOwnOrderBy, latestPer) + : composedAst; // [relation semi-join] A PLANNED read (`relation-semi-join.ts`): the // final `where` and the driver options are handed to the planner in // place of the driver call, and the read answers the plan's own empty @@ -554,6 +588,8 @@ export class FindFacet { // symbol-keyed option. const plan = (options as Record | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined; if (plan !== undefined) { + // A planned read is never a latest-per read: the planner reads ids. + if (latestPer !== undefined) throw new Error(`find('${object}'): a planned read cannot carry a latest-per request.`); plan.capture(driverAst.where as FilterCondition | undefined, driverOptions); opCtx.result = plan.rows; return opCtx.result; @@ -561,6 +597,10 @@ export class FindFacet { try { let result = await driver.find(object, driverAst, driverOptions); + // [latest per group] The driver answered the window: the request's + // carriers read this back, and a read that comes back without it + // was not served as one row per group. + if (latestPer !== undefined) latestPer.outcome = { kind: 'served' }; // [#21571] The read's default projection is the DECLARED field set: // a column no metadata declares (a field retired in an upgrade, diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 3584dfdd778..870455531f8 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -5913,6 +5913,7 @@ export class ObjectQL implements IObjectQLEngine { formulaFaultSink: (...a) => engine.formulaFaultSink(...a), formulaOptionLabels: (...a) => engine.formulaOptionLabels(...a), getDriver: (...a) => engine.getDriver(...a), + hasHooksFor: (...a) => engine.hasHooksFor(...a), get logger() { return engine.logger; }, lowerRelationConditions: (...a) => engine.lowerRelationConditions(...a), maskSecretFields: (...a) => engine.maskSecretFields(...a), diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index c19c8b41f78..d1ef5378eca 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -243,6 +243,12 @@ const READERS: Record = { disposition: 'exempt', why: 'names the related object only to judge the join beside the federated test; it reads no row', }, + // [latest per group] A federated object refuses the one-row-per-group read + // before anything is read, so no window is compiled against its remote table. + 'latest-per.ts#latestPerRegistryRefusal :: isFederatedObject()': { + disposition: 'exempt', + why: 'a federated object refuses the latest-per read before anything is read; 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. diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 514d9955878..fc7ea266eba 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -269,6 +269,11 @@ export type { DatasourceDef } from './engine.js'; // refuses the filter rather than truncate it, and its words name this number. // Exported so a caller running the two-step route itself can page by it. export { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js'; +// "Each X with its latest Y": the engine-internal read option a door carries +// to `find` for one row per group, and the request it carries. The carriers +// that do not import this package spell the key `Symbol.for`, as it does. +export { LATEST_PER, LATEST_PER_MAX_KEYS } from './latest-per.js'; +export type { LatestPerRequest, LatestPerOrder, LatestPerOutcome } from './latest-per.js'; // [#16159] `SUMMARY_RECOMPUTE_CODE` joins the class it names. The refusal's own // docblock tells a caller to identify it by `code` rather than `instanceof` // (the two-realm split #14936 measured: this package declares BOTH realms in diff --git a/packages/objectql/src/latest-per.test.ts b/packages/objectql/src/latest-per.test.ts new file mode 100644 index 00000000000..352b526b3f5 --- /dev/null +++ b/packages/objectql/src/latest-per.test.ts @@ -0,0 +1,238 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The engine-internal one-row-per-group request (`latest-per.ts`): a `find` + * carrying {@link LATEST_PER} is handed to a SQL driver as ONE statement with + * the window directive on the composed AST — after every middleware, over the + * `where` they composed — and its partition and order fields are sort keys to + * every door before that. Wherever the engine cannot serve it in the driver's + * own statement, it is refused `INVALID_QUERY` / 400 with nothing read. + * + * A recording driver stands in for the SQL family: it answers to the name the + * engine names (or not) and records every call. What `driver-sql` compiles + * the directive to is pinned in that package; the whole read over MCP, under + * real row and field security, in the dogfood harness. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ObjectQL } from './engine.js'; +import { LATEST_PER, LATEST_PER_DIRECTIVE, type LatestPerRequest } from './latest-per.js'; + +const DEAL = 'lp_deal'; + +const DEAL_OBJECT = { + name: DEAL, + label: 'Deal', + fields: { + account: { name: 'account', type: 'text' }, + owner: { name: 'owner', type: 'text' }, + stage: { name: 'stage', type: 'text' }, + close_date: { name: 'close_date', type: 'date' }, + secret_rank: { name: 'secret_rank', type: 'number' }, + score: { name: 'score', type: 'formula', expression: '1', returnType: 'number' }, + tags: { name: 'tags', type: 'select', multiple: true, options: [{ label: 'A', value: 'a' }] }, + }, +}; + +interface SeenCall { verb: string; object: string; ast: any } + +function makeRecordingDriver(name: string, extra: Record = {}) { + const calls: SeenCall[] = []; + const driver: any = { + name, version: '0.0.0', supports: { readableIdsLeaf: true }, ...extra, + 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 [{ id: 'd1', account: 'a1' }]; }, + 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 []; }, + 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 }; +} + +type Thrown = (Error & { code?: string; status?: number; param?: string; field?: string }) | null; +const refusalOf = async (p: Promise): Promise => p.then(() => null, (e: any) => e); + +const newest = (over: Partial = {}): LatestPerRequest => ({ + by: ['account'], + orderBy: [{ field: 'close_date', order: 'desc' }], + ...over, +}); + +async function makeEngine(driverName: string, extra?: Record) { + const rec = makeRecordingDriver(driverName, extra); + const engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + engine.registry.registerObject(DEAL_OBJECT as any, 'test'); + return { engine, rec }; +} + +describe('latest per group — one driver statement, the window over the composed read', () => { + let engine: ObjectQL; + let rec: ReturnType; + + beforeEach(async () => { + ({ engine, rec } = await makeEngine('com.objectstack.driver.sql')); + }); + + it('one driver call: the directive rides the composed AST, after the middleware\'s injected where; the outcome is set', async () => { + // A read middleware injecting a row scope, as row-level security does. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === DEAL) op.ast.where = op.ast.where ? { $and: [op.ast.where, { owner: 'u_me' }] } : { owner: 'u_me' }; + await next(); + }); + const req = newest(); + const rows = await engine.find(DEAL, { where: { stage: 'open' }, limit: 5 }, { [LATEST_PER]: req } as never); + + expect(rows.map((r: any) => r.id)).toEqual(['d1']); + expect(req.outcome).toEqual({ kind: 'served' }); + const finds = rec.calls.filter((c) => c.verb === 'find'); + expect(finds).toHaveLength(1); + const ast = finds[0].ast; + expect(ast[LATEST_PER_DIRECTIVE]).toEqual({ by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] }); + expect(ast.where).toEqual({ $and: [{ stage: 'open' }, { owner: 'u_me' }] }); + expect(ast.limit).toBe(5); + // The judged sort keys are taken back off: the caller sent no orderBy. + expect(ast.orderBy).toBeUndefined(); + }); + + it('the middleware chain sees every partition and order field as a sort key, after the caller\'s own', async () => { + let seen: unknown; + engine.registerMiddleware(async (op: any, next: () => Promise) => { + if (op.object === DEAL) seen = op.ast.orderBy; + await next(); + }); + await engine.find(DEAL, { orderBy: [{ field: 'stage', order: 'asc' }] }, { + [LATEST_PER]: newest({ by: ['account', 'owner'] }), + } as never); + expect(seen).toEqual([ + { field: 'stage', order: 'asc' }, + { field: 'account', order: 'asc' }, + { field: 'owner', order: 'asc' }, + { field: 'close_date', order: 'desc' }, + ]); + // …and the driver gets the caller's own ORDER BY only. + expect(rec.calls.find((c) => c.verb === 'find')?.ast.orderBy).toEqual([{ field: 'stage', order: 'asc' }]); + }); + + it('a caller\'s own sort key on a partition field stays on the statement', async () => { + await engine.find(DEAL, { orderBy: [{ field: 'account', order: 'desc' }] }, { [LATEST_PER]: newest() } as never); + expect(rec.calls.find((c) => c.verb === 'find')?.ast.orderBy).toEqual([{ field: 'account', order: 'desc' }]); + }); + + it('a field gate that refuses a sort key refuses a hidden partition field before the driver is asked', async () => { + // Stands in for the field-level predicate guard: it refuses a hidden + // field wherever it appears as a sort key. + engine.registerMiddleware(async (op: any, next: () => Promise) => { + const sorted = (op.ast.orderBy ?? []).map((s: any) => s.field); + if (op.object === DEAL && sorted.includes('secret_rank')) { + const err: any = new Error('hidden field'); + err.code = 'PERMISSION_DENIED'; + err.status = 403; + throw err; + } + await next(); + }); + const req = newest({ by: ['secret_rank'] }); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: req } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); + expect(rec.calls).toHaveLength(0); + expect(req.outcome).toBeUndefined(); + }); + + it('no request, no directive: an ordinary find is unchanged', async () => { + await engine.find(DEAL, { orderBy: [{ field: 'stage', order: 'asc' }] }); + const ast = rec.calls.find((c) => c.verb === 'find')?.ast; + expect(ast[LATEST_PER_DIRECTIVE]).toBeUndefined(); + expect(ast.orderBy).toEqual([{ field: 'stage', order: 'asc' }]); + }); +}); + +describe('latest per group — refused INVALID_QUERY / 400 with nothing read', () => { + const refusedOn = async (name: string, extra?: Record) => { + const { engine, rec } = await makeEngine(name, extra); + const req = newest(); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: req } as never)); + return { err, calls: rec.calls.length, outcome: req.outcome }; + }; + + for (const [label, name, extra] of [ + ['the in-memory driver', 'com.objectstack.driver.memory', undefined], + ['MongoDB', 'com.objectstack.driver.mongodb', undefined], + ['the Turso driver on its remote face', 'com.objectstack.driver.turso', { transportMode: 'remote' }], + ['the Turso driver with no face it names', 'com.objectstack.driver.turso', undefined], + ] as const) { + it(`on ${label}`, async () => { + const { err, calls, outcome } = await refusedOn(name, extra); + expect({ code: err?.code, status: err?.status, param: err?.param }).toEqual({ code: 'INVALID_QUERY', status: 400, param: 'latestPer' }); + expect(err?.message).toMatch(/nothing was read/); + expect(calls).toBe(0); + expect(outcome).toBeUndefined(); + }); + } + + for (const [label, name, extra] of [ + ['the WASM SQLite driver', 'com.objectstack.driver.sqlite-wasm', undefined], + ['the Turso driver on its local face', 'com.objectstack.driver.turso', { transportMode: 'local' }], + ['the Turso driver on its replica face', 'com.objectstack.driver.turso', { transportMode: 'replica' }], + ] as const) { + it(`control: served on ${label}`, async () => { + const { err, calls, outcome } = await refusedOn(name, extra); + expect(err).toBeNull(); + expect(calls).toBe(1); + expect(outcome).toEqual({ kind: 'served' }); + }); + } + + it('on an object with an afterFind hook', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + engine.registerHook('afterFind', async () => {}, { object: DEAL }); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: newest() } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(err?.message).toMatch(/afterFind/); + expect(rec.calls).toHaveLength(0); + }); + + it('on an object with an object-keyed read middleware', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + engine.registerMiddleware(async (_op: any, next: () => Promise) => { await next(); }, { object: DEAL }); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: newest() } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(err?.message).toMatch(/object-keyed read middleware/); + expect(rec.calls).toHaveLength(0); + }); + + for (const [label, req, field] of [ + ['an unknown partition field', newest({ by: ['nope'] }), 'nope'], + ['a dotted partition field', newest({ by: ['account.name'] }), 'account.name'], + ['a formula order field', newest({ orderBy: [{ field: 'score', order: 'desc' }] }), 'score'], + ['a multi-value partition field', newest({ by: ['tags'] }), 'tags'], + ] as const) { + it(`${label}: INVALID_FIELD / 400`, async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: req } as never)); + expect({ code: err?.code, status: err?.status, field: err?.field }).toEqual({ code: 'INVALID_FIELD', status: 400, field }); + expect(rec.calls).toHaveLength(0); + }); + } + + for (const [label, req] of [ + ['no partition field', { by: [], orderBy: [{ field: 'close_date', order: 'desc' }] }], + ['four partition fields', { by: ['account', 'owner', 'stage', 'id'], orderBy: [{ field: 'close_date', order: 'desc' }] }], + ['no order key', { by: ['account'], orderBy: [] }], + ['an order that is neither asc nor desc', { by: ['account'], orderBy: [{ field: 'close_date', order: 'newest' }] }], + ['a partition field named twice', { by: ['account', 'account'], orderBy: [{ field: 'close_date', order: 'desc' }] }], + ] as const) { + it(`a request built wrong (${label})`, async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + const err = await refusalOf(engine.find(DEAL, {}, { [LATEST_PER]: req } as never)); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(rec.calls).toHaveLength(0); + }); + } +}); diff --git a/packages/objectql/src/latest-per.ts b/packages/objectql/src/latest-per.ts new file mode 100644 index 00000000000..2a37946c4fc --- /dev/null +++ b/packages/objectql/src/latest-per.ts @@ -0,0 +1,347 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * "Each X with its latest Y" — the newest record per group, served as ONE + * statement on the SQL family: `engine.find('crm_opportunity', query, + * { [LATEST_PER]: { by: ['account'], orderBy: [{ field: 'close_date', order: + * 'desc' }] } })` reaches the driver as + * `… WHERE AND id IN (SELECT id FROM (SELECT id, + * ROW_NUMBER() OVER (PARTITION BY account ORDER BY close_date DESC, id DESC) rn + * FROM crm_opportunity WHERE AND ) WHERE + * rn = 1) ORDER BY … LIMIT …`: one row per group, the group's first row in the + * request's order, ties broken by `id`, and the read's own ordering, paging, + * projection and presentation applied to those rows. + * + * ## An engine-internal option, never a wire key + * + * The request rides on {@link LATEST_PER}, a symbol-keyed READ option (the + * `EngineReadOptions` third argument of `find`), exactly as the relation + * group join rides on its own (`relation-group-join.ts`): no wire request, + * JSON body or spread author input can carry a symbol, so the public query + * vocabulary (`QueryAST`) is unchanged. It is a `Symbol.for` key because the + * doors that carry it to the engine (`@objectstack/metadata-protocol`'s + * `findData`, the MCP tools) do not depend on this package at runtime. + * Holding the key grants nothing: the read is still the caller's own `find`, + * through every door, gate and middleware the read always runs. + * + * ## The partition and order fields are sort keys to every door + * + * Grouping by a field and picking a row by a field both disclose that field's + * value through which rows come back, exactly as sorting by it does. So the AST + * the doors and the middleware chain see is ordered by each partition and + * order field the caller's own `orderBy` does not already name + * ({@link latestPerJudgedSortKeys}): every guard that judges a sort key — the + * field-level read gate on predicates first among them, the credential and + * internal-field refusals, the materialisable-sort door — judges these fields + * for the caller, in its own words. Only after the chain has run does the + * engine take those keys back out of the statement it hands the driver + * ({@link withoutJudgedLatestPerKeys}). ⛔ No second copy of any field gate + * lives here. + * + * ## The window runs over the fully scoped read + * + * The driver directive ({@link LATEST_PER_DIRECTIVE}) is attached at the + * executor boundary, to the AST whose `where` already carries every scope the + * pipeline composed (row-level security, sharing, the planned relation + * leaves); the driver applies its tenant wall to the windowed read with the + * read's own options. So the newest row of a group is chosen among the rows + * this caller may read: a group whose newest row is hidden from the caller + * answers its newest VISIBLE row. + * + * ## Refused, never approximated + * + * Prime Directive 5 (ruling record 6888468549): only a driver that compiles + * the window in SQL serves it ({@link driverCompilesLatestPer}). Every other + * driver — the in-memory driver, MongoDB, OData, the remote face of the Turso + * driver — is refused with `INVALID_QUERY` / 400 before anything is read; no + * in-process evaluation and no slower path exist. So is a read of an object + * whose rows can be narrowed after the driver call — an `afterFind` hook or + * an object-keyed read middleware — because the newest row the driver chose + * could then be dropped and the group would lose its answer; and a federated + * object, whose remote table this driver does not own. + */ + +import { StandardErrorCode } from '@objectstack/spec/api'; +import { STRUCTURED_JSON_TYPES, isMultiValueField } from '@objectstack/spec/data'; +import { isFederatedObject } from './federated-object.js'; +import { driverNameOf } from './relation-semi-join.js'; +import { PLATFORM_PROVISIONED_COLUMNS } from './declared-read-columns.js'; + +/** + * The read-option key of a latest-per request: `find(object, query, + * { [LATEST_PER]: request })`. A `Symbol.for` key — its carriers live in + * packages that do not import this one — and a symbol, so no wire request can + * carry it. + */ +export const LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); + +/** + * The AST key the driver reads its window from ({@link DriverLatestPer}); + * `driver-sql`'s `find` reads the same `Symbol.for` key. Set by the engine on + * the composed AST it hands `driver.find`, after every middleware has run — no + * middleware and no caller sees it. + */ +export const LATEST_PER_DIRECTIVE: unique symbol = Symbol.for('objectstack.driver.find.latestPer'); + +/** The most partition fields, and the most order keys, one request may name. */ +export const LATEST_PER_MAX_KEYS = 3; + +/** One key of the order that decides which row of a group is "latest". */ +export interface LatestPerOrder { + readonly field: string; + readonly order: 'asc' | 'desc'; +} + +/** What the engine did with a {@link LatestPerRequest}: set only once the driver answered it. */ +export interface LatestPerOutcome { + readonly kind: 'served'; +} + +/** + * The request: the fields that form a group, the order whose first row is a + * group's answer, and the slot the engine writes its {@link LatestPerOutcome} + * to. A carrier that hands the request on reads the slot back after the read: + * a read that came back without it was not served as one row per group, and + * is never an answer. + */ +export interface LatestPerRequest { + readonly by: readonly string[]; + readonly orderBy: readonly LatestPerOrder[]; + outcome?: LatestPerOutcome; +} + +/** What the driver is handed, on the AST under {@link LATEST_PER_DIRECTIVE}. */ +export interface DriverLatestPer { + readonly by: readonly string[]; + readonly orderBy: readonly LatestPerOrder[]; +} + +/** + * The drivers whose `find` compiles {@link LATEST_PER_DIRECTIVE}, named — no + * capability bit says which drivers compile it, and an unnamed driver is never + * handed one. `driver-sql` covers every dialect it speaks; the WASM SQLite + * driver inherits its `find`. The Turso driver is admitted only on its local + * and replica faces ({@link driverCompilesLatestPer}), which inherit the same + * `find`; its remote face compiles its own reads. + */ +export const LATEST_PER_COMPILING_DRIVERS: ReadonlySet = new Set([ + 'com.objectstack.driver.sql', + 'com.objectstack.driver.sqlite-wasm', +]); + +const TURSO_DRIVER = 'com.objectstack.driver.turso'; +const TURSO_SQL_FACES: ReadonlySet = new Set(['local', 'replica']); + +/** The request on a read's options, when one rides there. */ +export function latestPerRequestOf(options: unknown): LatestPerRequest | undefined { + if (options === null || typeof options !== 'object') return undefined; + const request = (options as Record)[LATEST_PER]; + return request === undefined ? undefined : (request as LatestPerRequest); +} + +/** + * Whether `driver` compiles the window: a named driver of + * {@link LATEST_PER_COMPILING_DRIVERS}, or the Turso driver on a face that + * runs `driver-sql`'s own `find` (`transportMode` `local` or `replica`, read + * as written — anything else is the remote face or unknown, and refused). + */ +export function driverCompilesLatestPer(driver: { readonly name?: unknown; readonly find?: unknown } | undefined): boolean { + if (typeof driver?.find !== 'function') return false; + const name = driver.name; + if (typeof name !== 'string') return false; + if (LATEST_PER_COMPILING_DRIVERS.has(name)) return true; + if (name !== TURSO_DRIVER) return false; + const mode = (driver as { readonly transportMode?: unknown }).transportMode; + return typeof mode === 'string' && TURSO_SQL_FACES.has(mode); +} + +type CodedError = Error & { + code?: string; status?: number; httpStatus?: number; + object?: string; param?: string; field?: string; +}; + +/** The refusal's shared shape: 400, the object and the parameter named, nothing read. The code is stamped by the caller. */ +function refusalOf(object: string, detail: string): CodedError { + const err = new Error( + `find('${object}') with latestPer: ${detail} The query was NOT run and nothing was read.`, + ) as CodedError; + err.status = 400; + // …and `httpStatus`, the same number under ADR-0112 D5's spelling — what a + // consumer holding the THROWN error reads; `status` stays for the HTTP doors. + err.httpStatus = 400; + err.object = object; + err.param = 'latestPer'; + return err; +} + +/** A refusal of the request, `INVALID_QUERY` / 400, nothing read. */ +function refusal(object: string, detail: string): CodedError { + const err = refusalOf(object, detail); + err.code = StandardErrorCode.enum.INVALID_QUERY; + return err; +} + +/** A partition or order field refused, `INVALID_FIELD` / 400 naming the field, nothing read. */ +function fieldRefusal(object: string, detail: string, field: string): CodedError { + const err = refusalOf(object, detail); + err.code = StandardErrorCode.enum.INVALID_FIELD; + err.field = field; + return err; +} + +const isFieldName = (v: unknown): v is string => typeof v === 'string' && v !== ''; + +/** + * Judge the request's SHAPE: one to {@link LATEST_PER_MAX_KEYS} distinct + * partition fields, one to {@link LATEST_PER_MAX_KEYS} distinct order keys each + * `asc` or `desc`. Throws the refusal on a request built wrong. + */ +export function assertLatestPerShape(object: string, request: LatestPerRequest): void { + const by = (request as { by?: unknown }).by; + if (!Array.isArray(by) || by.length === 0 || by.length > LATEST_PER_MAX_KEYS || !by.every(isFieldName)) { + throw refusal(object, `'by' must name 1 to ${LATEST_PER_MAX_KEYS} fields that form a group.`); + } + if (new Set(by).size !== by.length) throw refusal(object, `'by' names a field twice.`); + const orderBy = (request as { orderBy?: unknown }).orderBy; + if (!Array.isArray(orderBy) || orderBy.length === 0 || orderBy.length > LATEST_PER_MAX_KEYS) { + throw refusal(object, `'orderBy' must name 1 to ${LATEST_PER_MAX_KEYS} keys that decide which record of a group is the latest.`); + } + const seen = new Set(); + for (const key of orderBy as unknown[]) { + const field = (key as { field?: unknown } | null)?.field; + const order = (key as { order?: unknown } | null)?.order; + if (!isFieldName(field) || (order !== 'asc' && order !== 'desc')) { + throw refusal(object, `each 'orderBy' key is { field, order } with order 'asc' or 'desc'.`); + } + if (seen.has(field)) throw refusal(object, `'orderBy' names '${field}' twice.`); + seen.add(field); + } +} + +/** + * The field verdict: every partition and order field is a stored, single-valued + * scalar column of `object` — a declared field or a platform column (`id`, + * `created_at`, `updated_at`). Unknown, dotted, computed (`formula`), + * structured-JSON and multi-value fields are refused `INVALID_FIELD` / 400: no + * driver shares a meaning for a computed value or a document as a group key or + * an order. `undefined` when every field passes. + */ +export function latestPerFieldRefusal(object: string, schema: unknown, request: LatestPerRequest): Error | undefined { + const fields = (schema as { fields?: unknown } | undefined)?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) { + return refusal(object, `the object's fields are not registered, so its partition and order fields cannot be judged.`); + } + const provisioned = new Set(PLATFORM_PROVISIONED_COLUMNS); + const named = [ + ...request.by.map((field) => ({ field, role: 'partition' })), + ...request.orderBy.map((key) => ({ field: key.field, role: 'order' })), + ]; + for (const { field, role } of named) { + if (field.includes('.')) { + return fieldRefusal(object, `the ${role} field '${field}' is a dotted path; name a field of '${object}' itself.`, field); + } + if (provisioned.has(field)) continue; + if (!Object.prototype.hasOwnProperty.call(fields, field)) { + return fieldRefusal(object, `the ${role} field '${field}' is not a field of '${object}'.`, field); + } + const def = (fields as Record)[field]; + const type = typeof def?.type === 'string' ? def.type : undefined; + if (type === 'formula') { + return fieldRefusal(object, `the ${role} field '${field}' is a formula, computed on read, so no column holds it; ` + + `store the value in a field of its own and name that field.`, field); + } + if (type !== undefined && (STRUCTURED_JSON_TYPES.has(type) || isMultiValueField({ type, multiple: def?.multiple === true }))) { + return fieldRefusal(object, `the ${role} field '${field}' holds a list or a JSON document, which is no group key or ` + + `order the drivers share; name a field that stores one scalar value.`, field); + } + } + return undefined; +} + +/** What {@link latestPerRegistryRefusal} reads off the engine. */ +export interface LatestPerRegistryFacts { + readonly driver: { readonly name?: unknown; readonly find?: unknown } | undefined; + readonly schema: unknown; + /** An `afterFind` hook is registered for the object. */ + readonly hasAfterFindHook: boolean; + /** An object-keyed read middleware is registered for the object. */ + readonly hasObjectMiddleware: boolean; +} + +/** + * The registry half of the refusal: the error the request is refused with on + * this read, or `undefined` when the registry admits it. Nothing is read. + */ +export function latestPerRegistryRefusal(object: string, facts: LatestPerRegistryFacts): Error | undefined { + if (!driverCompilesLatestPer(facts.driver)) { + return refusal(object, `this read's driver '${driverNameOf(facts.driver as { readonly name?: unknown } | undefined)}' ` + + 'does not compile one row per group in its own statement, and the platform does not compute it in memory. ' + + 'The SQL drivers serve it; on this driver, read the groups first, then each group\'s latest record.'); + } + if (isFederatedObject(facts.schema)) { + return refusal(object, `'${object}' is a federated object, whose remote table this driver does not window.`); + } + if (facts.hasAfterFindHook) { + return refusal(object, `'${object}' has an afterFind hook, which may drop rows after the driver chose each group's ` + + 'latest record, so a group could lose its answer.'); + } + if (facts.hasObjectMiddleware) { + return refusal(object, `'${object}' has an object-keyed read middleware, which may drop rows after the driver chose ` + + 'each group\'s latest record, so a group could lose its answer.'); + } + return undefined; +} + +/** The field a sort entry names: a plain string, or a `{ field }` node. */ +function sortKeyField(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 sort keys the read is judged as ordered by: each partition field (`asc`) + * and each order key the caller's own `orderBy` does not already name. The + * engine adds them to the AST the doors and the middleware chain see, so every + * guard that judges a sort key judges them. + */ +export function latestPerJudgedSortKeys(request: LatestPerRequest, ownOrderBy: unknown): LatestPerOrder[] { + const named = new Set((Array.isArray(ownOrderBy) ? ownOrderBy : []).map(sortKeyField)); + const judged: LatestPerOrder[] = []; + const add = (key: LatestPerOrder): void => { + if (named.has(key.field)) return; + named.add(key.field); + judged.push({ field: key.field, order: key.order }); + }; + for (const field of request.by) add({ field, order: 'asc' }); + for (const key of request.orderBy) add(key); + return judged; +} + +/** + * The statement the driver is handed: the chain's final AST without the sort + * keys {@link latestPerJudgedSortKeys} added for it, and with the window + * directive. An AST whose own `orderBy` was absent stays absent when nothing + * else is left in it. + */ +export function withLatestPerDirective( + ast: T, + judged: readonly LatestPerOrder[], + ownOrderBy: unknown, + request: LatestPerRequest, +): T { + const drop = new Set(judged.map((key) => key.field)); + let orderBy = ast.orderBy; + if (drop.size > 0 && Array.isArray(orderBy)) { + const kept = (orderBy as unknown[]).filter((entry) => { + const field = sortKeyField(entry); + return field === undefined || !drop.has(field); + }); + orderBy = kept.length === 0 && !Array.isArray(ownOrderBy) ? undefined : kept; + } + const directive: DriverLatestPer = { + by: [...request.by], + orderBy: request.orderBy.map((key) => ({ field: key.field, order: key.order })), + }; + return { ...ast, orderBy, [LATEST_PER_DIRECTIVE]: directive }; +} diff --git a/packages/qa/dogfood/test/latest-per-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/latest-per-over-mcp.dogfood.test.ts new file mode 100644 index 00000000000..2db48bce332 --- /dev/null +++ b/packages/qa/dogfood/test/latest-per-over-mcp.dogfood.test.ts @@ -0,0 +1,298 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// "Each X with its latest Y" in one MCP call: `query_records` with +// `latestPer` on the CRM example, as a member's agent asks it, over the live +// `/mcp` transport — real SecurityPlugin, real MCP plugin, the SQL driver, +// a real organization wall (`multiTenant: 'posture-only'`, the `isolated` +// posture). +// +// The member of organization A holds one app set: read on the CRM objects, a +// row-level policy that hides closed-lost deals, and `probability` withheld. +// +// ⭐ one row per group: each account's latest deal, each owner's latest deal, +// each deal's latest activity; a tie on the date goes to the record id; +// ⭐ THE ROW-SECURITY PIN: an account whose newest deal the member may not +// read answers its newest deal the member CAN read — never the hidden +// one, and never nothing (the hidden row is the newest at rest); +// ⭐ a partition or order field the member may not read is refused, and a +// withheld field stays withheld on the served rows; +// ⭐ the organization wall: a member of B, whose deals share A's stages and +// are newer, never wins A's groups, and A's never reach B; +// ⭐ more groups than the cap: `maxLimit` rows and `truncated: true`; under +// it, no flag; +// ⭐ control: the same query without `latestPer` answers every row. +// +// Drivers that cannot compile the window (the in-memory driver, the remote +// face of the Turso driver) refuse before anything is read: pinned against +// the engine in `packages/objectql/src/latest-per.test.ts`, and the Turso +// remote face's own word in `packages/drivers/driver-turso`. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import crmStack from '@objectstack/example-crm'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { assertArmed, armedWhen } from './armed.js'; + +const OPP = 'crm_opportunity'; +const ACCOUNT = 'crm_account'; +const ACTIVITY = 'crm_activity'; +const SYS = { context: { isSystem: true } } as const; +type Row = Record; +const rowsOf = (r: any): Row[] => + (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); + +const DOMAIN = 'latestper.verify.test'; +const OWNER_A = `owner-a@${DOMAIN}`; +const OWNER_B = `owner-b@${DOMAIN}`; +const MEMBER_A = `member-a@${DOMAIN}`; +const MEMBER_B = `member-b@${DOMAIN}`; +/** More activity groups than the tool's cap (`maxQueryLimit`, 50 by default). */ +const CAP = 50; +const MANY = CAP + 5; + +/** The member's app set: read on the CRM objects, closed-lost deals hidden, `probability` withheld. */ +const memberSet: PermissionSet = PermissionSetSchema.parse({ + name: 'latestper_member', + label: 'Latest per group over MCP — a CRM member', + objects: { + [OPP]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [ACCOUNT]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + [ACTIVITY]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, + fields: { [`${OPP}.probability`]: { readable: false, editable: false } }, + rowLevelSecurity: [ + { name: 'latestper_hide_lost', object: OPP, operation: 'select', using: "record.stage != 'closed_lost'" }, + ], +}); + +describe('query_records latestPer over MCP on the CRM example — one row per group under row, field and tenant security', () => { + let stack: VerifyStack; + let ql: any; + const tok: Record = {}; + const org: Record = {}; + const uid: Record = {}; + const acct: Record = {}; + const opp: Record = {}; + const act: Record = {}; + + const idOf = (b: any): string => String(b?.id ?? b?.record?.id ?? ''); + const userId = async (email: string): Promise => + String((await ql.findOne('sys_user', { where: { email }, context: SYS.context }))?.id ?? ''); + + /** One MCP `tools/call` over the live transport, as a bearer; its first content block parsed. */ + const tool = async (bearer: string, name: string, args: Record) => { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${bearer}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), + }); + expect(res.status).toBe(200); + const body: any = await res.json(); + const text = String(body.result?.content?.[0]?.text ?? body.error?.message ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: body.result?.isError === true || body.error !== undefined, payload, text }; + }; + const query = async (bearer: string, args: Record) => { + const answer = await tool(bearer, 'query_records', args); + expect(answer.isError, answer.text).toBe(false); + return answer.payload; + }; + const ids = (payload: any): string[] => rowsOf(payload).map((r) => String(r.id)); + + /** A new organization, created and made active by its owner. */ + const organization = async (ownerEmail: string, name: string, slug: string): Promise => { + const owner = await stack.signUp(ownerEmail); + const created = await stack.apiAs(owner, 'POST', '/auth/organization/create', { name, slug }); + expect(created.status, `org create ${slug}: ${await created.clone().text()}`).toBe(200); + const id = String(((await created.json()) as { id: string }).id); + const active = await stack.apiAs(owner, 'POST', '/auth/organization/set-active', { organizationId: id }); + expect(active.status, `set-active ${slug}: ${await active.clone().text()}`).toBe(200); + return id; + }; + /** A plain member of `orgId`, active in it. */ + const memberOf = async (email: string, orgId: string): Promise => { + const bearer = await stack.signUp(email); + await ql.insert('sys_member', { user_id: await userId(email), organization_id: orgId, role: 'member' }, SYS); + const active = await stack.apiAs(bearer, 'POST', '/auth/organization/set-active', { organizationId: orgId }); + expect(active.status, `member set-active: ${await active.clone().text()}`).toBe(200); + return bearer; + }; + const deal = async (key: string, o: string, account: string, owner: string, stage: string, close: string) => { + opp[key] = idOf(await ql.insert(OPP, { + name: `LP ${key}`, account, owner_id: owner, stage, close_date: close, amount: 100, probability: 40, organization_id: o, + }, SYS)); + }; + + beforeAll(async () => { + stack = await bootStack(crmStack as never, { + multiTenant: 'posture-only', + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, memberSet], + fallbackPermissionSet: memberSet.name, + }), + extraPlugins: [new MCPServerPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + + org.a = await organization(OWNER_A, 'LP Org A', 'latestper-a'); + org.b = await organization(OWNER_B, 'LP Org B', 'latestper-b'); + tok.a = await memberOf(MEMBER_A, org.a); + tok.b = await memberOf(MEMBER_B, org.b); + uid.a = await userId(MEMBER_A); + uid.ownerA = await userId(OWNER_A); + uid.b = await userId(MEMBER_B); + + for (const [key, o] of [['a1', org.a], ['a2', org.a], ['a3', org.a], ['b1', org.b]] as const) { + acct[key] = idOf(await ql.insert(ACCOUNT, { name: `LP account ${key}`, organization_id: o }, SYS)); + } + // Account a1: the newest deal (x1, closed lost) is hidden from the member; + // its newest READABLE deal is x2. Account a2: two deals tie on the date. + // Account a3: one deal. Organization B: one account whose deals share A's + // stages and are newer than every deal of A. + await deal('x1', org.a, acct.a1, uid.a, 'closed_lost', '2031-06-30'); + await deal('x2', org.a, acct.a1, uid.ownerA, 'proposal', '2031-05-01'); + await deal('x3', org.a, acct.a1, uid.a, 'qualification', '2031-01-15'); + await deal('y1', org.a, acct.a2, uid.ownerA, 'prospecting', '2031-03-03'); + await deal('y2', org.a, acct.a2, uid.ownerA, 'proposal', '2031-03-03'); + await deal('z1', org.a, acct.a3, uid.a, 'prospecting', '2030-12-01'); + await deal('b1', org.b, acct.b1, uid.b, 'proposal', '2032-01-01'); + await deal('b2', org.b, acct.b1, uid.b, 'prospecting', '2032-02-02'); + + // Activities on x2 and y1 (each deal's latest activity), and MANY one-row + // groups (one subject each) for the cap. + const activity = async (key: string, opportunity: string | undefined, subject: string, due: string) => { + act[key] = idOf(await ql.insert(ACTIVITY, { + subject, type: 'call', status: 'planned', ...(opportunity ? { opportunity } : {}), due_date: due, organization_id: org.a, + }, SYS)); + }; + await activity('t1', opp.x2, 'LP follow-up', '2031-04-01T09:00:00.000Z'); + await activity('t2', opp.x2, 'LP follow-up', '2031-04-20T09:00:00.000Z'); + await activity('t3', opp.y1, 'LP follow-up', '2031-02-01T09:00:00.000Z'); + for (let i = 0; i < MANY; i++) { + await activity(`m${i}`, undefined, `LP many ${String(i).padStart(2, '0')}`, '2031-01-01T09:00:00.000Z'); + } + + await assertArmed([ + armedWhen({ + control: 'a real wall: two organizations, each member active in its own', + disarmedBy: 'a single organization would pass every tenant pin over one tenant', + observe: async () => { + const tenancy = await stack.kernel.getServiceAsync<{ posture: string; isolationActive: boolean }>('tenancy'); + return { posture: tenancy.posture, active: tenancy.isolationActive, distinct: org.a !== org.b && !!org.a && !!org.b }; + }, + armed: (o) => o.posture === 'isolated' && o.active && o.distinct, + describe: (o) => `posture ${o.posture}, active ${o.active}, distinct orgs ${o.distinct}`, + }), + armedWhen({ + control: 'at rest, the hidden closed-lost deal IS account a1\'s newest', + disarmedBy: 'a hidden row that is not the newest would pass the row-security pin without testing it', + observe: async () => { + const rows = rowsOf(await ql.find(OPP, { where: { account: acct.a1 }, orderBy: [{ field: 'close_date', order: 'desc' }], context: SYS.context })); + return { newest: String(rows[0]?.id), stage: String(rows[0]?.stage) }; + }, + armed: (o) => o.newest === opp.x1 && o.stage === 'closed_lost', + describe: (o) => `newest ${o.newest} (${o.stage})`, + }), + armedWhen({ + control: 'the member\'s row policy really hides the closed-lost deal from an ordinary query', + disarmedBy: 'a policy that never bound would let the hidden row be "newest visible" by accident', + observe: async () => ({ ids: ids(await query(tok.a, { objectName: OPP, where: { account: acct.a1 } })) }), + armed: (o) => !o.ids.includes(opp.x1) && o.ids.includes(opp.x2), + describe: (o) => `member reads ${o.ids.length} deals of a1`, + }), + ]); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('⭐ each account\'s latest deal: one row per group, the tie to the record id, the hidden newest replaced by the newest VISIBLE', async () => { + const payload = await query(tok.a, { + objectName: OPP, + latestPer: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] }, + fields: ['id', 'account', 'stage', 'close_date'], + }); + const byAccount = Object.fromEntries(rowsOf(payload).map((r) => [String(r.account), String(r.id)])); + const tie = [opp.y1, opp.y2].sort().reverse()[0]; + expect(byAccount).toEqual({ [acct.a1]: opp.x2, [acct.a2]: tie, [acct.a3]: opp.z1 }); + // ⭐ never the hidden row, and never nothing for its group. + expect(ids(payload)).not.toContain(opp.x1); + expect(payload.truncated).toBeUndefined(); + expect(payload.total).toBeUndefined(); + expect(payload.hasMore).toBe(false); + }); + + it('⭐ each owner\'s latest deal', async () => { + const payload = await query(tok.a, { + objectName: OPP, + latestPer: { by: ['owner_id'], orderBy: [{ field: 'close_date', order: 'desc' }] }, + }); + const byOwner = Object.fromEntries(rowsOf(payload).map((r) => [String(r.owner_id), String(r.id)])); + // The member's own newest deal (x1) is hidden: x3 answers for them. + expect(byOwner).toEqual({ [uid.a]: opp.x3, [uid.ownerA]: opp.x2 }); + }); + + it('⭐ each deal\'s latest activity', async () => { + const payload = await query(tok.a, { + objectName: ACTIVITY, + where: { subject: 'LP follow-up' }, + latestPer: { by: ['opportunity'], orderBy: [{ field: 'due_date', order: 'desc' }] }, + }); + const byDeal = Object.fromEntries(rowsOf(payload).map((r) => [String(r.opportunity), String(r.id)])); + expect(byDeal).toEqual({ [opp.x2]: act.t2, [opp.y1]: act.t3 }); + }); + + it('⭐ a partition or order field the member may not read is refused; the withheld field stays withheld on the rows', async () => { + for (const latestPer of [ + { by: ['probability'], orderBy: [{ field: 'close_date', order: 'desc' }] }, + { by: ['account'], orderBy: [{ field: 'probability', order: 'desc' }] }, + ]) { + const answer = await tool(tok.a, 'query_records', { objectName: OPP, latestPer }); + expect(answer.isError, `${JSON.stringify(latestPer)}: ${answer.text}`).toBe(true); + expect(answer.payload?.error?.code ?? answer.payload?.code, answer.text).toBe('PERMISSION_DENIED'); + expect(answer.text).not.toContain(opp.x2); + } + const served = await query(tok.a, { objectName: OPP, latestPer: { by: ['account'], orderBy: [{ field: 'close_date', order: 'desc' }] } }); + for (const row of rowsOf(served)) expect(row.probability).toBeUndefined(); + }); + + it('⭐ the organization wall: B\'s newer deals never win A\'s groups, and A\'s never reach B', async () => { + const latestPer = { by: ['stage'], orderBy: [{ field: 'close_date', order: 'desc' }] }; + const a = await query(tok.a, { objectName: OPP, latestPer }); + expect(ids(a)).not.toEqual(expect.arrayContaining([opp.b1])); + expect(ids(a)).not.toContain(opp.b2); + const byStageA = Object.fromEntries(rowsOf(a).map((r) => [String(r.stage), String(r.id)])); + expect(byStageA).toEqual({ proposal: opp.x2, qualification: opp.x3, prospecting: opp.y1 }); + + const b = await query(tok.b, { objectName: OPP, latestPer }); + expect(ids(b).sort()).toEqual([opp.b1, opp.b2].sort()); + }); + + it('⭐ more groups than the cap: the cap\'s rows and truncated: true; one group fewer than the page, no flag', async () => { + const latestPer = { by: ['subject'], orderBy: [{ field: 'due_date', order: 'desc' }] }; + const capped = await query(tok.a, { objectName: ACTIVITY, where: { subject: { $startsWith: 'LP many' } }, latestPer }); + expect(rowsOf(capped)).toHaveLength(CAP); + expect(capped.truncated).toBe(true); + expect(capped.hasMore).toBe(true); + expect(capped.total).toBeUndefined(); + // The groups, not the rows, are what is counted: every served subject is distinct. + expect(new Set(rowsOf(capped).map((r) => r.subject)).size).toBe(CAP); + + const whole = await query(tok.a, { objectName: ACTIVITY, where: { subject: 'LP follow-up' }, latestPer, limit: 2 }); + expect(rowsOf(whole)).toHaveLength(1); + expect(whole.truncated).toBeUndefined(); + }); + + it('control: without latestPer the same query answers every row the member reads', async () => { + const payload = await query(tok.a, { objectName: OPP, where: { account: acct.a1 } }); + expect(ids(payload).sort()).toEqual([opp.x2, opp.x3].sort()); + }); +}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index d9aad0e2798..5f85b284a42 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -114,6 +114,8 @@ import { servedRecordTitle, standaloneActionOwnerKey, SummaryRecomputeError, + LATEST_PER, + type LatestPerRequest, type PackageScopedRefusal, type PackageScopedRegistry, } from '@objectstack/objectql'; @@ -863,8 +865,35 @@ export async function callData(deps: ActionExecutionDeps, const { object, ...rest } = params; return rest; })(); + // [latest per group] The engine's one-row-per-group request, when an + // in-process door (the MCP tools) set it on `params` under the + // engine's own symbol key — never a wire key. Handed to `findData` on + // its request under the same key, and read back: a read that comes back + // without the engine's outcome on it was not served as one row per + // group, and its rows are no answer. + const latestPer = (params as Record | undefined)?.[LATEST_PER] as LatestPerRequest | undefined; if (protocol && typeof protocol.findData === 'function') { - return await protocol.findData({ object: params.object, query, context: executionContext }); + if (latestPer === undefined) { + return await protocol.findData({ object: params.object, query, context: executionContext }); + } + const answer = await protocol.findData({ object: params.object, query, context: executionContext, [LATEST_PER]: latestPer }); + if (latestPer.outcome?.kind !== 'served') { + throw { + statusCode: 500, + message: `The one-row-per-group read of '${params.object}' came back without being served as one row ` + + 'per group, so its rows are not the answer and none is returned.', + }; + } + return answer; + } + if (latestPer !== undefined) { + // The fallback below serves canonical QueryAST keys only; one row + // per group is the engine's window, reached through `findData`. + throw { + statusCode: 501, + message: `Data query fallback cannot serve one row per group of '${params.object}': the protocol service ` + + '(metadata-protocol plugin) is not registered, and only its findData carries that read to the engine.', + }; } if (ql) { // [#4386] This fallback used to pass only `{ context }` — the diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index fba506411a7..c85895e7864 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -48,6 +48,7 @@ import { resolveOpenAuthoringInjection } from './mcp-authoring.js'; // [#28715] The engine's own reading of "this field declares options" (its // `label()` map is built from it), never a second spelling here. import { declaresOptions } from '@objectstack/formula'; +import { LATEST_PER, type LatestPerRequest } from '@objectstack/objectql'; import { RUNTIME_OWNED_FIELD_TYPES, SEARCH_COMPANION_FIELD, isVirtualSearchField } from '@objectstack/spec/data'; // [#15705] The resume door's one refusal table, shared with // `POST /automation/:name/runs/:runId/resume` so the two doors answer one @@ -1187,7 +1188,12 @@ export function buildMcpBridge( if (typeof o?.limit === 'number') query.limit = o.limit; if (typeof o?.offset === 'number') query.offset = o.offset; if (o?.orderBy) query.orderBy = o.orderBy; - return await callData('query', { object, query }, driver, envId, ec); + if (!o?.latestPer) return await callData('query', { object, query }, driver, envId, ec); + // [latest per group] One row per group rides to the engine on the + // engine's own symbol key (never a wire key), through `findData`, + // which judges the query as it judges every other. + const latestPer: LatestPerRequest = { by: o.latestPer.by, orderBy: o.latestPer.orderBy }; + return await callData('query', { object, query, [LATEST_PER]: latestPer }, driver, envId, ec); }, /** * [ADR-0090 D10 — maintainer ruling 2026-09-08, #16549] The diff --git a/scripts/check-tenant-chokepoint.mjs b/scripts/check-tenant-chokepoint.mjs index 119a5d27e46..f11270294ed 100644 --- a/scripts/check-tenant-chokepoint.mjs +++ b/scripts/check-tenant-chokepoint.mjs @@ -267,6 +267,7 @@ const DECLARED_WATCH_HINTS = [ 'packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts', 'packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts', 'packages/drivers/driver-sql/src/sql-driver-introspection.ts', + 'packages/drivers/driver-sql/src/sql-driver-latest-per.ts', 'packages/drivers/driver-sql/src/sql-driver-lifecycle.ts', 'packages/drivers/driver-sql/src/sql-driver-managed-drift.ts', 'packages/drivers/driver-sql/src/sql-driver-oracle-dialect.ts',