Repository navigation
feat(spec, objectql, driver-sql, driver-turso): run a per-measure aggregation filter in SQL behind one driver capability bit - #33854
Conversation
An optional DriverCapabilities boolean: aggregate() evaluates a per-measure aggregations[].filter itself, with the engine's in-memory answer. Absence means false, so a driver that declares nothing keeps the in-memory path. Regenerated the authorable surface and the driver reference pages. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
…gate aggregate() compiles aggregations[].filter with the same where compiler a where goes through and places it in fn(CASE WHEN (pred) THEN arg END); count(*) becomes count(CASE WHEN (pred) THEN 1 END) with no ELSE. A group the filter empties answers the empty-group value. A predicate that cannot be lifted cleanly is refused NOT_IMPLEMENTED/501. SqlDriver advertises supports.aggregationFilter. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
The remote transport refuses a per-aggregation filter, so remote mode reports the bit off and the engine keeps filtered measures on find() plus in-memory aggregation. Local and replica modes inherit SqlDriver's compile. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
…ory walker The walker's value-less exit read undefined only, so a SQL NULL column reached the JS comparison and coerced to 0: count where amount <= 0 counted every row with no amount, and $between failed neither bound. A NULL column now fails $gt, $gte, $lt, $lte and $between, as an absent one does and as SQL does. The equality family, $in/$nin, the presence operators and a null comparand answer as before. Pinned on all three faces: the measure filter, having, and the in-memory where for plugin drivers. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
… bit engine.aggregate sends an aggregate whose measures carry a filter to driver.aggregate only when the driver declares supports.aggregationFilter and has the method; every other driver keeps find() plus in-memory aggregation. The other forks that force the rows path still win. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
… numbers under the security layer Two engines over the same data and security (isolated tenancy, row-level security, an unreadable field): SqlDriver with the capability, and the same driver reporting it off. Every function answers the same rows and numbers on both, and neither counts another organization's row or a row outside the member's read scope that the filter would match. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
…ry read builder The two builders that compile a measure filter's predicate now carry the statement's tenant scope, so every read builder routes through applyTenantScope; the lift strips the scoped reference statement and its bindings. A test pins that each organization counts only its own rows and that the tenant predicate stays in the WHERE, outside the CASE. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
… that SqlDriver compiles them The compensated-sum file keeps its rows path by reporting the capability off; the where-doors file records the 400 a compiled measure filter answers and keeps the 200 on a driver without the bit; the analytics echo case asserts the conditional aggregate the driver now runs. No expected number changes. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
…s evaluated now The aggregate() contract, the in-memory aggregation header and the remote transport's refusal said every driver lowers a measure filter in memory. They now name the aggregationFilter capability. The changeset records the where-compiler refusal a compiled measure filter now shares. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
📓 Docs Drift CheckThis PR changes 4 package(s): 7 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 2 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 178 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin d83052d5a4d0bd788e9460bbc1685553c49a0439 && git checkout d83052d5a4d0bd788e9460bbc1685553c49a0439
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 895783a1e864e0fe629c56b3c6315771ca87bf87 aea485202eb2e4a293afa06bfc04cd8f2571bbcf && git checkout -B drift-repro 895783a1e864e0fe629c56b3c6315771ca87bf87 && git merge --no-ff aea485202eb2e4a293afa06bfc04cd8f2571bbcf
node scripts/docs-audit/affected-docs.mjs --json 895783a1e864e0fe629c56b3c6315771ca87bf87
|
|
domain:spec#4 · os-project-manager · session_01FEkQ5mecqk8M5q9vjKj6aS Contract-review-handoff: review#1 — CONTRACT_REVIEW_TIER unavailable (maintainer routing 「review#1 正在入座,你这个账户后续的契约复审找他」, 2026-11-15T12:23Z) · head 1e2fb85 |
|
review#1 · os-elon-musk · session_016WV4cy7hQ5MvQ83ByNZ8ZH Contract-review-claim: session_016WV4cy7hQ5MvQ83ByNZ8ZH · head 1e2fb85 · 2026-11-15T12:26:06Z |
|
review#1 · os-elon-musk · session_016WV4cy7hQ5MvQ83ByNZ8ZH Contract reviewServed-tier: First review of this head. Claim: comment 6894293725. Tier evidence: ① Derived judgments
② Semver level
③ Boundary flags
④ Design judgment
Implementing files: the engine gate is a strict M1 (must-fix) — the head does not type-check. S1 (should-fix) — S2 (should-fix) — the bit's TSDoc promises more than was measured, and Nits, no effect on the verdict:
Implemented-by: VERDICT: FAIL |
knex.raw takes RawBinding[]; the lifted predicate's bindings were typed unknown[], which the package type-check refuses. They are the bindings knex's own toSQL() returned, so they carry its Value type through. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
…by the backend collation The aggregationFilter bit promised the in-memory answer on every operator but text ordering, which was measured on SQLite and PostgreSQL 16 only. Text equality and membership also follow a case- or accent-insensitive collation, as the same datasource's where does; the TSDoc, the describe and the changeset now say so and name MySQL and SQL Server as not measured. The changeset's kind line becomes semantic: a stored having or measure filter keeps validating and now matches other rows under the NULL rule. The query syntax page drops a row that listed the per-measure filter as not enforced. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
|
domain:spec#4 · os-project-manager · session_01FEkQ5mecqk8M5q9vjKj6aS Contract-review-handoff: review#1 — CONTRACT_REVIEW_TIER unavailable (maintainer routing 「review#1 正在入座,你这个账户后续的契约复审找他」, 2026-11-15T13:19Z) · head 8e48947 |
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head 8e48947 · 2026-11-15T13:21Z |
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract reviewServed-tier: Read at 2026-11-15T13:43Z. Claim: comment 6894944006. Handed to review#2 by review#1 (6894936609 on mailbox #33873). Delta review of the earlier record, ID 6894395884, which reviewed head Closures, by id:
One new finding on this head, S3 below, on a ① Derived judgments
② Semver level
③ Boundary flags
④ Design judgmentNo must-fix.
S3 (should-fix) — the The remaining implementing files ( Nits, no effect on the verdict:
Implemented-by: VERDICT: PASS |
…t and name Oracle as unmeasured The aggregate() TSDoc said a driver declaring aggregationFilter answers each measure filter with the in-memory path's answers; it now defers to the latitude the bit states. The bit's TSDoc and the changeset name Oracle beside MySQL and SQL Server as not measured. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf
|
domain:spec#4 · os-project-manager · session_01FEkQ5mecqk8M5q9vjKj6aS ACCEPT · PR #33854 (#33698) · head
|
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head aea4852 · 2026-11-15T15:00Z |
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract reviewServed-tier: Read at 2026-11-15T15:04Z. Claim: comment 6896505381. Independence: implemented and dispatched by domain:spec#4 (os-project-manager); reviewed by os-tesla. Delta review of record 6895214298, which judged head Closures, by id:
M1, S1 and S2 stay closed. One new nit on this head, N5 below. ① Derived judgments
② Semver level
③ Boundary flags
④ Design judgmentNo must-fix, no should-fix.
One thing I tried to break: Oracle treats the empty string as NULL, which is not a collation matter. It does not falsify the sentence. The rule the bit states is the The remaining implementing files ( Nits, no effect on the verdict:
Implemented-by: VERDICT: PASS |
…ter, and where a per-measure filter runs (objectstack-ai#34014) <!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9NXd2SJ1z5XQzawbhD1qEaF)_ Fixes objectstack-ai#33868 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:查询技能新增一条规则「没有值的列(null 或缺失)不满足任何大小比较(`$gt/$gte/$lt/$lte/$between`)」,并改正了「带 filter 的度量一定走内存」这句已过时的话(声明 `aggregationFilter` 的驱动在数据库里算),另加一条评测用例。 - 为什么改:objectstack-ai#33854 已改变运行时行为;不教的话,作者和 AI 会以为 `amount $lte 0` 也会把没填金额的记录算进去,仪表盘上的数字会被误读,且技能还在说一句已经不成立的话。 - 风险与回滚:只改技能文档、一条 eval 和一个 changeset,不动运行时代码;回滚即 revert 本 PR。 - 先看:`skills/objectstack-query/rules/aggregation.md`(Filtered Aggregation 提示块,措辞最接近契约承诺)→ `rules/filters.md`(新规则一节,以及为付账删掉的两处重复)→ `evals/filters-pagination-search.json` 第 8 条。 - 两分钟验证:`node scripts/check-skills-token-ratchet.mjs`,预期全绿,filters.md 显示 `2473 / 2473`、aggregation.md 显示 `2264 / 2357`。 - 需要你做的:批准本 draft(受管面 Tier H)。 ## What changes The query skill now teaches two things PR objectstack-ai#33854 made true, and drops one sentence it made false. `skills/objectstack-query/rules/filters.md` (published, English): - **New section "A column with no value fails every ordering test"** (it replaces "Prefer `$null` to a bare `null` comparand", whose rule is kept as its last sentence): `$gt` / `$gte` / `$lt` / `$lte` / `$between` never match a row whose column is null or absent, in `where`, an aggregation's `filter` and `having` alike; `{ amount: { $lte: 0 } }` skips the rows with no amount, and an `$or` with `{ amount: { $null: true } }` keeps them. `null` is not an ordering comparand (`{ $gte: null }` is refused `INVALID_FILTER` / 400). - **Paid for in the same file** by two restatements: the case-sensitivity paragraph, whose rule `SKILL.md` § String Operators carries ("compare CASE-SENSITIVELY; `$icontains` is the case-INSENSITIVE twin (ASCII folding only)"), now a one-line pointer; and the second Date example (`$between` over two `Date`s), whose home is the operator table's `$between` row plus the `$gte: new Date(…)` example kept directly above it. Lost with no home: the `café` / `CAFÉ` illustration of ASCII-only folding (the rule survives in SKILL.md). `skills/objectstack-query/rules/aggregation.md`: - **§ Filtered Aggregation:** the callout no longer says any filtered measure "forces the in-memory path — no driver compiles a conditional aggregate, and one reached directly refuses `NOT_IMPLEMENTED`". A driver that declares `supports.aggregationFilter` (`driver-sql`; `driver-turso` outside remote mode) runs the filter in the database whenever the aggregate itself is pushed down (a date bucket under a non-UTC `timezone`, or a granularity the driver does not bucket natively, keeps the whole call in memory: `tzRequiresInMemory` and `allStructuredSupported` sit in the same route condition), compiled as that datasource's `where` is: it answers what the same condition answers there (text by the database collation) and is refused where it is (the pinned case: a `{ $field }` comparison on a column the object does not declare, `INVALID_FILTER` / 400). On any other driver the engine reads the scoped rows and evaluates the filter itself; no answer is promised beyond that. A column with no value fails its ordering tests either way. - **§ HAVING:** `avg` / `min` / `max` over no values is `null`, so `having: { average: { $lte: 0 } }` drops that group. `skills/objectstack-query/evals/filters-pagination-search.json`: case 8, one aggregate call returning the total and the count of deals whose `amount` is zero or less, where a deal with no amount must count. `must_contain`: `filter`, `$or`, `$lte: 0`, `$null: true`; `must_not_contain` is empty, so no correct answer that restates the rule can trip it. Spliced with the file's hand formatting kept. `skills/objectstack-ui/rules/dashboards.md` is untouched: it never states how a measure filter is evaluated (it only lists "measure-scoped filters" as fitting a dataset). `.changeset/33868-skills-no-value-ordering-measure-filter.md`: `'@objectstack/skills': patch`. Every taught fact is read from origin/main at or after `0ac112fc`: - `packages/objectql/src/having-filter.ts`: `NULL_IS_NOT_ORDERED_OPERATORS = new Set(['$gt', '$gte', '$lt', '$lte', '$between'])`; in `checkCondition`, `if (value === undefined && !NO_VALUE_ANSWERED_BY_OPERATOR.has(op)) return false;` then `if (value === null && NULL_IS_NOT_ORDERED_OPERATORS.has(op) && !orderingComparandHoldsNull(op, target)) return false;`. Pinned by `having-filter-null-ordering.test.ts` (each face, and the empty-group `having`) and `packages/rest/src/aggregate-measure-filter-pushdown.test.ts` ("a NULL amount fails an ordering filter on both paths"). - `packages/spec/src/data/filter.zod.ts` ("null is NOT a comparand: null is not ordered — state absence with the null predicate instead") and `filter-comparand-shape.ts` (`nullOrderingComparandError`, `INVALID_FILTER` / 400). - `packages/objectql/src/engine-delete-and-aggregate.ts`: `const aggregationFilterNative = drv?.supports?.aggregationFilter === true;` and the `(!hasAggregationFilter || aggregationFilterNative)` route condition. - `packages/drivers/driver-sql/src/sql-driver.ts` (`aggregationFilter: true`); `packages/drivers/driver-turso/src/turso-driver.ts` (`aggregationFilter: false` in remote mode); `packages/spec/src/data/driver.zod.ts` (the bit's describe text: text compares by the backend collation as in `where`). - `packages/rest/src/aggregation-filter-where-doors.test.ts`: the `where` twin and the per-aggregation filter of `{ created_at: { $ne: { $field: 'photo' } } }` on an audit-opt-out object both answer `{ status: 400, code: 'INVALID_FILTER' }` on driver-sql. ### Size readings (tree objectstack-ai/objectstack, origin/main bc6b7ff → head d47493b) | Reading | Before | After | |:--|--:|--:| | `rules/filters.md` lines / bytes / tokens | 211 / 9925 / 2482 | 209 / 9892 / 2473 (row re-locked 2482 → 2473 at the measurement) | | `rules/aggregation.md` lines / bytes / tokens | 262 / 8381 / 2096 | 270 / 9053 / 2264 (ceiling 2357, row unchanged) | | `evals/filters-pagination-search.json` lines / bytes / tokens | 75 / 5464 / 1366 | 85 / 6422 / 1606 (eval fixture, measured, not ratcheted) | | All 11 `skills/*/SKILL.md` lines | 4596 | 4596 (none touched) | | Whole bundle, ratcheted (authored) tokens / ceilings | 187685 / 194017 | 187844 / 194008 (+159 / -9) | | Whole bundle, eval fixtures tokens | 46508 | 46748 (+240) | | Whole bundle total tokens | 245988 | 246387 (+399) | `scripts/check-skills-token-ratchet.mjs`: the `filters.md` row is re-locked at its measured 2473 (review N3), with the arithmetic and each cut's home in the row comment; no other row moves. ## Tests No code changed, so there is nothing to ablate. Gate readings are under Verification. ## Acceptance notes - **Build tier, declared:** `dispatch-gates --tier` puts `skills/**` at the contract-review tier (clause ①). This card thread is served below it and cannot switch its own model, so (as the claim records) the authoring and the commit ran in an isolated os-dev subagent pinned to the contract-review tier inside this worktree; the merge of main, relay writes, gates and report ran in the thread. - **Not taught, on purpose:** what `$ne` / `$nin` / `$notContains` answer on a column with no value (each answers a column with no value by its own arm, `NO_VALUE_ANSWERED_BY_OPERATOR`). It is a standing rule this card did not change; the card's list of unchanged operators also omits `$empty`, which the code keeps in the same set. - **Refusal wording:** the skill names only the pinned refusal case. A plain undeclared key (`{ nope: 1 }`) answers `INVALID_FIELD`, not `INVALID_FILTER`, on both positions (row 4 of `aggregation-filter-where-doors.test.ts`), so "undeclared column ⇒ `INVALID_FILTER`" is not written bare. - **NOT MEASURED:** `driver-mongodb` own `where` on a null column with `$lte` (no pin read; it rests on BSON type bracketing). `driver-memory` own `find` is pinned by `memory-matcher-null-value-and-comparand.test.ts` (objectstack-ai#13553), per review 6897568297. - Review round 1 (record 6897568297): S1 (pushdown clause), N1 ("no values") and N3 (row re-lock) taken in one commit, `b87277b6`, authored at the contract-review tier like the first; N2 left as is. - Main was merged before each gate run (`a7754819`, `d47493ba`) so the derivation read a current tree. ## Verification All readings are at head `d47493ba` (`git rev-parse --short HEAD` after the last commit), tree objectstack-ai/objectstack. - Package build closure: `turbo run build --concurrency=2 --filter='./packages/**'` under `os-verify-lock.sh`, `VERDICT command-exit 0` (held 5m35s, after the first merge; the second merge touched only `scripts/pm/**` and `.claude/**`, nothing built). - Acceptance gates: `check:skill-docs` ✅ "Skill docs in sync"; `check:skill-refs` ✅ "9 generated files in sync with packages/spec"; `check:skill-examples` ✅ "346 prose examples type-check across 3 surface(s)"; `check-skills-token-ratchet` ✓ "57 authored bundle file(s) within their ceilings", rows `2473 / 2473` and `2264 / 2357`. - `dispatch-gates --ran`: "63 derived famil(ies) accounted for — 63 run, 0 NOT-MEASURED (a DERIVED zero)" (63, not 45: the ratchet script is now in the diff, so its families and `check:pm-dispatch-gates` are derived). Three extra runs are recorded outside the derivation (`check:skill-docs`, `check:skill-refs`, `check:skill-examples`). - CI families outside the derived list are left to this PR's check-runs. <details><summary>Derived gate list, 63 + 3, exit codes captured before any pipe</summary> ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-declaration-mirrors.mjs :: exit 0 node scripts/check-declaration-mirrors.mjs --self-test :: exit 0 node scripts/check-doc-route-spelling.mjs --advisory :: exit 0 node scripts/check-doc-route-spelling.mjs --self-test :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-self-test-wired.mjs :: exit 0 node scripts/check-self-test-wired.mjs --self-test :: exit 0 node scripts/check-self-test-workflow-commands.mjs :: exit 0 node scripts/check-self-test-workflow-commands.mjs --self-test :: exit 0 node scripts/check-skills-token-ratchet.mjs :: exit 0 node scripts/check-skills-token-ratchet.mjs --self-test :: exit 0 node scripts/check-whole-set-label-write.mjs :: exit 0 node scripts/check-whole-set-label-write.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/bare-root-worklist.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions :: exit 0 pnpm check:agent-test-spelling :: exit 0 pnpm check:bash32-floor :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cli-command-ids :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:corpus-claim-drift :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:entry-guard :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:parse-guard :: exit 0 pnpm check:pm-dispatch-gates :: exit 0 pnpm check:pm-governed-merges :: exit 0 pnpm check:pm-skill-id-lint :: exit 0 pnpm check:pnpm-filter-targets :: exit 0 pnpm check:pnpm-flag-spellings :: exit 0 pnpm check:published-files :: exit 0 pnpm check:ratchet-remedy-authority :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:role-word :: exit 0 pnpm check:scripts-symbol-anchors :: exit 0 pnpm check:skill-compatibility :: exit 0 pnpm check:skill-frame-sync :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:skill-links :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm --filter @objectstack/spec check:skill-docs :: exit 0 pnpm --filter @objectstack/spec check:skill-refs :: exit 0 pnpm --filter @objectstack/spec check:skill-examples :: exit 0 ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQokeaWJKGm2S7ZrDA)_ <!-- signed: domain:skills#2 · os-steve · session_01ADHkmRxXmVQ41fqnaTPGAv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Fixes #33698
What changes
A per-measure aggregation filter (
aggregations[].filter) now runs inside SQL on driver-sql, as a conditional aggregate, instead of the engine reading every scoped row into memory. The route is the one capability bit the card's route A names.DriverCapabilitiesSchemagains one optional boolean,aggregationFilter: the driver'saggregate()evaluates a per-measure filter itself, with the engine's in-memory answers. Absence meansfalse. Its TSDoc states the promise, the engine reader, why it is a bit and not method presence, and the latitude it inherits: text comparison in a measure filter follows the backend collation, as thewhereof the same datasource does (ordering everywhere; equality and membership on a case- or accent-insensitive collation), with the measured and unmeasured dialects named. Regenerated:authorable-surface/data.jsonand the three driver reference pages undercontent/docs/references/data/.engine-delete-and-aggregate.ts). A filtered aggregate goes todriver.aggregateonly whendriver.supports.aggregationFilter === trueand the driver has the method. Every other driver keepsfind()plusapplyInMemoryAggregation, unchanged. The other forks that force the rows path (a non-UTC timezone with a date bucket, an unadvertised granularity) still win.whereuses (applyFilterson a builder of the same table), lifted out ofselect * from t where …and placed inCASE WHEN. The lift is guarded: a compiled statement that is not exactly that prefix plus one predicate, or whose?placeholders do not pair one to one with its bindings, is refusedNOT_IMPLEMENTED/ 501 instead of guessed at (no tested dialect reaches it; a test forces it). Both the reference builder and the filtered builder go throughapplyTenantScope, like every read builder in the driver (check:tenant-chokepoint), so the lift strips the same scoped prefix and the tenant predicate stays in the statement's ownWHERE, outside everyCASE; a test pins that with two organizations. SQL Server's GUID priming now also reads the measure filters.SqliteWasmDriverinherits the compile (probed: filtered sum and count answer correctly).aggregationFilter: false, the way it emptiesqueryDateGranularity, becauseRemoteTransport.aggregaterefuses the key (501). Local mode inheritstrueand runs SqlDriver's compile; a test measures it answering a filtered sum.$gt,$gte,$lt,$lteand$betweenin the in-memory evaluator, as an absent column already did. See Observable change below.The SQL shape, per function (H4)
predis the where compiler's predicate for that measure's filter; the statement's ownWHERE(tenant wall, read scope, the caller'swhere) is untouched.sumsum(col)sum(CASE WHEN (pred) THEN col END)avgavg(col)avg(CASE WHEN (pred) THEN col END)minmin(col)min(CASE WHEN (pred) THEN col END)maxmax(col)max(CASE WHEN (pred) THEN col END)count(no field)count(*)count(CASE WHEN (pred) THEN 1 END)count(field)count(col)count(CASE WHEN (pred) THEN col END)count_distinctcount(distinct col)count(distinct CASE WHEN (pred) THEN col END)colkeeps the existing aggregand wrapping (PG boolean cast, double accumulation forsum/avg). NoELSEanywhere: a row the filter rejects contributes NULL, which every aggregate skips, socountnever counts it (ELSE 0would). A group the filter empties answers the existing empty-group values (sumand the counts0,avg/min/maxnull).CASE WHENis used on every dialect, PostgreSQL included, so there is one shape to test.Observable change
Faster filtered measures on driver-sql, same numbers (bench below).
The in-memory evaluator stops treating NULL as 0 in ordering tests. It serves three faces: a measure filter on a driver without the bit,
having, and the in-memorywherethat plugin drivers use (matchesDriverWhere). Before: "count where amount ≤ 0" also counted every row with no amount;$gte 0/$gt -5/$lt 1likewise;$betweenmatched a NULL column for any bounds (numbers, text, dates, times); ahavinglikeavg_amount ≤ 0kept an empty group (whoseavgisnull). After: none of those match, as SQL and the spec ("null is not ordered") say. Unchanged:$eq,$ne,$in,$nin,$exists,$null,$empty, and anullcomparand.A direct
SqlDriver#aggregatecall with a measure filter answers the filtered numbers instead of refusing 501.A measure filter the where compiler refuses now refuses on driver-sql (seat ruling A, comment 6893557132). Because the filter is compiled by the same where compiler as
where, it answers what itswheretwin answers. The recorded case is inaggregation-filter-where-doors.test.ts: a{ $field }comparison ofcreated_atwith an image field on an object with no audit fields.whererefused it400 INVALID_FILTERbefore and still does; the measure filter used to be evaluated in memory and answer200(total 6), and on driver-sql it now answers400 INVALID_FILTER. On a driver without the bit it still answers200, and a new case pins that. The changeset says so.Text in a measure filter compares by the database collation on driver-sql, as the
whereof the same datasource already does. The in-memory path compares text exactly. On a case-insensitive collation,stage $eq 'won'now also countsWonrows, aswhere: { stage: 'won' }already selects them; ordering a non-temporal text column follows the collation everywhere. Measured: SQLite, and PostgreSQL 16 with aC.UTF-8collation, agree with the in-memory path on every operator; PostgreSQL 16 with an ICUen-UScollation differs only in text ordering. MySQL, SQL Server and Oracle were not measured; the MySQL and SQL Server default collations are case-insensitive. The bit is declared on every dialect (review#1 S2, option (b)): gating them off would keep those dialects on a path that answers differently from their ownwhere.For the contract reviewer (review#1)
Two observable changes above go beyond speed and want a reading against the contract: item 2 (the in-memory NULL rule, which also changes
havingand plugin-driverwhere) and item 4 (a measure filter now shares itswheretwin's refusal on driver-sql, so the same request answers400on driver-sql and200on a driver without the bit). Item 4 makes the measure filter agree with thewhereposition the spec pairs it with; the remaining split is between drivers, not between positions on one driver.Why
#33698: a measure filter forced
engine.aggregateontofind()plus in-memory aggregation for every driver, so a filtered dashboard tile read the whole scoped table into the process.H3 measured before the engine edit, per the order: 119 filters through the real engine on a real SqlDriver, in-memory evaluator against driver-sql's where compiler (
/mnt/project-files/pm-orders/spec/33698-h3-measurement.md). SQLite 106 same / 13 different; PostgreSQL 16 C.UTF-8 106 / 13; PostgreSQL 16 ICU en-US 101 / 18; four of the "different" rows were the same refusal envelope on both sides. The gap was reported asneeds_decision(6892601944); the seat ruled option C (6892621130): fix the walker's NULL rule in this PR, then the static bit is enough. The gap left is declared, not gated (observable change 5): text comparison follows the database collation, as forwhere. MySQL, SQL Server and Oracle were not measured (no server in the container).Verification
Tests added or changed:
packages/drivers/driver-sql/src/sql-driver-aggregation-filter.test.ts(replaces…-filter-refusal.test.ts): each of the six functions with a measure filter, per group including a group the filter empties, against a hand-written answer and againstfind(where = filter)aggregated in JS;count(field)vscount(*); binding order with awhereand two filtered measures; NULL ordering; vacuous{}; a filter the where compiler refuses is refused alike; the tenant wall (two organizations: the other organization's rows count in no measure, and the tenant predicate sits inWHERE, outside theCASE); the lift guard. SQLite and live PostgreSQL 16: 28 passed, 1 skipped.sql-driver-11455-aggregate-fault-envelope.test.ts: the build-time refusal control now uses the where compiler's refusal (INVALID_FILTER/ 400).packages/objectql/src/engine-aggregate-filter-pushdown.test.ts: bit true goes todriver.aggregatewith the resolved filter; no bit,false, a truthy non-boolean, or no method go tofind()plus in-memory; a non-UTC date bucket still wins; no filtered measure is unchanged.packages/objectql/src/having-filter-null-ordering.test.ts: the NULL rule on all three faces, the unchanged operators, the empty-grouphaving, and the null comparand.packages/rest/src/aggregate-measure-filter-pushdown.test.ts: security parity throughPOST /api/v1/data/:object/querywith the realSecurityPlugin,isolatedtenancy, row-level security and an unreadable field. Two engines over identical data: SqlDriver (pushed down, asserteddriver.aggregateonce and nofind) and SqlDriver with the bit off (assertedfindonce). Same rows and numbers for every function; another organization'swonrow and an out-of-scopewonrow counted by neither; a measure filter on the unreadable field is403 PERMISSION_DENIEDon both.packages/drivers/driver-turso/src/turso-driver.test.ts: remote reports the bit off, local inherits it and answers a filtered sum.remote-transport-aggregate-function-refusal.test.ts: the two-face parity pin now says the local face compiles and each face declares what it does.packages/spec/src/data/driver.test.ts: the bit parses, is absent by default, refuses a non-boolean; five live bits.packages/rest/src/rest-aggregate-compensated-sum.test.tscompares the native and rows paths and forced the rows path with a filtered measure. Its driver now reportsaggregationFilter: false, so the two paths stay the ones their names say; all its numbers hold.packages/rest/src/aggregation-filter-where-doors.test.ts: item 4 above, re-recorded, plus the no-bit case.packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts: the measure-filter echo case asserted "the driver grouped nothing". It now asserts the one groupedsum(CASE WHEN …)statement the driver runs; the rows and the echo it runs are unchanged (SQLite and live PostgreSQL 16: 49 passed).Ablations (old behaviour put back, red, restored):
CASE, no filter bindings,count(*)):sql-driver-aggregation-filter.test.ts10 failed / 4 passed; restored 14 passed (run before the tenant-wall cases were added).count(CASE WHEN … THEN 1 ELSE 0 END): 3 failed (count, count(field) vs count(*), NULL ordering); restored.!hasAggregationFilter:engine-aggregate-filter-pushdown.test.ts2 failed / 6 passed; the bit ignored (always push): 3 failed / 5 passed; restored 8 passed.having-filter-null-ordering.test.ts28 failed / 25 passed (nine ordering cases on three faces, plus the empty-grouphaving); restored 53 passed.Suites on the final head (rebased on
main1e65a38): spec 28507 passed; objectql 13202 passed; driver-sql 4305 passed / 241 skipped (SQLite), its aggregation files on live PostgreSQL 16 285 passed / 7 skipped; driver-turso 2539 passed / 34 skipped; rest 8748 passed / 355 skipped; service-analytics 5216 passed / 335 skipped; driver-sqlite-wasm 766 passed (before the rebase).Bench (M0 row
aggregate_measure_filter, admin,groupBy status,sum(quantity) filter quantity ≥ 10+count)Same box, same build,
bench.mjs --only aggregate_measure_filter,aggregate_group_status, 20 iterations after 3 warmups. Before is this build withdriver-sql's builtsupportspatched toaggregationFilter: falsefor the run (exactly the pathmaintakes for this query:find()plus in-memory aggregation), then restored; after is the build as committed. Wall-clock on a shared box: read the ratios, not the absolute milliseconds.Control, the unfiltered
aggregate_group_status(admin) in the same runs: 100k SQLite 48.5 → 48.2, PG 46.9 → 37.1; 1M SQLite 441.9 → 417.4, PG 171.8 → 183.1. The filtered measure now costs what the unfiltered aggregate costs. The statement the server ran after (SQLite 100k, from the admin's debug timing):Nothing under
packages/qa/dogfood/bench/sql-perf/is changed: the bench writes its results under its work directory, not the repo. Its scenarionote("a per-measure filter routes engine.aggregate to the in-memory path") is now true only for drivers without the bit; left as is because the surface allows the bench only for recording numbers.Gates
On the final head
aea48520: every familynode scripts/pm/dispatch-gates.mjs --commandsderives for this tree was run, each exit code recorded before any pipe: 124 run, 124 exit 0.--ranreconciliation: 124 derived, 124 run, 0 NOT-MEASURED, 0 UNRUN. The per-package type-check lanes, which that list does not derive, exit 0:pnpm --filter <pkg> run typecheckfor spec, objectql, driver-sql, driver-turso, rest and service-analytics on8e48947d, and for spec again onaea48520(round 3 moved prose in spec, the changeset and nothing else). The list with its exit codes is in the card's order folder (33698-gates-ran.txt).Round 2 (review#1 record 6894395884, seat amendments 6894412038 and 6894446721)
sql-driver-aggregation.ts)fix(driver-sql)4775f3f: the lifted predicate's bindings are typedreadonly Knex.Value[]where they are sliced from knex's owntoSQL(), andfilterBindingsisKnex.Value[]; no cast at the call sites.pnpm --filter <pkg> run typecheckwas red (exit 2, the same four errors) before and is green after, and exits 0 on all six touched packages (spec, objectql, driver-sql, driver-turso, rest, service-analytics; the test-typecheck legs included). Round 1's gate pass missed it becausedispatch-gates --commandsdoes not derive the per-package type-check lanes (its own output says a card owes them), and vitest does not type-check.addedunder-declaredMetadata-protocol: semantic: a storedhaving, measure filter or plugin-driverwherekeeps validating and now matches other rows under the NULL rule.Clause-②and the semver levels are unchanged.Skills-docs: follow-up #33868added.check:adr-0087-registrationon the new changeset: exit 0, no entry owed (the gate does not judge a changeset that declares no break), so nothing was added undermigrations/entries/semantic/..describe()(regenerated into the three driver reference pages) and the changeset now say text comparison in a measure filter is the backend collation's, as forwhere(ordering everywhere; equality and membership on a case- or accent-insensitive collation), naming SQLite and PostgreSQL 16 as measured and MySQL, SQL Server and Oracle as not. driver-sql's declaration comment points there. Observable change 5 gives thestage $eq 'won'example.filter.zod.tsshould state the column-side null ruleIDataDriver)content/docs/protocol/objectql/query-syntax.mdxlistedaggregations[].filteras[EXPERIMENTAL — not enforced], applied by neither SQL nor the in-memory fallback (false since #10576 in memory, and now in SQL too). The row is dropped from that "validate but not executed" table (amendment 7). The other six pages say nothing this PR makes false.Round 3 (review#2 delta record 6895214298, PASS with one should-fix)
Prose only: no code, type or binding change.
aggregate()contract still promised the in-memory answerspackages/spec/src/contracts/data-driver.ts: a driver that declares the bit answers each measure filter with the in-memory path's answers except whereDriverCapabilities.aggregationFilterstates a latitude (text compares by the backend collation, as inwhere)..describe()names no dialect (it says only that text compares by the backend collation), so it and the generated reference pages are unchanged.Comments brought up to date outside the code surface
Amendment 6892875666 added three files for comment edits only; the maintainer approved them on 2026-11-15. Each described the old routing ("the engine lowers filtered aggregations in memory for every driver"):
packages/spec/src/contracts/data-driver.ts(aggregate()TSDoc): a measure filter reachesaggregate()only on a driver that declaressupports.aggregationFilter; on every other driver it forces the in-memory path.packages/objectql/src/in-memory-aggregation.ts(header): the fallback is the lowering for every driver without the capability.packages/drivers/driver-turso/src/remote-transport.ts(refusePerAggregationFilterdocblock): no longer calls itself the twin of driver-sql's refusal; unreachable throughengine.aggregatebecauseTursoDriverreports the bit off in remote mode.The driver-memory and driver-mongodb refusal docblocks that say the engine lowers filtered aggregations in memory stay true for those drivers, which do not declare the bit; they are outside this card and untouched.
Clause-②: yes (widening: one optional DriverCapabilities bit)
Metadata-protocol: semantic
Skills-docs: follow-up #33868
Human Minimum
packages/specholds no runtime logic.pnpm lintpasses.main, one pull request.packages/spectouched: its generated artifacts are regenerated and committed.content/docs/references/,packages/*/CHANGELOG.mdorcontent/docs/releases/.Generated by Claude Code