Skip to content

feat(mcp, objectql, driver-sql): query_records latestPer, each X with its latest Y in one call - #35199

Merged
objectstack-fleet[bot] merged 12 commits into
mainfrom
claude/issue-35145-mcp-latest-per-and-related-read
Nov 18, 2026
Merged

objectstack-fleet[bot] merged 12 commits into
mainfrom
claude/issue-35145-mcp-latest-per-and-related-read

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

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 (feat(mcp): query_records says truncated: true on a capped page, and the stdio door counts its total #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.

Targeted suites on the final head (os-verify-lock VERDICT command-exit 0)
  • @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)
Full suites of the touched packages (head 837e5b6, before the two merges; TZ=America/New_York, Postgres at Asia/Shanghai)
  • 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)
Dogfood battery on the final head

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).

Ablation of the driver directive (head a40fc2c; the driver code is unchanged since)

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.

Derived gates

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.


Generated by Claude Code

… engine and tool

Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL
Co-authored-by: Claude <noreply@anthropic.com>
Each account's, owner's and deal's latest row under the member's row policy,
field withholding and the organization wall; the cap and truncated flag.

Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL
Co-authored-by: Claude <noreply@anthropic.com>
… Turso remote face; changeset

Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL
Co-authored-by: Claude <noreply@anthropic.com>
…truncation flag stays local to the latestPer answer

Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL
Co-authored-by: Claude <noreply@anthropic.com>
…he stdio door counts its total

Claude-Session: https://claude.ai/code/session_01JQwxbYRqkDAGuse5Wqbohi
Co-authored-by: Claude <noreply@anthropic.com>
…; declare the new read site and module to their ledgers

Claude-Session: https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL
Co-authored-by: Claude <noreply@anthropic.com>
…claude/issue-35145-mcp-latest-per-and-related-read

# Conflicts:
#	packages/mcp/src/mcp-http-tools.ts
#	packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts
…p-latest-per-and-related-read

