Skip to content

Commit 1caee8c

Browse files
feat(mcp, objectql, driver-sql): query_records latestPer, each X with its latest Y in one call (#35199)
Part of #35145 (PR 1 of 2: `latestPer` on `query_records`; the card's second half stays open for PR 2) 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 ## 维护者速读 - 改了什么:MCP 的 `query_records` 新增 `latestPer` 参数,一次调用就能回答“每个客户的最新一笔商机”这类“每组取最新一条”的问题,每组恰好返回一行。 - 为什么改:以前 AI 代理要么拉全量再自己分组(慢、会被 50 行上限截断),要么逐组发请求;现在由数据库用窗口函数一次算完。 - 风险与回滚:不传 `latestPer` 的调用完全不变;新参数只在 SQL 驱动上执行,其它驱动直接拒绝、不读任何数据。回滚即撤销本 PR,无数据迁移。 - 先看:`packages/objectql/src/latest-per.ts`(哪些驱动、哪些对象、哪些字段允许)、`packages/drivers/driver-sql/src/sql-driver-latest-per.ts`(窗口子查询,注意租户条件与 where 在窗口内部生效)、`packages/objectql/src/engine-find.ts`(请求在安全条件合成之后才交给驱动)。 - 两分钟验证:`pnpm --filter @objectstack/driver-sql exec vitest run --maxWorkers=2 src/sql-driver-latest-per.test.ts`,预期 SQLite 8 条全绿(每个客户只回最新一笔,平局按 id,空日期排最后)。 - 需要你做的:无,席位落地。 ## What changes `query_records` takes `latestPer: { by, orderBy }` and answers 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` or `desc`. A tie goes to the record id in the direction of the last key; an empty order value ranks last. - **Tool** (`packages/mcp`): the argument is bounded in the tool's input schema (strict object, 1 to 3 of each). `limit` counts groups and is capped like any list. The answer is `{ object, records, hasMore }` and never a `total`; when more groups exist than came back it carries `truncated: true`, set by `query_records`' shared `servedQueryPage` (#35185) from the door's `hasMore` (the door reads one group past the page). A plain `query_records` call is unchanged here. `McpLatestPer` is a new exported type. A bridge answer that is not one page of groups is a coded server fault, never passed on as a list. The stdio bridge carries the request the same way. - **Door** (`packages/runtime`: `domains/mcp.ts`, `action-execution.ts`; `packages/metadata-protocol`: `findData`): the request rides an in-process symbol member, never a wire or query key. `findData` checks the partition and order fields exist and meet the same stored-field rules as `orderBy`, refuses `latestPer` with `groupBy` or aggregations, reads `limit + 1`, and confirms the engine served the window before answering. - **Engine** (`packages/objectql`: new `latest-per.ts`, `engine-find.ts`): the request is checked before anything is read. Its partition and order fields join the read's sort keys while the read is judged, so every field it reaches meets the same checks as `orderBy` (a field the caller may not read is refused). The directive is handed to the driver only at the executor boundary, on the fully composed read, and the judged keys are taken back off. Served by the SQL driver and `driver-sqlite-wasm`, and by the Turso driver on a local or embedded-replica database. Refused with `INVALID_QUERY` / 400, nothing read: every other driver (in-memory, Turso's remote face, MongoDB), a federated object, an object with an `afterFind` hook or object-scoped read middleware. A computed, JSON or multi-value field, or a dotted path, is refused as a partition or order field (`INVALID_FIELD`). - **Driver** (`packages/drivers/driver-sql`: new `sql-driver-latest-per.ts`, `sql-driver-crud.ts`): `find` adds one predicate, `id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY … ORDER BY …, id) FROM t WHERE tenant AND where) WHERE rn = 1)`. The window is chosen among the rows the read's own scope and `where` admit, so the organization wall and every composed condition hold inside the choice. The read's own ORDER BY, projection, limit and offset apply to the groups; no helper column reaches the rows. The Turso driver's remote face refuses the directive itself too. - `@objectstack/spec` is unchanged. Docs: `content/docs/ai/connect-mcp.mdx` gains a `latestPer` section. ## Tests - `packages/drivers/driver-sql/src/sql-driver-latest-per.test.ts`, on the live dialect matrix: one row per group, ties to id, NULL last, ascending, a `where` that hides a group's newest row (the newest admitted row answers), the tenant wall, two partition fields, the read's own ORDER BY / limit / offset / projection, no helper column, a control without the directive, a malformed directive refused. - `packages/objectql/src/latest-per.test.ts`: the directive lands on the composed read after middleware; middleware sees the judged keys; the field gate refuses with no driver call; the driver allowlist and every refusal (memory, MongoDB, Turso remote and faceless, `afterFind`, object middleware, field kinds, shape); controls served on sqlite-wasm and Turso local and replica. - `packages/metadata-protocol/src/protocol.find-data-latest-per.test.ts`: `limit + 1` on the engine option, no `total` and no COUNT, an unserved window is `INTERNAL_ERROR` / 500, an undeclared field refused before the engine, no combining with `groupBy`. - `packages/mcp/src/mcp-query-records-latest-per.test.ts`: the tool's bounds, forwarding, the cap, `truncated`, the no-answer case; the stdio bridge's option and probe. - `packages/drivers/driver-sqlite-wasm/src/sqlite-wasm-latest-per.test.ts` and `packages/drivers/driver-turso/src/remote-transport-latest-per-refusal.test.ts`: the wasm dialect serves the window; the Turso remote face refuses with no statement sent. - `packages/qa/dogfood/test/latest-per-over-mcp.dogfood.test.ts`: the CRM example over the live `/mcp` transport with the security plugin and a real two-organization wall. A member's agent asks for each account's, each owner's and each deal's latest row. A row policy hides the newest deal of one account: the answer is that account's newest row the member can read, never the hidden one and never nothing. Also: a partition or order field the member may not read is refused and a withheld field stays withheld; the other organization's newer rows never win; 55 groups answer 50 rows with `truncated: true`; a control without `latestPer`. Armed controls check the wall is real, the hidden row is the newest at rest, and the row policy binds. ## Acceptance notes - The in-memory driver and Turso's remote face are pinned refusing in the engine suite (and the Turso remote face in its own suite), not in the dogfood run: the dogfood boot runs on the SQL driver. - Every object a new read shape reaches is judged by the MCP read guard; `latestPer` reaches only the object named in `objectName`. - MySQL: the driver-sql table runs on the MySQL cell of the live dialect matrix in CI's live-dialect job (push and schedule, not pull requests); locally MySQL was not provisioned (NOT MEASURED here). SQLite and Postgres 16 ran locally. - The dispatch asked for `Refs #35145`; this body uses `Part of #35145`, which is the non-closing spelling the dev standard names. Neither closes the card. ## Verification All readings below are from head `303482dda2b` unless a block says otherwise. <details><summary>Targeted suites on the final head (os-verify-lock VERDICT command-exit 0)</summary> - `@objectstack/mcp` full suite: Test Files 73 passed (73), Tests 1292 passed (1292) - objectql `latest-per.test.ts` + `federated-injected-column-readers.test.ts`: Tests 28 passed (28) - driver-sql `sql-driver-latest-per.test.ts`: Tests 16 passed, 1 skipped (SQLite and a local Postgres 16 cell at Asia/Shanghai; the MySQL cell had no server here) - driver-turso remote refusal: 2 passed; driver-sqlite-wasm: 2 passed; metadata-protocol `protocol.find-data-latest-per.test.ts`: 5 passed - dogfood `latest-per-over-mcp.dogfood.test.ts`: Tests 7 passed (7) </details> <details><summary>Full suites of the touched packages (head 837e5b6, before the two merges; TZ=America/New_York, Postgres at Asia/Shanghai)</summary> - driver-sql: Test Files 271 passed, 4 skipped; Tests 5567 passed, 131 skipped - metadata-protocol: Test Files 359 passed, 4 skipped; Tests 23187 passed - objectql: 13822 passed, 1 failed (the federated reader ledger, which this branch then declared; re-run green above) - driver-turso: Tests 2565 passed, 36 skipped; driver-sqlite-wasm: Tests 768 passed; runtime: Tests 11546 passed, 4 skipped - mcp: 1 failed (the stdio read-site ledger, then declared; full suite green above) </details> <details><summary>Dogfood battery on the final head</summary> `pnpm --filter @objectstack/dogfood test` under os-verify-lock: VERDICT command-exit 0 · Test Files 481 passed, 3 skipped (484) · Tests 4132 passed, 18 skipped (4150). </details> <details><summary>Ablation of the driver directive (head a40fc2c; the driver code is unchanged since)</summary> `node scripts/ablation-replace.mjs` turned `if (latestPer !== undefined) {` in `sql-driver-crud.ts` into `if (latestPer !== undefined && false) {` (anchor 1 to 0, blob ddd18cc to 453444f). `sql-driver-latest-per.test.ts` went red: 5 failed, 3 passed (one row per group, ascending, the hidden newest, two partition fields, paging and projection). The three that held do not depend on the predicate: the tenant wall, the control and the malformed directive. Restore: blob back to ddd18cc, `git diff HEAD` empty. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` on head `303482dda2b`: 124 families. All run locally, every exit 0. `check:type-check-debt` was re-run under the lock and printed OK. `check:pm-dispatch-gates` exited 0 at head `d8341c37620`; none of its inputs changed after that. `--ran` reconciliation: 124 derived, 124 run, 0 unrun. `node scripts/check-platform-checklist.mjs --changed-from origin/main`: OK, 0 anchors lost. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 756aba2 commit 1caee8c

27 files changed

Lines changed: 1971 additions & 30 deletions

‎.changeset/35145-mcp-latest-per.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/mcp': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/driver-sql': patch
5+
'@objectstack/driver-turso': patch
6+
'@objectstack/metadata-protocol': patch
7+
'@objectstack/runtime': patch
8+
---
9+
10+
feat(mcp): "each X with its latest Y" in one `query_records` call — `latestPer`
11+
12+
Clause-②: yes (widening): a new read form on the published MCP tool surface. Judged from the card content; the build confirms it
13+
Metadata-protocol: none
14+
15+
`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' }] } }`.
16+
17+
- 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.
18+
- 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.
19+
- `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`.
20+
- 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.
21+
- 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.
22+
23+
Without `latestPer`, `query_records` and every read are unchanged.

‎content/docs/ai/connect-mcp.mdx‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,39 @@ service is installed:
280280
| `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 |
281281
| `query_dataset` | Compute a governed metric by the names `list_datasets` gives; the answer carries its provenance (the dataset and measures used) |
282282

283+
### Each X with its latest Y: `latestPer`
284+
285+
"Each account with its latest deal" is one `query_records` call. `latestPer`
286+
names the groups and the order that picks each group's row:
287+
288+
```json
289+
{
290+
"objectName": "crm_opportunity",
291+
"where": { "stage": { "$ne": "closed_won" } },
292+
"latestPer": { "by": ["account"], "orderBy": [{ "field": "close_date", "order": "desc" }] }
293+
}
294+
```
295+
296+
- `by` takes 1 to 3 fields; `orderBy` takes 1 to 3 keys, each `asc` or `desc`.
297+
The answer is one row per group: the group's first row in that order. A tie
298+
goes to the record id, in the direction of the last key; an empty order value
299+
ranks last.
300+
- The row is chosen among the rows the caller may read and the `where` admits:
301+
a group whose newest row is hidden from the caller answers its newest row the
302+
caller can read. Your own `orderBy`, `fields` and `offset` apply to the
303+
answered rows.
304+
- `limit` counts groups (capped at 50, like any list). The answer is
305+
`{ object, records, hasMore }` with no `total`; when more groups exist than
306+
came back it also carries `truncated: true`.
307+
- A partition or order field the caller may not read is refused, as it is in
308+
`orderBy`. A computed, JSON or multi-value field, or a dotted path, is refused
309+
as a partition or order field.
310+
- The SQL drivers serve it (Postgres, MySQL, SQLite, and Turso on a local or
311+
embedded-replica database). Elsewhere (the in-memory driver, Turso's remote
312+
connection, MongoDB) the call is refused with `INVALID_QUERY` before anything
313+
is read, as it is for an object with an `afterFind` hook or object-scoped read
314+
middleware.
315+
283316
### Governed metrics and the `initialize` instructions
284317

285318
`list_datasets` and `query_dataset` are registered with the `data:read` scope,

‎packages/drivers/driver-sql/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ export {
4646
UnsupportedDialectEmissionError,
4747
renderDialectEmissionRefusal,
4848
} from './dialect-emission-refusal.js';
49+
// [latest per group] The window directive `find` compiles, so a subclass that
50+
// answers `find` on another transport (Turso's remote face) can tell it rode in.
51+
export { LATEST_PER_DIRECTIVE, latestPerDirectiveOf } from './sql-driver-latest-per.js';
52+
export type { LatestPerDirective, LatestPerDirectiveOrder } from './sql-driver-latest-per.js';
4953
// [ADR-0131 D9] The autonumber counter's refusal of an organization-less row on
5054
// a tenant table — exported for the same reason: a caller recognises it by `code`.
5155
export {

‎packages/drivers/driver-sql/src/sql-driver-crud.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
import type { SqlDriver } from './sql-driver.js';
4242
import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js';
4343
import { StandardErrorCode } from '@objectstack/spec/api';
44+
import { latestPerDirectiveOf, latestPerIdSubquery } from './sql-driver-latest-per.js';
4445

4546
/**
4647
* [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its
@@ -154,7 +155,7 @@ export class CrudFacet {
154155
* cited that as agreement, which it was not; objectstack#4419.) The
155156
* obligation the contract states is on `find`, and this keeps it there.
156157
*/
157-
static async findRows(this: Pick<CrudHost, 'applyFilters' | 'applyTenantScope' | 'backendStatementFault' | 'formatOutput' | 'getBuilder' | 'isMssql' | 'isOracle' | 'mapSortField' | 'orderKeysFor' | 'primeMssqlGuidColumns' | 'primeMssqlPagingKey' | 'primeOracleRawUuidColumns' | 'remoteColumn' | 'unresolvableFilterColumnRefusal'>, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise<any[]> {
158+
static async findRows(this: Pick<CrudHost, 'applyFilters' | 'applyTenantScope' | 'backendStatementFault' | 'formatOutput' | 'getBuilder' | 'isMssql' | 'isOracle' | 'knex' | 'mapSortField' | 'orderKeysFor' | 'primeMssqlGuidColumns' | 'primeMssqlPagingKey' | 'primeOracleRawUuidColumns' | 'remoteColumn' | 'unresolvableFilterColumnRefusal'>, object: string, query: DriverQuery, options?: DriverOptions, singleRowLookup = false): Promise<any[]> {
158159
// [#31390] On Oracle a federated object's RAW(16) uuid columns are read from
159160
// the remote catalog before a comparand or a written value is bound.
160161
if (this.isOracle) await this.primeOracleRawUuidColumns(object);
@@ -169,6 +170,10 @@ export class CrudFacet {
169170
// whether the statement HAS a sort to drop, instead of asking whether the
170171
// caller supplied one — since #4363 those are different questions.
171172
const orderKeys = this.orderKeysFor(object, query, { singleRowLookup });
173+
// [latest per group] One row per group, when the engine handed the window
174+
// directive (`sql-driver-latest-per.ts`): one more predicate on the same
175+
// statement, so every clause below holds for it unchanged.
176+
const latestPer = latestPerDirectiveOf(query);
172177

173178
// Build everything EXCEPT the SELECT list, so the unknown-column retry
174179
// below can rebuild without re-deriving where/order/pagination.
@@ -181,6 +186,12 @@ export class CrudFacet {
181186
if (query.where) {
182187
this.applyFilters(b, query.where, options);
183188
}
189+
if (latestPer !== undefined) {
190+
b.whereIn(
191+
this.remoteColumn(object, 'id', 'id'),
192+
latestPerIdSubquery.call(this, object, query.where, latestPer, options),
193+
);
194+
}
184195

185196
// ORDER BY
186197
if (withOrderBy) {
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [latest per group] `find()` compiles the window directive the engine hands
5+
* it (objectql `latest-per.ts`) into its own statement: one more predicate,
6+
* `id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY …
7+
* ORDER BY …, id) rn FROM t WHERE <tenant wall> AND <where>) w WHERE rn = 1)`.
8+
*
9+
* Pinned here: one row per group, the order's first row, ties broken by id in
10+
* the last key's direction, a NULL order value ranked last; the window chosen
11+
* among the rows the read's `where` admits (a group whose newest row the
12+
* `where` hides answers its newest admitted row) and inside the tenant wall
13+
* (another tenant's newer row never wins a group); the read's own ORDER BY,
14+
* limit, offset and projection applied to the groups; no helper column on the
15+
* rows; and a malformed directive refused before anything compiles.
16+
*
17+
* Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`,
18+
* `OS_TEST_MYSQL_URL`); SQLite always runs.
19+
*/
20+
21+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
22+
import type { DriverQuery } from '@objectstack/spec/contracts';
23+
import { SqlDriver } from './sql-driver.js';
24+
import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js';
25+
import { LATEST_PER_DIRECTIVE, type LatestPerDirective } from './sql-driver-latest-per.js';
26+
27+
const TABLE = 'os_latest_per_deal';
28+
29+
/**
30+
* Deals by account and owner. Account `a1`: d3 is newest; `a2`: d5 and d6 tie
31+
* on the date (d6 wins on id, descending); `a3`: d8 has no date and ranks last
32+
* whatever the direction; `ab` is another tenant's account, and `a1` carries
33+
* one more deal, newer than all, in another tenant (xb).
34+
*/
35+
const DEALS = [
36+
{ id: 'd1', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-01-10', amount: 10, organization_id: 'org_a' },
37+
{ id: 'd2', account: 'a1', owner: 'u2', stage: 'lost', close_date: '2026-02-10', amount: 20, organization_id: 'org_a' },
38+
{ id: 'd3', account: 'a1', owner: 'u1', stage: 'hidden', close_date: '2026-03-10', amount: 30, organization_id: 'org_a' },
39+
{ id: 'd4', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-01-05', amount: 40, organization_id: 'org_a' },
40+
{ id: 'd5', account: 'a2', owner: 'u1', stage: 'won', close_date: '2026-04-01', amount: 50, organization_id: 'org_a' },
41+
{ id: 'd6', account: 'a2', owner: 'u2', stage: 'won', close_date: '2026-04-01', amount: 60, organization_id: 'org_a' },
42+
{ id: 'd7', account: 'a3', owner: 'u1', stage: 'won', close_date: '2026-01-01', amount: 70, organization_id: 'org_a' },
43+
{ id: 'd8', account: 'a3', owner: 'u1', stage: 'won', close_date: null, amount: 80, organization_id: 'org_a' },
44+
{ id: 'xb', account: 'a1', owner: 'u1', stage: 'won', close_date: '2026-12-31', amount: 90, organization_id: 'org_b' },
45+
{ id: 'yb', account: 'ab', owner: 'u9', stage: 'won', close_date: '2026-06-01', amount: 99, organization_id: 'org_b' },
46+
];
47+
48+
const latestBy = (by: string[], orderBy: LatestPerDirective['orderBy']): LatestPerDirective => ({ by, orderBy });
49+
const NEWEST_PER_ACCOUNT = latestBy(['account'], [{ field: 'close_date', order: 'desc' }]);
50+
51+
const query = (directive: unknown, over: Partial<DriverQuery> = {}): DriverQuery => ({
52+
orderBy: [{ field: 'account', order: 'asc' }],
53+
...over,
54+
[LATEST_PER_DIRECTIVE]: directive,
55+
} as unknown as DriverQuery);
56+
57+
const ids = (rows: Array<Record<string, unknown>>) => rows.map((r) => String(r.id));
58+
59+
function declareCell(cell: DialectCell): void {
60+
describe(`[latest per group] driver-sql — find answers one row per group (${cell.label})`, () => {
61+
let driver: SqlDriver;
62+
const OLD_POSTURE = process.env.OS_TENANCY_POSTURE;
63+
64+
beforeAll(async () => {
65+
process.env.OS_TENANCY_POSTURE = 'isolated';
66+
driver = new SqlDriver(cell.config());
67+
await driver.execute(`drop table if exists ${TABLE}`).catch(() => {});
68+
await driver.initObjects([
69+
{
70+
name: TABLE,
71+
fields: {
72+
account: { type: 'text' }, owner: { type: 'text' }, stage: { type: 'text' },
73+
close_date: { type: 'date' }, amount: { type: 'number' }, organization_id: { type: 'text' },
74+
},
75+
},
76+
] as never);
77+
for (const row of DEALS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true });
78+
});
79+
80+
afterAll(async () => {
81+
await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {});
82+
await driver?.disconnect?.();
83+
if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE;
84+
else process.env.OS_TENANCY_POSTURE = OLD_POSTURE;
85+
});
86+
87+
it('one row per group: the newest; a tie goes to the larger id; a NULL date ranks last', async () => {
88+
const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
89+
expect(ids(rows)).toEqual(['d3', 'd6', 'd7']);
90+
});
91+
92+
it('ascending: the earliest per group, a tie to the smaller id, NULL still last', async () => {
93+
const rows = await driver.find(TABLE, query(latestBy(['account'], [{ field: 'close_date', order: 'asc' }])), { tenantId: 'org_a' });
94+
expect(ids(rows)).toEqual(['d1', 'd4', 'd7']);
95+
});
96+
97+
it('a group whose newest row the where hides answers its newest ADMITTED row, never nothing', async () => {
98+
const rows = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, { where: { stage: { $ne: 'hidden' } } }), { tenantId: 'org_a' });
99+
expect(ids(rows)).toEqual(['d2', 'd6', 'd7']);
100+
});
101+
102+
it('inside the tenant wall: another tenant\'s newer row never wins, its groups never appear', async () => {
103+
const a = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
104+
expect(ids(a)).not.toContain('xb');
105+
expect(ids(a)).not.toContain('yb');
106+
const b = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_b' });
107+
expect(ids(b)).toEqual(['xb', 'yb']);
108+
});
109+
110+
it('several partition fields: one row per (account, owner)', async () => {
111+
const rows = await driver.find(TABLE, query(latestBy(['account', 'owner'], [{ field: 'close_date', order: 'desc' }]), {
112+
orderBy: [{ field: 'id', order: 'asc' }],
113+
}), { tenantId: 'org_a' });
114+
expect(ids(rows)).toEqual(['d2', 'd3', 'd5', 'd6', 'd7']);
115+
});
116+
117+
it('the read\'s own ORDER BY, limit, offset and projection apply to the groups; no helper column', async () => {
118+
const page = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT, {
119+
orderBy: [{ field: 'amount', order: 'desc' }],
120+
limit: 2,
121+
offset: 1,
122+
fields: ['id', 'amount'],
123+
}), { tenantId: 'org_a' });
124+
// Groups by amount desc: d7 (70), d6 (60), d3 (30) → offset 1, limit 2.
125+
expect(ids(page)).toEqual(['d6', 'd3']);
126+
for (const row of page) expect(Object.keys(row).sort()).toEqual(['amount', 'id']);
127+
const full = await driver.find(TABLE, query(NEWEST_PER_ACCOUNT), { tenantId: 'org_a' });
128+
for (const row of full) expect(Object.keys(row).some((k) => k.startsWith('__os_latest_per'))).toBe(false);
129+
});
130+
131+
it('control: the same read without the directive answers every row', async () => {
132+
const rows = await driver.find(TABLE, { orderBy: [{ field: 'id', order: 'asc' }] } as DriverQuery, { tenantId: 'org_a' });
133+
expect(ids(rows)).toEqual(['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8']);
134+
});
135+
136+
it('a malformed directive is refused before anything compiles', async () => {
137+
const err = await driver.find(TABLE, query({ by: [], orderBy: [] }), { tenantId: 'org_a' })
138+
.then(() => null, (e: Error) => e);
139+
expect(err?.message).toMatch(/latest-per directive is malformed/);
140+
});
141+
});
142+
}
143+
144+
for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'find latest per group', declareCell);

0 commit comments

Comments
 (0)