Repository navigation
Commit 0ac112f
feat(spec, objectql, driver-sql, driver-turso): run a per-measure aggregation filter in SQL behind one driver capability bit (#33854)
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.
- **Spec (widening).** `DriverCapabilitiesSchema` gains one optional
boolean, `aggregationFilter`: the driver's `aggregate()` evaluates a
per-measure filter itself, with the engine's in-memory answers. Absence
means `false`. 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 the
`where` of 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.json` and the three driver reference pages
under `content/docs/references/data/`.
- **Engine** (`engine-delete-and-aggregate.ts`). A filtered aggregate
goes to `driver.aggregate` only when `driver.supports.aggregationFilter
=== true` and the driver has the method. Every other driver keeps
`find()` plus `applyInMemoryAggregation`, unchanged. The other forks
that force the rows path (a non-UTC timezone with a date bucket, an
unadvertised granularity) still win.
- **driver-sql.** Declares the bit. Each filtered measure's predicate
comes from the same where compiler a `where` uses (`applyFilters` on a
builder of the same table), lifted out of `select * from t where …` and
placed in `CASE 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 refused `NOT_IMPLEMENTED` /
501 instead of guessed at (no tested dialect reaches it; a test forces
it). Both the reference builder and the filtered builder go through
`applyTenantScope`, 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 own `WHERE`, outside
every `CASE`; a test pins that with two organizations. SQL Server's GUID
priming now also reads the measure filters. `SqliteWasmDriver` inherits
the compile (probed: filtered sum and count answer correctly).
- **driver-turso.** Remote mode reports `aggregationFilter: false`, the
way it empties `queryDateGranularity`, because
`RemoteTransport.aggregate` refuses the key (501). Local mode inherits
`true` and runs SqlDriver's compile; a test measures it answering a
filtered sum.
- **objectql walker (option C of the H3 decision, its own commit).** A
SQL NULL column now fails `$gt`, `$gte`, `$lt`, `$lte` and `$between` in
the in-memory evaluator, as an absent column already did. See
*Observable change* below.
### The SQL shape, per function (H4)
`pred` is the where compiler's predicate for that measure's filter; the
statement's own `WHERE` (tenant wall, read scope, the caller's `where`)
is untouched.
| function | without a filter | with a filter |
|:--|:--|:--|
| `sum` | `sum(col)` | `sum(CASE WHEN (pred) THEN col END)` |
| `avg` | `avg(col)` | `avg(CASE WHEN (pred) THEN col END)` |
| `min` | `min(col)` | `min(CASE WHEN (pred) THEN col END)` |
| `max` | `max(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_distinct` | `count(distinct col)` | `count(distinct CASE WHEN
(pred) THEN col END)` |
`col` keeps the existing aggregand wrapping (PG boolean cast, double
accumulation for `sum` / `avg`). No `ELSE` anywhere: a row the filter
rejects contributes NULL, which every aggregate skips, so `count` never
counts it (`ELSE 0` would). A group the filter empties answers the
existing empty-group values (`sum` and the counts `0`, `avg` / `min` /
`max` `null`). `CASE WHEN` is used on every dialect, PostgreSQL
included, so there is one shape to test.
## Observable change
1. **Faster filtered measures on driver-sql**, same numbers (bench
below).
2. **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-memory `where` that plugin drivers use
(`matchesDriverWhere`). Before: "count where amount ≤ 0" also counted
every row with no amount; `$gte 0` / `$gt -5` / `$lt 1` likewise;
`$between` matched a NULL column for any bounds (numbers, text, dates,
times); a `having` like `avg_amount ≤ 0` kept an empty group (whose
`avg` is `null`). After: none of those match, as SQL and the spec ("null
is not ordered") say. Unchanged: `$eq`, `$ne`, `$in`, `$nin`, `$exists`,
`$null`, `$empty`, and a `null` comparand.
3. **A direct `SqlDriver#aggregate` call** with a measure filter answers
the filtered numbers instead of refusing 501.
4. **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 its
`where` twin answers. The recorded case is in
`aggregation-filter-where-doors.test.ts`: a `{ $field }` comparison of
`created_at` with an image field on an object with no audit fields.
`where` refused it `400 INVALID_FILTER` before and still does; the
measure filter used to be evaluated in memory and answer `200` (total
6), and on driver-sql it now answers `400 INVALID_FILTER`. On a driver
without the bit it still answers `200`, and a new case pins that. The
changeset says so.
5. **Text in a measure filter compares by the database collation on
driver-sql**, as the `where` of the same datasource already does. The
in-memory path compares text exactly. On a case-insensitive collation,
`stage $eq 'won'` now also counts `Won` rows, as `where: { stage: 'won'
}` already selects them; ordering a non-temporal text column follows the
collation everywhere. Measured: SQLite, and PostgreSQL 16 with a
`C.UTF-8` collation, agree with the in-memory path on every operator;
PostgreSQL 16 with an ICU `en-US` collation 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 own
`where`.
### 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
`having` and plugin-driver `where`) and item 4 (a measure filter now
shares its `where` twin's refusal on driver-sql, so the same request
answers `400` on driver-sql and `200` on a driver without the bit). Item
4 makes the measure filter agree with the `where` position the spec
pairs it with; the remaining split is between drivers, not between
positions on one driver.
## Why
#33698: a measure filter forced `engine.aggregate` onto `find()` 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 as `needs_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 for `where`. 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 against `find(where = filter)` aggregated in
JS; `count(field)` vs `count(*)`; binding order with a `where` and 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 in `WHERE`, outside the `CASE`); 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 to `driver.aggregate` with the resolved filter; no bit,
`false`, a truthy non-boolean, or no method go to `find()` 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-group
`having`, and the null comparand.
- `packages/rest/src/aggregate-measure-filter-pushdown.test.ts`:
security parity through `POST /api/v1/data/:object/query` with the real
`SecurityPlugin`, `isolated` tenancy, row-level security and an
unreadable field. Two engines over identical data: SqlDriver (pushed
down, asserted `driver.aggregate` once and no `find`) and SqlDriver with
the bit off (asserted `find` once). Same rows and numbers for every
function; another organization's `won` row and an out-of-scope `won` row
counted by neither; a measure filter on the unreadable field is `403
PERMISSION_DENIED` on 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.
- Existing tests that described the old routing (each approved by the
maintainer on 2026-11-15, amendments 6893557132 and 6893580970; no
expected number changes):
- `packages/rest/src/rest-aggregate-compensated-sum.test.ts` compares
the native and rows paths and forced the rows path with a filtered
measure. Its driver now reports `aggregationFilter: 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 grouped `sum(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):
- driver-sql: the measure's operand put back to the bare aggregand (no
`CASE`, no filter bindings, `count(*)`):
`sql-driver-aggregation-filter.test.ts` **10 failed / 4 passed**;
restored 14 passed (run before the tenant-wall cases were added).
- driver-sql: `count(CASE WHEN … THEN 1 ELSE 0 END)`: **3 failed**
(count, count(field) vs count(*), NULL ordering); restored.
- engine: the gate put back to `!hasAggregationFilter`:
`engine-aggregate-filter-pushdown.test.ts` **2 failed / 6 passed**; the
bit ignored (always push): **3 failed / 5 passed**; restored 8 passed.
- walker: the NULL exit disabled: `having-filter-null-ordering.test.ts`
**28 failed / 25 passed** (nine ordering cases on three faces, plus the
empty-group `having`); restored 53 passed.
Suites on the final head (rebased on `main` 1e65a38): 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 with `driver-sql`'s built `supports`
patched to `aggregationFilter: false` for the run (exactly the path
`main` takes 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.
| scale | dialect | before p50 / p95 ms | after p50 / p95 ms |
|:--|:--|--:|--:|
| 100k | SQLite | 300.2 / 351.6 | 48.3 / 62.3 |
| 100k | PostgreSQL 16 | 608.2 / 685.2 | 34.5 / 37.4 |
| 1M | SQLite | 5378.2 / 5898.1 | 431.1 / 501.7 |
| 1M | PostgreSQL 16 | 6357.8 / 7106.9 | 175.8 / 191.8 |
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):
```sql
select `status`, sum(CASE WHEN (`quantity` >= ?) THEN `quantity` END) as `big`, count(*) as `n`
from `bench_line_item` where `opportunity` in (select `id` from `bench_opportunity` where `account` in (select `id` from `bench_account`)) group by `status`
```
Nothing under `packages/qa/dogfood/bench/sql-perf/` is changed: the
bench writes its results under its work directory, not the repo. Its
scenario `note` ("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 family `node
scripts/pm/dispatch-gates.mjs --commands` derives for this tree was run,
each exit code recorded before any pipe: **124 run, 124 exit 0**.
`--ran` reconciliation: 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 typecheck` for spec, objectql, driver-sql,
driver-turso, rest and service-analytics on `8e48947d`, and for spec
again on `aea48520` (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)
| finding | what changed |
|:--|:--|
| **M1** — the head did not type-check (TS2769 ×4 in
`sql-driver-aggregation.ts`) | `fix(driver-sql)` 4775f3f: the lifted
predicate's bindings are typed `readonly Knex.Value[]` where they are
sliced from knex's own `toSQL()`, and `filterBindings` is
`Knex.Value[]`; no cast at the call sites. `pnpm --filter <pkg> run
typecheck` was 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 because `dispatch-gates
--commands` does not derive the per-package type-check lanes (its own
output says a card owes them), and vitest does not type-check. |
| **S1** — the declared kind `added` under-declared | The changeset and
this body now say `Metadata-protocol: semantic`: a stored `having`,
measure filter or plugin-driver `where` keeps validating and now matches
other rows under the NULL rule. `Clause-②` and the semver levels are
unchanged. `Skills-docs: follow-up #33868` added.
`check:adr-0087-registration` on the new changeset: exit 0, no entry
owed (the gate does not judge a changeset that declares no break), so
nothing was added under `migrations/entries/semantic/`. |
| **S2** — the bit's TSDoc promised more than was measured | Option (b):
the bit stays on every dialect. Its TSDoc, its `.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 for `where` (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 the `stage
$eq 'won'` example. |
| **N1** — `filter.zod.ts` should state the column-side null rule |
Filed as #33869. |
| **N2** — bench scenario note | Already stated under *Bench*. |
| Docs drift (the bot's seven pages via `IDataDriver`) | One sentence
was false: `content/docs/protocol/objectql/query-syntax.mdx` listed
`aggregations[].filter` as `[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.
| finding | what changed |
|:--|:--|
| **S3** — the `aggregate()` contract still promised the in-memory
answers | `packages/spec/src/contracts/data-driver.ts`: a driver that
declares the bit answers each measure filter with the in-memory path's
answers except where `DriverCapabilities.aggregationFilter` states a
latitude (text compares by the backend collation, as in `where`). |
| **N3** — Oracle unnamed | The bit's TSDoc and the changeset name
Oracle beside MySQL and SQL Server as not measured. The `.describe()`
names no dialect (it says only that text compares by the backend
collation), so it and the generated reference pages are unchanged. |
| **N4** — "is exempt" | The S1 row above now says the gate does not
judge a changeset that declares no break. |
### 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 reaches `aggregate()` only on a driver that declares
`supports.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`
(`refusePerAggregationFilter` docblock): no longer calls itself the twin
of driver-sql's refusal; unreachable through `engine.aggregate` because
`TursoDriver` reports 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
- [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic.
- [x] 2. Every name I added uses the casing for its kind.
- [x] 3. No formatter ran; `pnpm lint` passes.
- [x] 4. One issue, one branch off an up-to-date `main`, one pull
request.
- [x] 5. A change that publishes carries a changeset, and both
declaration lines are filled in here and in the changeset.
- [x] 6. `packages/spec` touched: its generated artifacts are
regenerated and committed.
- [x] 7. No hand edits to `content/docs/references/`,
`packages/*/CHANGELOG.md` or `content/docs/releases/`.
- [x] 8. Title, body and comments are in English.
- [x] The *Before Submitting* list in CONTRIBUTING.md is done.
---
_Generated by [Claude
Code](https://claude.ai/code/session_01FEkQ5nSNBMzF8jj9quUkjf)_
<!-- signed: domain:spec#4 · os-project-manager ·
session_01FEkQ5nSNBMzF8jj9quUkjf -->
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent 9404cb1 commit 0ac112f
28 files changed
Lines changed: 1226 additions & 196 deletions
File tree
- .changeset
- content/docs
- protocol/objectql
- references/data
- packages
- drivers
- driver-sql/src
- driver-turso/src
- objectql/src
- rest/src
- services/service-analytics/src/__tests__
- spec
- authorable-surface
- src
- contracts
- data
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
90 | 90 | | |
91 | 91 | | |
92 | 92 | | |
93 | | - | |
94 | 93 | | |
95 | 94 | | |
96 | 95 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
141 | 141 | | |
142 | 142 | | |
143 | 143 | | |
144 | | - | |
| 144 | + | |
145 | 145 | | |
146 | 146 | | |
147 | 147 | | |
| |||
165 | 165 | | |
166 | 166 | | |
167 | 167 | | |
| 168 | + | |
168 | 169 | | |
169 | 170 | | |
170 | 171 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
62 | 62 | | |
63 | 63 | | |
64 | 64 | | |
65 | | - | |
| 65 | + | |
66 | 66 | | |
67 | 67 | | |
68 | 68 | | |
| |||
78 | 78 | | |
79 | 79 | | |
80 | 80 | | |
| 81 | + | |
81 | 82 | | |
82 | 83 | | |
83 | 84 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
32 | 32 | | |
33 | 33 | | |
34 | 34 | | |
| 35 | + | |
35 | 36 | | |
36 | 37 | | |
37 | 38 | | |
| |||
75 | 76 | | |
76 | 77 | | |
77 | 78 | | |
78 | | - | |
| 79 | + | |
79 | 80 | | |
80 | 81 | | |
81 | 82 | | |
| |||
87 | 88 | | |
88 | 89 | | |
89 | 90 | | |
| 91 | + | |
90 | 92 | | |
91 | 93 | | |
92 | 94 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
290 | 290 | | |
291 | 291 | | |
292 | 292 | | |
| 293 | + | |
| 294 | + | |
| 295 | + | |
293 | 296 | | |
294 | 297 | | |
295 | | - | |
| 298 | + | |
296 | 299 | | |
297 | 300 | | |
298 | | - | |
299 | | - | |
| 301 | + | |
| 302 | + | |
300 | 303 | | |
301 | 304 | | |
302 | 305 | | |
| |||
This file was deleted.
0 commit comments