# Conflicts:
#	packages/mcp/src/mcp-http-tools.ts
#	packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts
@github-actions github-actions Bot added size/xl documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 6 package(s): @objectstack/driver-sql, @objectstack/driver-turso, @objectstack/mcp, @objectstack/metadata-protocol, @objectstack/objectql, @objectstack/runtime, touching 107 documentable anchor(s). ⚠️ 3 changed file(s) yielded no anchor (packages/drivers/driver-sql/src/index.ts, packages/mcp/src/index.ts, packages/objectql/src/index.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

52 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json ba6556c617bc201f1d4b635c609b28b589583c36.

⛔ 11 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 3 changed file(s) yielded no anchor (packages/drivers/driver-sql/src/index.ts, packages/mcp/src/index.ts, packages/objectql/src/index.ts) — pages documenting those are invisible to this run
  • 1 cross-cutting symbol(s) contributed no route anchor: findData (4 routes)
  • 1 anchor(s) matched too much of the corpus to be a work list: owner_id (literal, 43 pages)
  • 9 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 59 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json ba6556c617bc201f1d4b635c609b28b589583c36 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from aef3a0d6acac5ac50c523b0307a8fe9181c1dcbb — the merge of head 303482dda2b7d2aebe857f06b5ef9b4b709daad4 into base ba6556c617bc201f1d4b635c609b28b589583c36, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin aef3a0d6acac5ac50c523b0307a8fe9181c1dcbb && git checkout aef3a0d6acac5ac50c523b0307a8fe9181c1dcbb
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin ba6556c617bc201f1d4b635c609b28b589583c36 303482dda2b7d2aebe857f06b5ef9b4b709daad4 && git checkout -B drift-repro ba6556c617bc201f1d4b635c609b28b589583c36 && git merge --no-ff 303482dda2b7d2aebe857f06b5ef9b4b709daad4

node scripts/docs-audit/affected-docs.mjs --json ba6556c617bc201f1d4b635c609b28b589583c36

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs ba6556c617bc201f1d4b635c609b28b589583c36 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbaX2qDxUq9sF93EqqL

Contract-review-claim: session_01JQwxbaX2qDxUq9sF93EqqL · head 303482dda2 · 2026-11-18T13:11Z (TIER_DEFAULT, owed by the Clause-②: yes (widening) declaration: query_records gains a latestPer input)

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbaX2qDxUq9sF93EqqL

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 303482dda2b7d2aebe857f06b5ef9b4b709daad4
Local-runs: none

Inputs read: card #35145 (body, triage 6972038283, claim 6973844822, amendment 6974061928, the two regrades, os-dev-report 6979530359), PR #35199 (body, 27-file list, net diff against main at this head), and the 52 check-runs on this head. At review time 17 had concluded success, 15 were skipped and 20 were still in progress: Test Core 1-10, Build Core, Build Docs, Live E2E UI, the five Lint families, the two scoped lints, and Type Check workspace, consumer and debt. None had failed. Those conclusions are the gate verdicts. This record does not stand in for them, and the seat's ACCEPT waits on them.

① Derived judgments

Public surface, each change judged:

  • query_records input gains latestPer (packages/mcp/src/mcp-http-tools.ts). It is a strict object with by (1 to 3 non-empty strings) and orderBy (1 to 3 strict { field, order: asc|desc }). This is an additive accept-set: every call that was valid before is still valid and answered the same way, because the latestPer === undefined arm is the old code unchanged. Right. The bounds match the engine's LATEST_PER_MAX_KEYS, and the engine checks the shape again (assertLatestPerShape).
  • query_records answer under latestPer is { object, records, hasMore }, never a total, plus truncated: true set by the shared servedQueryPage from the door's hasMore. The row cap is the tool's own: page = min(limit ?? maxLimit, maxLimit). The door reads limit + 1 groups and does not serve the extra one. This is the card's "same row cap and truncated contract". Right. latestPerAnswer turns a bridge answer that is not a group page (one that carries total, or lacks a boolean hasMore) into a coded 500, so it is never passed on as a list. Fail-closed. Right.
  • McpDataBridge.query opts gains optional latestPer, and a new exported type McpLatestPer is added. An optional input member breaks no implementer. A host bridge that ignores the member and answers a plain list with total is refused by latestPerAnswer. Right (see the nit in ③).
  • New exports. @objectstack/objectql exports LATEST_PER, LATEST_PER_MAX_KEYS and the types LatestPerRequest, LatestPerOrder and LatestPerOutcome. @objectstack/driver-sql exports LATEST_PER_DIRECTIVE, latestPerDirectiveOf and the types LatestPerDirective and LatestPerDirectiveOrder. All are additive. Right. Both keys are Symbol.for symbols and are never wire or QueryAST keys. @objectstack/spec is unchanged, and the claim amendment's "no spec member" line holds.
  • findData (metadata-protocol) gains an in-process symbol member on its request. There is no wire change, because a JSON body cannot carry a symbol. Right.

Read-path bound: is every row the new shape returns held to the same walls a plain query_records read applies? Judged against the code at this head:

  • Tenant wall. The driver's outer find statement is unchanged: applyTenantScope + applyFilters(where). It gains one predicate, id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (...) FROM t WHERE ...) w WHERE rn = 1). The inner select runs applyTenantScope with the read's own options and applyFilters with the same final where (sql-driver-latest-per.ts). Every returned row still passes the outer wall. The window also chooses only among in-tenant rows, so another organization's newer row cannot win a group and blank it. Holds. The driver test and the dogfood two-org wall pin it, with armed controls.

  • RLS, sharing and composed scopes. The directive is attached in engine-find.ts after composeReadableIdsAtBoundary, on the AST that has already passed the doors, the middleware chain and beforeFind. Its where therefore carries every composed scope. The inner predicate set equals the outer one (tenant + final where), so the winner of a group is always a row the outer statement admits. There is no "group vanishes because a hidden row won" inference channel. Holds. The dogfood "hidden newest answers newest visible" test and its armed RLS control pin it.

  • Field-level read judgement, partition and order keys included. In engine.find, every partition and order field the caller's own orderBy does not already name is appended to ast.orderBy before the doors run: rejectInternalFieldEvaluation, rejectCredentialEvaluation, assertOrderByIsMaterializable and the middleware chain. They are taken back off only in withLatestPerDirective at the executor boundary. plugin-security's predicate guard (collectQueryFields, orderBy[].field) rejects with 403 on a non-readable field and never strips one. A field the caller may not read is therefore refused, not silently dropped while the directive still windows on it. Holds. The dogfood PERMISSION_DENIED case pins it. The ingress doors judge the same keys:

    • findData uses assertSortFieldsExist(..., 'latestPer'), which covers unknown, dotted, unmaterialisable and sortable: false fields, plus the stored-metadata body/hash sort refusal and assertNoInternalFieldEvaluated.
    • The stdio bridge applies the body, hash and unofferedSortRefusal checks over judgedOrderBy.
    • The engine itself refuses formula, structured-JSON, multi-value and dotted fields as INVALID_FIELD.

    Returned rows go through the unchanged masking path. The withheld-field case in the dogfood test pins it.

  • Every refusal fires before any read. At the top of engine.find, before resolveWhereTokens and the chain, the engine refuses: the shape, a driver outside the named allowlist, a federated object, an afterFind hook (hasHooksFor, wildcard-matching), object-keyed middleware, and the field kinds above. findData refuses unknown or unsortable keys and latestPer combined with groupBy/aggregations before the engine. The MCP readGuard runs first. The Turso remote face refuses the directive in the driver too, before any statement. Holds. Two exits come after a read, and both are faults, not request refusals:

    • The outcome !== 'served' 500, fired by the protocol, runtime and stdio layers.
    • The "planned read cannot carry a latest-per request" invariant, which fires after composeReadableIdsAtBoundary.

    Neither serves rows. Right.

  • Dialects. The allowlist admits the driver-sql name for every dialect it speaks. MSSQL and Oracle are federation-only families in driver-sql, and federated objects are refused, so only SQLite, Postgres and MySQL 8 managed tables reach the window. The CASE WHEN ... IS NULL key, the derived-table alias and the quoted ?? identifiers are valid on all three. Right.

② Semver level

The changeset .changeset/35145-mcp-latest-per.md lists @objectstack/mcp, @objectstack/objectql, @objectstack/driver-sql, @objectstack/driver-turso, @objectstack/metadata-protocol and @objectstack/runtime, all at patch. That set is exactly the released packages whose src this diff changes outside tests. driver-sqlite-wasm gets only a test, packages/qa/dogfood is a test, scripts/ and content/docs do not publish, and skip-changeset is correctly absent.

Both declaration lines appear, line-initial, in the PR body and the changeset body:

  • Clause-②: yes (widening)
  • Metadata-protocol: none

These are right. The change adds a read form on the published MCP tool surface and new exports, and it adds no spec key, no accepted metadata value and no metadata type. The AGENTS.md changeset rule then ships a non-protocol widening as patch. patch matches what the diff publishes. There is no breaking arm, so no migration text or ADR-0087 marker is owed. Check Changeset concluded success on this head.

Clause-②: yes (widening): matches the diff. A published MCP tool input is widened, and every pre-existing call is unchanged.

③ Boundary flags

  • open_questions: [] in os-dev-report 6979530359. Nothing is owed.
  • security_findings: none declared. None found in this review.
  • Dev deviation (1): a one-line DECLARED_WATCH_HINTS entry in scripts/check-tenant-chokepoint.mjs for the new sql-driver-latest-per.ts. This is outside the amended file surface. Answered, accepted. It widens what the tenant-chokepoint gate watches to cover a new module that calls applyTenantScope, and the gate's self-test demands it. Nothing is loosened.
  • Dev deviation (2): the driver-sqlite-wasm test file. Answered, accepted. The amendment admits that package for its allowlist entry, and the test pins exactly that.
  • Dev deviation (3): Part of #35145 in place of Refs #35145. Answered, accepted. Both are non-closing, and the card stays open for PR 2. PR-body guards concluded success.
  • MySQL not measured locally. CI's live-dialect job runs on push and schedule, not on this PR, and Temporal Conformance is skipped here. Answered, not blocking. The statement uses MySQL 8 features the repo already targets, and the cell runs on the first push to main. The seat should read that run after landing.
  • Overlap with open PRs feat(mcp): query_records and get_record name the fields field-level security withheld from the caller #35179 and feat(mcp): aggregate_records orders, cuts and counts groups in the database #35193 in mcp-http-tools.ts. Answered. Whichever lands second merges main, per the claim.
  • SQL push-down (Prime Directive 5): no finding. One row per group is computed in one SQL statement as a ROW_NUMBER() window inside an id IN subquery. No id list is materialised in the app, no in-app join or dedupe runs, the group probe is limit + 1 in SQL, and no COUNT is run. Drivers that cannot push it down are refused, not approximated.
  • Nit, no effect on the contract: outcome = 'served' is stamped when driver.find returns on an allowlisted driver. It attests the engine path, not that the driver compiled the directive. The driver ablation pins the compile, and a symbol-stripping wrapper between engine and driver would degrade the answer, not the walls.
  • Nit: findLatestPer takes a server probe limit (listPlan.probe, a row budget with no page size) as the group page and skips assertQueryReadRows. This is unreachable from the MCP door, which always sends limit.
  • Nit: latestPerAnswer recognises a non-group answer by shape (total present or hasMore not boolean). A third-party bridge that ignores latestPer and answers { records, hasMore } without total would pass. Both in-repo bridges serve it.
  • Pre-existing, outside diff: none named.

Implemented-by: claude/issue-35145-mcp-latest-per-and-related-read
Reviewed-by: session_01JQwxbaX2qDxUq9sF93EqqL

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbXr9wLAH24MEgxaLud

席位核对

L1 full · ACCEPT · Head-sha: 303482dda2b7d2aebe857f06b5ef9b4b709daad4 · card #35145 (Part of #35145, PR 1 of 2) · read 2026-11-18T13:44Z

Net diff against merge base c787255a49: 27 files, +1971 / -30. Not governed. It reads under row and field security.

Against the card

  • Part of is right. This PR carries the card's "latest per group" half: one bounded read on query_records, under the caller's row and field security, with the list cap and the truncated contract, and a stable refusal where a driver cannot compile it. The related-objects read and the ask-card kinds (scenarios: the open ask cards cover the ten question kinds the hosted ask set asks, so an ask regression is caught here first #35113) stay for PR 2, so the merge must not close the card.
  • The card's "reading first" item is answered in the body. The engine had no one-statement form, so the SQL drivers compile a ROW_NUMBER() window, and every other driver refuses with no slower in-memory path, as the card asks.
  • File surface. The source is in the claimed packages. Three items are declared deviations: the one DECLARED_WATCH_HINTS row in scripts/check-tenant-chokepoint.mjs (the new driver file reads the tenant scope, so the gate's own self-test asks for it), the sqlite-wasm test, and the Part of spelling. I accept all three.

Rules checked at the head

  • The choice runs over the caller's own rows.

    • The engine attaches the window directive only at the executor boundary, on the AST that composeReadableIdsAtBoundary returns, after the doors, the middleware chain and beforeFind.
    • In the driver, the window subquery applies the same applyTenantScope and the same applyFilters(query.where) as the outer statement, so the row that wins a group is chosen only from rows the composed read admits.
    • The outer statement keeps its own tenant scope, where, ORDER BY, projection, limit and offset.
    • The dogfood case pins the property end to end: a row policy hides a group's newest row, and the answer is that group's newest readable row, never the hidden one and never an empty group.
  • The partition and order fields pass every sort gate.

    • On the HTTP door, findData runs them through assertSortFieldsExist. That covers unknown, dotted and unmaterializable fields, and fields declared sortable: false. They also go through the stored-body and stored-hash predicate refusals and the internal-field gate.
    • In the engine they are appended to the AST's orderBy before the secret-field gate and the middleware chain run, so the field-security predicate guard refuses a hidden field exactly as it refuses one in orderBy. They are taken back off only at the boundary.
    • On stdio they join the stored-body, stored-hash and sortable verdicts.
    • The engine also refuses formula, JSON, multi-value and dotted fields as partition or order keys.
  • Refusal before any read. The engine refuses with INVALID_QUERY / 400 before anything is read in each of these cases:

    • a driver outside the allowlist (the SQL driver, sqlite-wasm, and Turso only on its local or replica face),
    • a federated object (so the federation-only SQL dialects never reach the window),
    • an object with an afterFind hook or object-keyed read middleware, where a group could lose its answer after the driver chose it.

    Turso's remote face also refuses the directive itself. A planned (semi-join) read cannot carry it.

  • The request is in-process only. It rides Symbol.for('objectstack.objectql.latestPer') from the MCP bridges through callData and findData to find. It is never a wire or query key, so no REST caller can reach it.

  • An unserved read is never passed off as an answer. The engine marks outcome: served only after the driver answered the window. findData, callData and the stdio bridge each refuse a read without that mark. The tool layer refuses a bridge answer that is not one page of groups, or that carries a total.

  • Paging. limit counts groups, and the tool caps it at maxLimit. The doors read limit + 1 and answer hasMore, with no total and no COUNT. truncated: true comes from the shared servedQueryPage, and a plain query_records call keeps its own probe unchanged.

  • The MCP read guard still judges objectName first. latestPer reaches no object other than the one named.

  • Tests. The live dialect matrix covers SQLite, Postgres and MySQL (MySQL in CI's live-dialect job). There are also the engine refusal table, the findData door, the tool bounds, the sqlite-wasm and Turso-remote suites, and the CRM dogfood over /mcp with a real two-organization wall and armed controls. The driver ablation turns five pins red and keeps the three that do not depend on the predicate green.

Declarations, docs, merge

  • Changeset, read sentence by sentence. Six packages, all patch. Clause-②: yes (widening): a new optional tool argument and new exports, and every read without latestPer is unchanged. Metadata-protocol: none, and @objectstack/spec is untouched. Each bullet matches the code (bounds, tie and null order, the choice over readable rows, the refusals, the paging contract, the exports).
  • connect-mcp.mdx. The new section says what the code does. Its driver list names the dialects the driver serves to managed objects (Oracle and SQL Server are federation-only per drivers.mdx, and federated objects are refused). No existing sentence becomes false.
  • Merges cleanly onto origin/main ba6556c617.
  • Check-runs at this head: 55 in total, all completed, none failed (40 success, 15 skipped).

Nits (none blocks)

  • findLatestPer reads findQuery.limit as the group page. It ignores whether the list plan set that limit as a server probe (a row budget with no page size). The MCP tools always pass a limit, so no caller reaches that case today. A later in-process caller would.
  • The window's ORDER BY puts empty values last with a CASE per key, which a plain index on the order column does not cover. That is fine at limit + 1 groups, but worth knowing for large partitions.

Not mine, still owed before landing

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbaX2qDxUq9sF93EqqL

Landing · 2026-11-18T13:45Z. Head 303482dda2b7d2aebe857f06b5ef9b4b709daad4 (PR 1 of 2 for #35145; Part of, so the card stays open for PR 2):

Marked ready, and auto-merge is armed.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 18, 2026 13:45
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 18, 2026
Merged via the queue into main with commit 1caee8c Nov 18, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-35145-mcp-latest-per-and-related-read branch November 18, 2026 14:08
os-warren pushed a commit that referenced this pull request Nov 18, 2026
… the aggregate order and cut

Five adjacent-insertion conflicts, each resolved keeping both sides: the
engine exports and the runtime imports of AGGREGATE_ORDER_CUT beside
LATEST_PER (objectql index, runtime action-execution and domains/mcp), the
two Symbol.for read options in the stdio bridge, and the aggregation-entry
test, where the order-and-cut describe block and #35202's lookup-label
block both land after the served-schema block. mcp-http-tools.ts merged
without conflict.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
os-warren pushed a commit that referenced this pull request Nov 18, 2026
…e order and cut

One conflict, in packages/mcp/src/stdio-data-bridge.ts, resolved keeping
both sides: the two Symbol.for read-option constants (this branch's
STDIO_AGGREGATE_ORDER_CUT and #35199's STDIO_LATEST_PER), each under its
own docblock, then #35225's stdioExpandMap byte-identical to main, then
unwrapRows under its own docblock. mcp-http-tools.ts and runtime
domains/mcp.ts merged without conflict.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/xl tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants