diff --git a/.changeset/33698-measure-filter-pushdown.md b/.changeset/33698-measure-filter-pushdown.md new file mode 100644 index 00000000000..fb6c8126d7b --- /dev/null +++ b/.changeset/33698-measure-filter-pushdown.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +'@objectstack/driver-sql': patch +'@objectstack/driver-turso': patch +--- + +feat(spec, objectql, driver-sql, driver-turso): a per-measure aggregation filter runs in SQL on driver-sql, behind one declared driver capability (#33698) + +Clause-②: yes (widening: one optional DriverCapabilities bit) +Metadata-protocol: semantic + +**The capability.** `DriverCapabilities` (`@objectstack/spec/data`) gains one optional boolean, `aggregationFilter`: the driver's `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the answers the engine's in-memory aggregation gives, except that text compares by the database collation (see the last paragraph). Absence means `false`. A driver that declares nothing keeps exactly the path it had. + +**What runs where.** + +- `engine.aggregate` sends an aggregate whose measures carry a `filter` to `driver.aggregate` only when the driver declares `aggregationFilter: true` and has the method. Every other driver keeps the in-memory path: `find()` for the scoped rows, then the filter and the aggregate in the engine. A non-UTC timezone with a date bucket still forces the in-memory path, as before. +- `driver-sql` declares the bit and compiles each filtered measure as a conditional aggregate, the predicate from the same where compiler a `where` uses: `sum(CASE WHEN (pred) THEN amount END)`, the same for `avg`, `min`, `max`; `count(CASE WHEN (pred) THEN 1 END)` for a count of rows (no `ELSE 0`, which `count` would count); `count(CASE WHEN (pred) THEN field END)` for a count of a field; `count(distinct CASE WHEN (pred) THEN field END)` for `count_distinct`. A group the filter empties answers `0` for `sum` and the counts and `null` for `avg`, `min` and `max`, as before. The tenant wall and the read scope stay on the statement's own `where`, so a measure filter only narrows inside them. `SqliteWasmDriver` inherits the compile. +- `driver-turso` turns the bit off in remote mode, where the remote transport refuses the key; local and embedded-replica modes inherit driver-sql's compile. +- A direct `SqlDriver#aggregate` call with a measure filter now answers the filtered numbers instead of refusing `NOT_IMPLEMENTED` / 501. The 501 remains only for a compiled predicate the driver cannot isolate, which no tested dialect produces. + +**What answers differently in memory.** A measure filter, a `having` clause and the in-memory `where` that plugin drivers use all go through one engine evaluator. In that evaluator a column holding no value (SQL NULL) now fails `$gt`, `$gte`, `$lt`, `$lte` and `$between`, as SQL does and as the spec says (null is not ordered). Before, NULL counted as `0` for numbers, so "count where amount ≤ 0" also counted every row with no amount, and `$between` matched a NULL column for any bounds. A `having` on an empty group's `avg`, `min` or `max` (which is `null`) likewise no longer passes an ordering test. `$eq`, `$ne`, `$in`, `$nin`, `$exists`, `$null`, `$empty` and a `null` comparand answer as before. + +**A measure filter the `where` compiler refuses now refuses on driver-sql.** Because driver-sql compiles a measure filter with the same where compiler, a filter that compiler refuses answers the same `400 INVALID_FILTER` its `where` twin answers. The recorded case is a `{ $field }` comparison between columns of different classes on an object with no audit fields (`created_at` against an image field): before, the engine evaluated it in memory and answered `200`; on driver-sql it now answers `400 INVALID_FILTER`, as `where` always did. A driver without the bit still evaluates it in memory and answers `200`. + +**Declared latitude: text compares by the database collation.** On driver-sql a measure filter now answers what the `where` of the same datasource answers, so text comparison in it follows the database collation, where the in-memory path compares text exactly. Ordering a non-temporal text column (`$gt` / `$lt` / `$between` on text) follows the collation everywhere; on a case- or accent-insensitive collation, equality and membership do too, so `stage $eq 'won'` also counts `Won` rows, as `where` already does. Measured: SQLite and PostgreSQL 16 agree with the in-memory path on every operator with a `C.UTF-8` collation; 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. diff --git a/content/docs/protocol/objectql/query-syntax.mdx b/content/docs/protocol/objectql/query-syntax.mdx index 45e05ca391b..c83238522e3 100644 --- a/content/docs/protocol/objectql/query-syntax.mdx +++ b/content/docs/protocol/objectql/query-syntax.mdx @@ -90,7 +90,6 @@ on the `find()` path: | Member | Status | |:-------|:-------| -| `aggregations[].filter` | `[EXPERIMENTAL — not enforced]` — a SQL `FILTER (WHERE …)` affordance neither the SQL builders nor the in-memory fallback applies | | `search.fuzzy` / `boost` / `operator` / `minScore` / `language` / `highlight` | `[EXPERIMENTAL — not enforced]` — only `query` and `fields` drive the expansion | `top` is the exception that *is* honored — the engine normalises it to `limit`. diff --git a/content/docs/references/data/driver-nosql.mdx b/content/docs/references/data/driver-nosql.mdx index 690bb162cdb..81eb356ce1f 100644 --- a/content/docs/references/data/driver-nosql.mdx +++ b/content/docs/references/data/driver-nosql.mdx @@ -141,7 +141,7 @@ const result = AggregationPipelineSchema.parse(data); | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Driver instance name | | **type** | `'nosql'` | ✅ | Driver type must be "nosql" | -| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean }` | ✅ | Driver capability flags | +| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean; … }` | ✅ | Driver capability flags | | **connectionString** | `string` | optional | Database connection string (driver-specific format) | | **poolConfig** | `{ min?: number; max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number }` | optional | Connection pool configuration | | **databaseType** | `Enum<'mongodb' \| 'couchdb' \| 'dynamodb' \| 'cassandra' \| 'redis' \| 'elasticsearch' \| 'neo4j' \| 'orientdb'>` | ✅ | Specific NoSQL database type | @@ -165,6 +165,7 @@ const result = AggregationPipelineSchema.parse(data); | **autonumber** | `boolean` | optional | Driver natively generates persistent autonumber/sequence values | | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | +| **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver-sql.mdx b/content/docs/references/data/driver-sql.mdx index a9526848854..0e33d1f5635 100644 --- a/content/docs/references/data/driver-sql.mdx +++ b/content/docs/references/data/driver-sql.mdx @@ -62,7 +62,7 @@ const result = DataTypeMappingSchema.parse(data); | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Driver instance name | | **type** | `'sql'` | ✅ | Driver type must be "sql" | -| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean }` | ✅ | Driver capability flags | +| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean; … }` | ✅ | Driver capability flags | | **connectionString** | `string` | optional | Database connection string (driver-specific format) | | **poolConfig** | `{ min?: number; max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number }` | optional | Connection pool configuration | | **dialect** | `Enum<'postgresql' \| 'mysql' \| 'sqlite' \| 'mssql' \| 'oracle' \| 'mariadb'>` | ✅ | SQL database dialect | @@ -78,6 +78,7 @@ const result = DataTypeMappingSchema.parse(data); | **autonumber** | `boolean` | optional | Driver natively generates persistent autonumber/sequence values | | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | +| **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver.mdx b/content/docs/references/data/driver.mdx index 01136220429..707842e7435 100644 --- a/content/docs/references/data/driver.mdx +++ b/content/docs/references/data/driver.mdx @@ -32,6 +32,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **autonumber** | `boolean` | optional | Driver natively generates persistent autonumber/sequence values | | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | +| **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | @@ -75,7 +76,7 @@ const result = DriverCapabilitiesSchema.parse(data); | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Driver instance name | | **type** | `Enum<'sql' \| 'nosql' \| 'cache' \| 'search' \| 'graph' \| 'timeseries'>` | ✅ | Driver type category | -| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean }` | ✅ | Driver capability flags | +| **capabilities** | `{ queryDateGranularity?: Record; autonumber?: boolean; batchSchemaSync?: boolean; transactionsUnsupported?: boolean; … }` | ✅ | Driver capability flags | | **connectionString** | `string` | optional | Database connection string (driver-specific format) | | **poolConfig** | `{ min?: number; max?: number; idleTimeoutMillis?: number; connectionTimeoutMillis?: number }` | optional | Connection pool configuration | @@ -87,6 +88,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **autonumber** | `boolean` | optional | Driver natively generates persistent autonumber/sequence values | | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | +| **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/packages/drivers/driver-sql/src/sql-driver-11455-aggregate-fault-envelope.test.ts b/packages/drivers/driver-sql/src/sql-driver-11455-aggregate-fault-envelope.test.ts index 63098c8a74d..ce33d18b544 100644 --- a/packages/drivers/driver-sql/src/sql-driver-11455-aggregate-fault-envelope.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-11455-aggregate-fault-envelope.test.ts @@ -290,13 +290,16 @@ describe(`[#11455] driver-sql — aggregate() takes the backend-fault envelope ( expect(noField.code, 'count_distinct with no field').toBe('INVALID_QUERY'); expect(noField.status, 'count_distinct with no field').toBe(400); + // [#33698] A per-aggregation filter now COMPILES (the where compiler, + // inside a CASE WHEN), so the build-time refusal it can raise is that + // compiler's: an operator outside the vocabulary. const filtered = await caught(() => driver.aggregate(TABLE, { - aggregations: [{ function: 'count', alias: 'n', filter: { rank: 1 } }], + aggregations: [{ function: 'count', alias: 'n', filter: { rank: { $nope: 1 } } }], } as DriverQuery), ); - expect(filtered.code, 'a per-aggregation filter').toBe('NOT_IMPLEMENTED'); - expect(filtered.status, 'a per-aggregation filter').toBe(501); + expect(filtered.code, 'a per-aggregation filter the where compiler refuses').toBe('INVALID_FILTER'); + expect(filtered.status, 'a per-aggregation filter the where compiler refuses').toBe(400); }); }); } diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation-filter-refusal.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation-filter-refusal.test.ts deleted file mode 100644 index 8da022152e0..00000000000 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation-filter-refusal.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#10576] A per-aggregation `filter` (`AggregationNodeSchema.filter`, the - * contract half of #10413) reaching this compiler DIRECTLY is refused with a - * wire identity — never silently dropped. - * - * Before #10576 this driver's `aggregate()` never read `agg.filter`: the - * statement it built aggregated EVERY row and reported success, which is the - * #10413 defect ("won deals" counting every opportunity) at the driver seam. - * The engine now lowers filtered aggregations in memory and never pushes one - * down here — so the only caller that can arrive with the key is a direct - * one, and the honest answers are exactly two: compile a conditional - * aggregate, or refuse loudly. This backend refuses (NOT_IMPLEMENTED/501, the - * #5907 class for "declared by the spec, not compiled by this face"). - * - * Every case asserts `code` AND `status`, never merely "it threw" (#6144): a - * bare-throw assertion is green before and after the envelope exists. - */ - -import { describe, it, expect, beforeEach } from 'vitest'; -import { SqlDriver } from './index.js'; -import type { QueryAST } from '@objectstack/spec/data'; - -interface WireBearingError extends Error { - code?: string; - status?: number; -} - -describe('[#10576] SqlDriver refuses a per-aggregation filter it cannot compile', () => { - let driver: SqlDriver; - - beforeEach(async () => { - driver = new SqlDriver({ - client: 'better-sqlite3', - connection: { filename: ':memory:' }, - useNullAsDefault: true, - }); - await driver.initObjects([ - { - name: 'deal', - fields: { - id: { type: 'text', name: 'id' }, - stage: { type: 'text', name: 'stage' }, - amount: { type: 'number', name: 'amount' }, - }, - } as any, - ]); - await driver.create('deal', { id: '1', stage: 'closed_won', amount: 500 }); - await driver.create('deal', { id: '2', stage: 'open', amount: 900 }); - }); - - it('refuses NOT_IMPLEMENTED/501, naming the aggregation and the engine lowering', async () => { - const ast = { - object: 'deal', - aggregations: [ - { function: 'count', alias: 'won_count', filter: { stage: 'closed_won' } }, - ], - } as unknown as QueryAST; - - let thrown: WireBearingError | undefined; - try { - await driver.aggregate('deal', ast); - } catch (e) { - thrown = e as WireBearingError; - } - - expect(thrown).toBeDefined(); - expect(thrown!.code).toBe('NOT_IMPLEMENTED'); - expect(thrown!.status).toBe(501); - expect(thrown!.message).toContain( - 'Per-aggregation `filter` on "won_count" is not supported by this backend (driver-sql).', - ); - // The remedy is named: the engine's in-memory lowering serves this query. - expect(thrown!.message).toContain('`engine.aggregate` lowers filtered aggregations in memory'); - }); - - it('control: the same aggregation WITHOUT a filter still computes (only the refusal was added)', async () => { - const rows = await driver.aggregate('deal', { - object: 'deal', - aggregations: [{ function: 'count', alias: 'n' }], - } as unknown as QueryAST); - expect(rows).toEqual([{ n: 2 }]); - }); - - it('control: an EMPTY filter object is vacuous (the where/having convention) and computes', async () => { - const rows = await driver.aggregate('deal', { - object: 'deal', - aggregations: [{ function: 'sum', field: 'amount', alias: 'total', filter: {} }], - } as unknown as QueryAST); - expect(rows).toEqual([{ total: 1400 }]); - }); -}); diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation-filter.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation-filter.test.ts new file mode 100644 index 00000000000..c9bc8fda71d --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation-filter.test.ts @@ -0,0 +1,281 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33698] A per-aggregation `filter` (`AggregationNodeSchema.filter`, #10576) + * compiles to a conditional aggregate — `fn(CASE WHEN (pred) THEN arg END)`, + * and `count(CASE WHEN (pred) THEN 1 END)` for `count(*)` — with the predicate + * from the same where compiler (`applyFilters`) a `where` goes through. This + * driver advertises it as `supports.aggregationFilter`. + * + * Before this, the compiler refused the key (`NOT_IMPLEMENTED` / 501) and the + * engine answered every filtered measure in memory. The answer each function + * must give is the in-memory path's: the rows a `find()` with the filter as its + * `where` reads, aggregated in JS ({@link reference}), and a group the filter + * empties answering what that aggregate answers over nothing + * (`emptyGroupValueFor`: `sum` and both counts `0`, `avg` / `min` / `max` + * `null`). Every function is pinned against that reference AND a hand-written + * literal, so a broken reference cannot carry a broken compile with it. + * + * `count(*)` is the shape that has a wrong spelling that LOOKS right: + * `count(CASE WHEN … THEN 1 ELSE 0 END)` counts every row (`count` counts + * non-NULL, and `0` is not NULL). The `won` count over group `b`, whose rows + * are all `open`, is `0` only with no `ELSE`. + * + * Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`, + * `OS_TEST_MYSQL_URL`); SQLite always runs. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { SqlDriver } from './sql-driver.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; + +const TABLE = 'os33698_measure_filter'; + +interface Row { + id: string; + g: string; + stage?: string | null; + amount?: number | null; + qty?: number | null; + tag?: string | null; +} + +const ROWS: readonly Row[] = [ + { id: 'a1', g: 'a', stage: 'won', amount: 10, qty: 1, tag: 'x' }, + { id: 'a2', g: 'a', stage: 'won', amount: 30, qty: 2, tag: 'x' }, + { id: 'a3', g: 'a', stage: 'won', amount: null, qty: 3, tag: 'y' }, + { id: 'a4', g: 'a', stage: 'open', amount: 100, qty: 4, tag: 'z' }, + { id: 'b1', g: 'b', stage: 'open', amount: 5, qty: 5, tag: 'x' }, + { id: 'b2', g: 'b', stage: 'open', amount: 7, qty: null, tag: null }, + // A NULL stage: rejected by `stage = 'won'` (the measure filter is a WHERE, + // three-valued), and by the reference's `find()` alike. + { id: 'c1', g: 'c', stage: null, amount: 1, qty: 1, tag: 'x' }, + { id: 'c2', g: 'c', stage: 'won', amount: 2, qty: 2, tag: 'q' }, +]; + +type Aggregation = NonNullable[number]; +type Fn = Aggregation['function']; +const FUNCTIONS: readonly Fn[] = ['count', 'sum', 'avg', 'min', 'max', 'count_distinct']; +const FIELD_OF: Record = { + count: undefined, sum: 'amount', avg: 'amount', min: 'amount', max: 'amount', count_distinct: 'tag', +} as Record; + +/** What the in-memory path answers for `fn(field)` over `values` (the rows the filter keeps). */ +function reference(fn: Fn, rows: Array>, field: string | undefined): number | null { + if (fn === 'count') return field ? rows.filter((r) => r[field] != null).length : rows.length; + const values = rows.map((r) => r[field!]).filter((v) => v != null); + if (fn === 'count_distinct') return new Set(values.map((v) => String(v))).size; + const nums = values.map(Number); + if (fn === 'sum') return nums.reduce((a, b) => a + b, 0); + if (nums.length === 0) return null; + if (fn === 'avg') return nums.reduce((a, b) => a + b, 0) / nums.length; + if (fn === 'min') return Math.min(...nums); + return Math.max(...nums); +} + +/** Hand-written answers for `stage = 'won'`, per group. */ +const WON: Record> = { + a: { count: 3, sum: 40, avg: 20, min: 10, max: 30, count_distinct: 2 } as Record, + b: { count: 0, sum: 0, avg: null, min: null, max: null, count_distinct: 0 } as Record, + c: { count: 1, sum: 2, avg: 2, min: 2, max: 2, count_distinct: 1 } as Record, +}; + +function declareCell(cell: DialectCell): void { + describe(`[#33698] driver-sql — a measure filter compiles to a conditional aggregate (${cell.label})`, () => { + let driver: SqlDriver; + + const byGroup = async (query: DriverQuery) => { + const rows = (await driver.aggregate(TABLE, query)) as Array>; + return Object.fromEntries(rows.map((r) => [String(r.g), r])); + }; + const keptRows = async (g: string, filter: Record) => + (await driver.find(TABLE, { where: { $and: [{ g }, filter] } } as DriverQuery)) as Array>; + + beforeAll(async () => { + driver = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.initObjects([ + { + name: TABLE, + fields: { + g: { type: 'text' }, + stage: { type: 'text' }, + amount: { type: 'number' }, + qty: { type: 'number' }, + tag: { type: 'text' }, + }, + }, + ] as never); + for (const row of ROWS) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true }); + }); + + afterAll(async () => { + await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver?.disconnect(); + }); + + it('advertises the capability', () => { + expect(driver.supports.aggregationFilter).toBe(true); + }); + + for (const fn of FUNCTIONS) { + it(`${fn}: answers the in-memory path's number, per group, a group the filter empties included`, async () => { + const field = FIELD_OF[fn]; + const filter = { stage: 'won' }; + const got = await byGroup({ + groupBy: ['g'], + aggregations: [ + { function: fn, ...(field ? { field } : {}), alias: 'won', filter }, + // The unfiltered measure beside it: the filter narrows ONE measure, never the statement. + { function: fn, ...(field ? { field } : {}), alias: 'all' }, + ], + } as DriverQuery); + expect(Object.keys(got).sort()).toEqual(['a', 'b', 'c']); + for (const g of ['a', 'b', 'c']) { + expect(got[g].won, `${fn} won, group ${g} (hand-written)`).toEqual(WON[g][fn]); + expect(got[g].won, `${fn} won, group ${g} (find + aggregate)`).toEqual(reference(fn, await keptRows(g, filter), field)); + expect(got[g].all, `${fn} all, group ${g}`).toEqual(reference(fn, await keptRows(g, {}), field)); + } + }); + } + + it('count(field) skips the NULLs the filter keeps; count(*) does not', async () => { + const got = await byGroup({ + groupBy: ['g'], + aggregations: [ + { function: 'count', field: 'amount', alias: 'priced_won', filter: { stage: 'won' } }, + { function: 'count', alias: 'won', filter: { stage: 'won' } }, + ], + } as DriverQuery); + expect(got.a).toMatchObject({ priced_won: 2, won: 3 }); + }); + + it('binds in text order: a where, two measure filters with comparands, and the aggregand', async () => { + const got = await byGroup({ + where: { qty: { $ne: 3 } }, + groupBy: ['g'], + aggregations: [ + { function: 'sum', field: 'amount', alias: 'big', filter: { amount: { $gte: 10 }, stage: { $in: ['won', 'open'] } } }, + { function: 'max', field: 'qty', alias: 'small_qty', filter: { $or: [{ amount: { $lt: 6 } }, { tag: 'q' }] } }, + { function: 'count', alias: 'n' }, + ], + } as DriverQuery); + // a: a3 is outside the where; big = 10 + 30 + 100; no amount < 6 and no tag q. + expect(got.a).toMatchObject({ big: 140, small_qty: null, n: 3 }); + // b: `$ne` is null-safe, so b2 (qty NULL) stays in the where; neither + // amount reaches 10, and only b1's amount is below 6. + expect(got.b).toMatchObject({ big: 0, small_qty: 5, n: 2 }); + expect(got.c).toMatchObject({ big: 0, small_qty: 2, n: 2 }); + }); + + it('a NULL column fails an ordering comparison (null is not ordered)', async () => { + const got = await byGroup({ + groupBy: ['g'], + aggregations: [ + { function: 'count', alias: 'le0', filter: { amount: { $lte: 1000 } } }, + { function: 'count', alias: 'between', filter: { qty: { $between: [-1, 10] } } }, + { function: 'count', alias: 'none', filter: { amount: { $null: true } } }, + ], + } as DriverQuery); + expect(got.a).toMatchObject({ le0: 3, between: 4, none: 1 }); + expect(got.b).toMatchObject({ le0: 2, between: 1, none: 0 }); + }); + + it('without groupBy: one row, the filter still narrows only its measure', async () => { + const rows = (await driver.aggregate(TABLE, { + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won', filter: { stage: 'won' } }, + { function: 'sum', field: 'amount', alias: 'total' }, + ], + } as DriverQuery)) as Array>; + expect(rows).toEqual([{ won: 42, total: 155 }]); + }); + + it('control: an EMPTY filter object is vacuous (the where/having convention)', async () => { + const rows = (await driver.aggregate(TABLE, { + aggregations: [{ function: 'sum', field: 'amount', alias: 'total', filter: {} }], + } as DriverQuery)) as Array>; + expect(rows).toEqual([{ total: 155 }]); + }); + + it('a filter the where compiler refuses is refused the same way here (no second vocabulary)', async () => { + const asWhere = await driver.find(TABLE, { where: { amount: { $nope: 1 } } } as never).then(() => null, (e: any) => e); + const asMeasure = await driver + .aggregate(TABLE, { aggregations: [{ function: 'count', alias: 'n', filter: { amount: { $nope: 1 } } }] } as never) + .then(() => null, (e: any) => e); + expect(asWhere?.code).toBeDefined(); + expect({ code: asMeasure?.code, status: asMeasure?.status }).toEqual({ code: asWhere.code, status: asWhere.status }); + }); + }); +} + +for (const cell of DIALECT_CELLS) { + declareDialectCell(cell, 'aggregate measure filter (#33698)', declareCell); +} + +describe('[#33698] a measure filter under a tenant scope: the scope stays on the statement, the filter narrows inside it', () => { + const T = 'os33698_tenant_measure'; + let driver: SqlDriver; + const statements: string[] = []; + + beforeAll(async () => { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.initObjects([ + { name: T, fields: { organization_id: { type: 'string' }, stage: { type: 'string' }, amount: { type: 'number' } } }, + ] as never); + await driver.create(T, { id: 'a1', organization_id: 'org_a', stage: 'won', amount: 10 } as never); + await driver.create(T, { id: 'a2', organization_id: 'org_a', stage: 'open', amount: 20 } as never); + // Another organization's row the filter WOULD match. + await driver.create(T, { id: 'b1', organization_id: 'org_b', stage: 'won', amount: 1000 } as never); + (driver as unknown as { knex: { on(e: string, f: (d: { sql?: string }) => void): void } }).knex.on('query', (d) => { + if (typeof d?.sql === 'string' && d.sql.includes(T)) statements.push(d.sql); + }); + }); + + afterAll(async () => { + await driver?.disconnect(); + }); + + it('each organization counts only its own rows, and the statement carries the tenant predicate once, outside the CASE', async () => { + const query = { + where: { amount: { $gt: 0 } }, + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won', filter: { stage: 'won' } }, + { function: 'count', alias: 'n' }, + ], + } as DriverQuery; + expect(await driver.aggregate(T, query, { tenantId: 'org_a' } as never)).toEqual([{ won: 10, n: 2 }]); + expect(await driver.aggregate(T, query, { tenantId: 'org_b' } as never)).toEqual([{ won: 1000, n: 1 }]); + // No tenant (the admin / seed path): every row, as `find()` answers it. + expect(await driver.aggregate(T, query)).toEqual([{ won: 1010, n: 3 }]); + const scoped = statements.find((sql) => sql.includes('CASE WHEN') && sql.includes('organization_id'))!; + expect(scoped).toBeDefined(); + // The CASE holds the measure filter alone; the tenant predicate is in the WHERE. + const caseBody = scoped.slice(scoped.indexOf('CASE WHEN'), scoped.indexOf('END') + 3); + expect(caseBody).toContain('stage'); + expect(caseBody).not.toContain('organization_id'); + expect(scoped.slice(scoped.indexOf(' where '))).toContain('organization_id'); + }); +}); + +describe('[#33698] the lift guard: a predicate that cannot be isolated is refused, never guessed at', () => { + /** A where compiler that leaves a literal `?` the bindings do not pair with. */ + class LiteralPlaceholderDriver extends SqlDriver { + protected applyFilters(builder: any, filters: any, options?: any): void { + super.applyFilters(builder, filters, options); + builder.whereRaw(`stage <> '\\?'`); + } + } + + it('answers NOT_IMPLEMENTED / 501 naming the measure, before any statement runs', async () => { + const driver = new LiteralPlaceholderDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.initObjects([{ name: 'deal', fields: { stage: { type: 'text' }, amount: { type: 'number' } } }] as never); + const err = await driver + .aggregate('deal', { aggregations: [{ function: 'count', alias: 'won_count', filter: { stage: 'won' } }] } as never) + .then(() => null, (e: any) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'NOT_IMPLEMENTED', status: 501 }); + expect(String(err?.message)).toContain('Per-aggregation `filter` on "won_count" could not be compiled as a conditional aggregate'); + await driver.disconnect(); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index c96be01c452..d3499ccb51c 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -30,6 +30,7 @@ import { coreSqlDialectOf } from './sql-driver-oracle-dialect.js'; import { emptyGroupValueFor } from '@objectstack/spec/data'; +import type { Knex } from 'knex'; import type { DriverOptions } from '@objectstack/spec/data'; import type { DriverQuery } from '@objectstack/spec/contracts'; import { AGGREGATE_ACCUMULATION, AGGREGATE_ANSWER_KIND, aggregandOperandSql } from '@objectstack/core'; @@ -78,8 +79,19 @@ export interface AggregationHost { export class AggregationFacet { /** The body of `SqlDriver#aggregate`; the method's docblock there is its contract. */ static async aggregate(this: Pick, object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { + // [#33698] The per-measure `filter`s that carry a condition (`{}` is the + // vacuous filter, same convention as `where` / `having`): each compiles + // with the where compiler below, so each is primed and read like a `where`. + const measureFilters = (query.aggregations ?? []) + .map((agg) => agg.filter) + .filter((filter): filter is NonNullable => !!filter && Object.keys(filter).length > 0); // [#31395] SQL Server: which columns are GUIDs, before a text operator compiles. - if (this.isMssql) await this.primeMssqlGuidColumns(object, query.where); + if (this.isMssql) { + await this.primeMssqlGuidColumns( + object, + measureFilters.length > 0 ? { $and: [...(query.where ? [query.where] : []), ...measureFilters] } : query.where, + ); + } // [#31390] On Oracle a federated object's RAW(16) uuid columns are read from // the remote catalog before a comparand or a written value is bound. if (this.isOracle) await this.primeOracleRawUuidColumns(object); @@ -94,6 +106,46 @@ export class AggregationFacet { // named the field verbatim, so a mapped object's GROUP BY / aggregand / // `distinct` asked the remote table for a column it does not have. const columnOf = (field: string): string => this.remoteColumn(object, field, field); + // [#33698] A measure filter's predicate, compiled by the SAME where + // compiler a `where` goes through (`applyFilters`: the same comparand + // gates, refusals, coercion and column map), on a builder of the same + // table carrying the same tenant scope as the statement, then lifted out + // of `select * from t [where ] (where|and) `. It goes inside + // the aggregate as `CASE WHEN (pred) THEN … END`, so it only NARROWS the + // rows the statement already reads: the tenant wall and the read scope + // stay on the statement's own WHERE, never in a measure. Neither builder + // here is executed; each is scoped like every other builder of a read + // door, so the reference statement and the filtered one differ by exactly + // the predicate. `undefined` = the filter compiled to no condition at all + // (a vacuous tree), so the measure is the unfiltered aggregate — what the + // in-memory path answers for it. + // The lift is guarded rather than trusted: a statement that is not the + // reference plus one predicate, whose leading bindings are not the + // reference's, or whose predicate's `?` placeholders do not pair one to + // one with its own bindings (a `??` or an escaped `\?` would be re-read by + // `knex.raw`), is refused (NOT_IMPLEMENTED/501), never guessed at. + const compileMeasureFilter = (filter: NonNullable, alias: string): { sql: string; bindings: readonly Knex.Value[] } | undefined => { + const reference = this.getBuilder(object, options); + this.applyTenantScope(reference, object, options); + const filtered = this.getBuilder(object, options); + this.applyTenantScope(filtered, object, options); + this.applyFilters(filtered, filter, options); + const bare = reference.toSQL(); + const compiled = filtered.toSQL(); + if (compiled.sql === bare.sql && compiled.bindings.length === bare.bindings.length) return undefined; + const prefix = [`${bare.sql} where `, `${bare.sql} and `].find((p) => compiled.sql.startsWith(p)); + const sql = prefix === undefined ? '' : compiled.sql.slice(prefix.length); + const bindings = compiled.bindings.slice(bare.bindings.length); + if ( + prefix === undefined + || bare.bindings.some((b, i) => b !== compiled.bindings[i]) + || /\?\?|\\\?/.test(sql) + || (sql.match(/\?/g) ?? []).length !== bindings.length + ) { + throw unsupportedAggregationFilterError(alias, 'driver-sql'); + } + return { sql, bindings }; + }; this.applyTenantScope(builder, object, options); if (query.where) { @@ -201,15 +253,21 @@ export class AggregationFacet { const aggregates = query.aggregations; if (aggregates) { for (const agg of aggregates) { - // [#10576] A per-aggregation `filter` this compiler cannot express is - // refused before any statement is built — silently emitting the - // UNFILTERED aggregate is the #10413 defect. Unreachable through - // `engine.aggregate` (the engine lowers filtered aggregations in - // memory); this is the direct-caller guard. `{}` is the vacuous filter, - // same convention as `where` / `having`. - if (agg.filter && Object.keys(agg.filter).length > 0) { - throw unsupportedAggregationFilterError(agg.alias ?? agg.field ?? '(unaliased)', 'driver-sql'); - } + // [#33698] A per-aggregation `filter` (#10576) compiles to a + // conditional aggregate — `fn(CASE WHEN (pred) THEN arg END)` — which + // is SQL's `fn(arg) FILTER (WHERE pred)` on every dialect this driver + // targets: a row the predicate rejects contributes NULL, which every + // aggregate skips. `count(*)` becomes `count(CASE WHEN (pred) THEN 1 + // END)` — ⛔ never `ELSE 0`, which `count` would count. A group the + // filter empties answers what that aggregate answers over nothing + // (`emptyGroupValueFor`, folded below like any other measure): `sum` + // and both counts `0`, `avg`/`min`/`max` NULL — the in-memory path's + // answer. Silently emitting the UNFILTERED aggregate is the #10413 + // defect; a predicate that cannot be lifted is refused instead (see + // `compileMeasureFilter`). `{}` is the vacuous filter. + const measureFilter = agg.filter && Object.keys(agg.filter).length > 0 + ? compileMeasureFilter(agg.filter, agg.alias ?? agg.field ?? '(unaliased)') + : undefined; const funcName = agg.function; const lowering = this.mapAggregateFunc(funcName); // Spec: `field` is optional for COUNT (means COUNT(*)). @@ -249,14 +307,22 @@ export class AggregationFacet { const argExpr = dialect === 'mssql' ? mssqlAggregandOperandSql(funcName, aggregandClass, '??') : aggregandOperandSql(funcName, aggregandClass, coreSqlDialectOf(dialect), '??'); + // The operand, conditional when a measure filter compiled: the + // predicate's bindings precede the column's `??` in the text, so they + // precede it in the bindings too. + const operand = measureFilter ? `CASE WHEN (${measureFilter.sql}) THEN ${argExpr} END` : argExpr; + const filterBindings: Knex.Value[] = measureFilter ? [...measureFilter.bindings] : []; const rawFunc = lowering.distinct - ? `${lowering.sql}(distinct ${argExpr})` - : `${lowering.sql}(${argExpr})`; + ? `${lowering.sql}(distinct ${operand})` + : `${lowering.sql}(${operand})`; + const starFunc = measureFilter + ? `${lowering.sql}(CASE WHEN (${measureFilter.sql}) THEN 1 END)` + : `${lowering.sql}(*)`; if (agg.alias) { if (fieldExpr === '*') { - builder.select(this.knex.raw(`${lowering.sql}(*) as ${this.aliasIdentifierSql(agg.alias)}`)); + builder.select(this.knex.raw(`${starFunc} as ${this.aliasIdentifierSql(agg.alias)}`, filterBindings)); } else { - builder.select(this.knex.raw(`${rawFunc} as ${this.aliasIdentifierSql(agg.alias)}`, [columnOf(fieldExpr)])); + builder.select(this.knex.raw(`${rawFunc} as ${this.aliasIdentifierSql(agg.alias)}`, [...filterBindings, columnOf(fieldExpr)])); } // [#15546] What this aggregate answers over NOTHING, read from the // policy rather than restated: `sum` (and the two counts, which never @@ -303,9 +369,9 @@ export class AggregationFacet { } } else { if (fieldExpr === '*') { - builder.select(this.knex.raw(`${lowering.sql}(*)`)); + builder.select(this.knex.raw(starFunc, filterBindings)); } else { - builder.select(this.knex.raw(rawFunc, [columnOf(fieldExpr)])); + builder.select(this.knex.raw(rawFunc, [...filterBindings, columnOf(fieldExpr)])); } } } diff --git a/packages/drivers/driver-sql/src/sql-driver-top-level.ts b/packages/drivers/driver-sql/src/sql-driver-top-level.ts index 0b1e8363576..24d43d55fb7 100644 --- a/packages/drivers/driver-sql/src/sql-driver-top-level.ts +++ b/packages/drivers/driver-sql/src/sql-driver-top-level.ts @@ -1190,30 +1190,31 @@ function uncompilableAggregateFunctionError(func: string): Error { /** * [#10576] An aggregation entry carries a per-aggregation `filter` - * (`AggregationNodeSchema.filter`, the contract half of #10413) and this - * backend compiles no conditional-aggregate expression (SQL `FILTER (WHERE …)` - * / `CASE WHEN`) for it — so it is refused rather than silently aggregating - * the UNFILTERED rows, which is exactly the wrong-numbers defect #10413 - * measured ("won deals" counting every row). Same class and envelope as - * {@link uncompilableAggregateFunctionError}: the query is spelled correctly - * and the spec declares the key, so this is a capability gap in the backend - * (NOT_IMPLEMENTED/501), not a mistake in the query (400). - * - * Unreachable through `engine.aggregate`, deliberately: the engine routes any - * call whose aggregations carry a filter through its in-memory lowering - * (`applyInMemoryAggregation`), which honours the predicate on every driver. - * This guard is the direct-caller half of "no silent drop, anywhere" — the - * refusal names the remedy so a direct caller knows the engine path works. + * (`AggregationNodeSchema.filter`, the contract half of #10413) whose compiled + * predicate this driver could not isolate for a conditional aggregate + * (`CASE WHEN … THEN … END` inside the aggregate) — so it is refused rather + * than silently aggregating the UNFILTERED rows, which is exactly the + * wrong-numbers defect #10413 measured ("won deals" counting every row). Same + * class and envelope as {@link uncompilableAggregateFunctionError}: the query + * is spelled correctly and the spec declares the key, so this is a capability + * gap in the backend (NOT_IMPLEMENTED/501), not a mistake in the query (400). + * + * Since `aggregationFilter` (the `DriverCapabilities` bit) this driver compiles + * a measure filter with the SAME where compiler (`applyFilters`) a `where` + * goes through, then lifts the predicate out of `select * from t where …`. + * This refusal is the guard on that lift: a compiled statement that is not + * exactly that prefix plus one predicate, or whose `?` placeholders do not + * match its bindings one to one, cannot be embedded safely, and is refused + * instead of guessed at. No dialect this package tests reaches it. */ function unsupportedAggregationFilterError(alias: string, backend: string): Error { const err = new Error( - `Per-aggregation \`filter\` on "${alias}" is not supported by this backend (${backend}). ` + + `Per-aggregation \`filter\` on "${alias}" could not be compiled as a conditional aggregate by this backend (${backend}). ` + `The query is spelled correctly and @objectstack/spec AggregationNodeSchema declares the key — ` + - `this backend compiles no conditional-aggregate (SQL FILTER (WHERE …) / CASE WHEN) expression ` + - `for it, so it is refused rather than silently aggregating the UNFILTERED rows, which ` + - `is why it answers NOT_IMPLEMENTED/501 rather than a 400. \`engine.aggregate\` lowers filtered ` + - `aggregations in memory for every driver without native support — route the query through the ` + - `engine, or drop the \`filter\` key.`, + `this backend could not isolate the compiled predicate for a CASE WHEN inside the aggregate, ` + + `so it is refused rather than silently aggregating the UNFILTERED rows, which ` + + `is why it answers NOT_IMPLEMENTED/501 rather than a 400. Drop the \`filter\` key, or move the ` + + `condition into \`where\` when it applies to every measure.`, ) as Error & { code?: string; status?: number }; err.code = StandardErrorCode.enum.NOT_IMPLEMENTED; err.status = 501; diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index efe7026f9b4..d44cb71dc8f 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -383,6 +383,16 @@ export class SqlDriver implements IDataDriver { // mode) opts out of the `beginTransaction()` it inherits from this class. // Absence would mean the same thing and say nothing. transactionsUnsupported: false, + // [#33698] `aggregate()` compiles a per-measure `aggregations[].filter` + // as a conditional aggregate (`fn(CASE WHEN (pred) THEN arg END)`), the + // predicate from the same where compiler a `where` goes through, so the + // engine sends filtered measures here instead of reading every row into + // memory. A subclass whose transport cannot run the compile (TursoDriver's + // remote mode answers `aggregate()` with 501) spreads this and turns it off. + // Declared on every dialect: text comparison in the filter is then the + // collation's, as for this datasource's `where` (the latitude the bit's + // TSDoc in `data/driver.zod.ts` states, measured dialects named there). + aggregationFilter: true, }; } diff --git a/packages/drivers/driver-turso/src/remote-transport-aggregate-function-refusal.test.ts b/packages/drivers/driver-turso/src/remote-transport-aggregate-function-refusal.test.ts index d36fc7fa464..4bc1544351d 100644 --- a/packages/drivers/driver-turso/src/remote-transport-aggregate-function-refusal.test.ts +++ b/packages/drivers/driver-turso/src/remote-transport-aggregate-function-refusal.test.ts @@ -111,6 +111,7 @@ import { describe, it, expect, vi } from 'vitest'; import { SqlDriver } from '@objectstack/driver-sql'; import { RemoteTransport } from './remote-transport.js'; +import { TursoDriver } from './turso-driver.js'; import { AggregationFunction } from '@objectstack/spec/data'; import type { AggregationNode, QueryAST } from '@objectstack/spec/data'; @@ -540,14 +541,19 @@ describe('[#5907] RemoteTransport refuses an aggregate function it cannot compil /** * [#10576] The per-aggregation `filter` (`AggregationNodeSchema.filter`, the - * contract half of #10413) — a key BOTH faces of this driver decline to - * compile, so both must refuse it identically rather than silently aggregating - * the unfiltered rows (the #10413 defect at the driver seam). The engine never - * pushes a filtered aggregation down (it lowers in memory); these pins are the - * direct-caller guard, and the parity pin keeps #6203's lesson: one driver, - * two faces, one answer. + * contract half of #10413). The remote transport compiles no conditional + * aggregate, so it refuses the key rather than silently aggregating the + * unfiltered rows (the #10413 defect at the driver seam). + * + * [#33698] The two faces no longer answer alike, and the capability bit is + * what keeps #6203's lesson ("one driver, two faces, one answer") at the + * engine: the LOCAL face inherits SqlDriver's compile and + * `supports.aggregationFilter: true`; the REMOTE face reports + * `aggregationFilter: false`, so `engine.aggregate` never sends it a filtered + * measure — it reads the rows and aggregates in memory. The remote refusal + * stays the direct-caller guard. */ -describe('[#10576] per-aggregation filter is refused identically by both faces', () => { +describe('[#10576] per-aggregation filter: refused by the remote face, compiled by the local one', () => { const filteredAst = (): QueryAST => ({ object: 'deal', aggregations: [{ function: 'count', alias: 'won_count', filter: { stage: 'closed_won' } }], @@ -563,17 +569,24 @@ describe('[#10576] per-aggregation filter is refused identically by both faces', expect(err.message).toContain('`engine.aggregate` lowers filtered aggregations in memory'); }); - it('LOCAL (SqlDriver face) refuses the same class with the same first-sentence shape', async () => { - const remote = await refusalOfAst('count(filter)', filteredAst()); - const local = await localRefusalOf('count(filter)', filteredAst()); - expect(local.code).toBe('NOT_IMPLEMENTED'); - expect(local.status).toBe(501); - expect(local.message).toContain( - 'Per-aggregation `filter` on "won_count" is not supported by this backend (driver-sql).', - ); - // First sentence for first sentence: the two faces differ only in the - // backend name they print. - expect(remote.message.replace('(Turso remote transport)', '(driver-sql)')).toBe(local.message); + it('[#33698] LOCAL (SqlDriver face) compiles the filter, and each face declares what it does', async () => { + const d = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }); + await d.initObjects([ + { name: 'deal', fields: { id: { type: 'text', name: 'id' }, stage: { type: 'text', name: 'stage' } } } as any, + ]); + await d.create('deal', { id: 'd1', stage: 'closed_won' }); + await d.create('deal', { id: 'd2', stage: 'open' }); + await expect(d.aggregate('deal', filteredAst())).resolves.toEqual([{ won_count: 1 }]); + expect(d.supports.aggregationFilter).toBe(true); + + // The remote face refuses (above) and says so in its capabilities, so the + // engine keeps filtered measures off it. + const remote = new TursoDriver({ url: 'libsql://test-db.turso.io', authToken: 'test-token' }); + expect(remote.supports.aggregationFilter).toBe(false); }); it('control: an EMPTY filter object is vacuous and still compiles on the remote face', async () => { diff --git a/packages/drivers/driver-turso/src/remote-transport.ts b/packages/drivers/driver-turso/src/remote-transport.ts index 183833668cf..ab0b4084e5a 100644 --- a/packages/drivers/driver-turso/src/remote-transport.ts +++ b/packages/drivers/driver-turso/src/remote-transport.ts @@ -851,15 +851,15 @@ function refuseAggregateFunction(func: string): never { /** * [#10576] An aggregation entry carries a per-aggregation `filter` - * (`AggregationNodeSchema.filter`, the contract half of #10413) — the twin of - * `driver-sql`'s `unsupportedAggregationFilterError`, first sentence for first - * sentence, and the same NOT_IMPLEMENTED/501 class for the same reason: the - * spec declares the key, this transport compiles no conditional-aggregate - * expression for it, so it is a capability gap in the backend rather than a - * mistake in the query. Refused rather than silently aggregating the - * UNFILTERED rows — the #10413 defect. Unreachable through `engine.aggregate` - * (the engine lowers filtered aggregations in memory for every driver); this - * fires only for a caller that reached the transport directly. + * (`AggregationNodeSchema.filter`, the contract half of #10413). NOT_IMPLEMENTED/501 + * because the spec declares the key and this transport compiles no + * conditional-aggregate expression for it, so it is a capability gap in the + * backend rather than a mistake in the query. Refused rather than silently + * aggregating the UNFILTERED rows — the #10413 defect. Unreachable through + * `engine.aggregate`: `TursoDriver` reports `supports.aggregationFilter: false` + * in remote mode (#33698), so the engine lowers a filtered aggregation in + * memory there; the local face inherits driver-sql's compile. This fires only + * for a caller that reached the transport directly. */ function refusePerAggregationFilter(alias: string): never { const err = new Error( diff --git a/packages/drivers/driver-turso/src/turso-driver.test.ts b/packages/drivers/driver-turso/src/turso-driver.test.ts index 342f28031e8..e84b881508e 100644 --- a/packages/drivers/driver-turso/src/turso-driver.test.ts +++ b/packages/drivers/driver-turso/src/turso-driver.test.ts @@ -437,19 +437,47 @@ describe('TursoDriver Capabilities', () => { expect(typeof driver.syncSchemasBatch).toBe('function'); }); - it('claims batchSchemaSync, an emptied queryDateGranularity and no transactions in remote mode', () => { + it('claims batchSchemaSync, an emptied queryDateGranularity, no transactions and no measure filter in remote mode', () => { const remote = new TursoDriver({ url: 'libsql://test-db.turso.io', authToken: 'test-token' }); expect(remote.transportMode).toBe('remote'); // [#18063] `transactionsUnsupported` joins the remote-only diff. It is a // claim HERE and not in local mode for the reason this census exists: the // bit is per-INSTANCE, and a value equal to the base's is not a claim. + // [#33698] `aggregationFilter` likewise: off remotely, inherited locally. expect(ownCapabilityClaims(remote)).toEqual([ + 'aggregationFilter', 'batchSchemaSync', 'queryDateGranularity', 'transactionsUnsupported', ]); }); + it('[#33698] reports aggregationFilter off in remote mode, and inherits it on in local mode', async () => { + // Remote mode's `aggregate()` is `RemoteTransport.aggregate`, which refuses + // a per-aggregation filter (501): the bit must say so, so the engine keeps + // filtered measures on `find()` + in-memory there. + const remote = new TursoDriver({ url: 'libsql://test-db.turso.io', authToken: 'test-token' }); + expect(remote.supports.aggregationFilter).toBe(false); + // Local mode runs SqlDriver's own `aggregate()`, which compiles it. + const local = new TursoDriver({ url: ':memory:' }); + expect(local.supports.aggregationFilter).toBe(true); + await local.connect(); + try { + await local.initObjects([{ name: 'm33698', fields: { stage: { type: 'text' }, amount: { type: 'number' } } }] as never); + await local.create('m33698', { id: 'r1', stage: 'won', amount: 3 }); + await local.create('m33698', { id: 'r2', stage: 'open', amount: 5 }); + const rows = await local.aggregate('m33698', { + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won', filter: { stage: 'won' } }, + { function: 'count', alias: 'n' }, + ], + } as never); + expect(rows).toEqual([{ won: 3, n: 2 }]); + } finally { + await local.disconnect(); + } + }); + it('does NOT advertise native date-granularity in remote mode (avoids the "[object Object]" aggregate 500)', () => { // Remote mode delegates aggregate() to RemoteTransport, which accepts only // string group-by identifiers and has no date bucketing. If remote inherited diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index 22c770ffb78..b29211a3b18 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -1938,6 +1938,15 @@ export class TursoDriver extends SqlDriver { // Local and embedded-replica modes inherit `false` from SqlDriver: they // run knex against a real connection and honour `options.transaction`. transactionsUnsupported: this.transportMode === 'remote', + + // [#33698] The remote transport compiles no measure filter: remote mode + // delegates `aggregate()` to `RemoteTransport.aggregate`, which refuses a + // per-aggregation `filter` (NOT_IMPLEMENTED / 501, + // `refusePerAggregationFilter`). Inheriting SqlDriver's `true` here would + // send every filtered measure to that refusal. `false` keeps remote mode + // on the engine's `find()` + in-memory path, which answers it; local and + // embedded-replica modes run SqlDriver's own compile and inherit `true`. + ...(this.transportMode === 'remote' ? { aggregationFilter: false } : {}), }; } diff --git a/packages/objectql/src/engine-aggregate-filter-pushdown.test.ts b/packages/objectql/src/engine-aggregate-filter-pushdown.test.ts new file mode 100644 index 00000000000..eb5e2344205 --- /dev/null +++ b/packages/objectql/src/engine-aggregate-filter-pushdown.test.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33698] `engine.aggregate` sends an aggregate whose measures carry a + * `filter` to `driver.aggregate` only when the driver declares + * `supports.aggregationFilter: true` AND has the method. Every other driver + * keeps the path it had: `find()` for the rows, then `applyInMemoryAggregation`. + * + * The bit is read strictly (`=== true`): a driver that inherits `aggregate()` + * without compiling the key (its face refuses it 501), or whose transport + * cannot run the compile (TursoDriver's remote mode), sends nothing down. + * The other forks that force the rows path — a non-UTC reference timezone + * with date bucketing, a granularity the driver does not advertise — still + * win over the bit. + * + * Stand-in drivers, for the reason `engine-aggregate-rows-ast.test.ts` gives; + * the real compile and its answers are pinned in driver-sql + * (`sql-driver-aggregation-filter.test.ts`) and end to end, with the security + * layer, in rest (`aggregate-measure-filter-pushdown.test.ts`). + */ + +import { describe, it, expect } from 'vitest'; +import type { EngineAggregateOptions } from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; + +type Row = Record; + +const ROWS: Row[] = [ + { id: 'r1', stage: 'won', amount: 10, owner: 'u1', created_at: '2026-01-01T03:00:00.000Z' }, + { id: 'r2', stage: 'won', amount: 20, owner: 'u2', created_at: '2026-01-02T03:00:00.000Z' }, + { id: 'r3', stage: 'open', amount: 40, owner: 'u1', created_at: '2026-01-02T03:00:00.000Z' }, +]; + +interface Seen { findAsts: any[]; aggregateAsts: any[] } + +function standIn(seen: Seen, supports: Record, opts: { withAggregate?: boolean } = {}) { + const driver: Record = { + name: 'stand-in', + version: '0.0.0', + supports, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async execute() { return null; }, + async find(_object: string, query: any) { + seen.findAsts.push(structuredClone(query)); + return ROWS.map((r) => ({ ...r })); + }, + async findOne() { return ROWS[0]; }, + async create(_o: string, d: any) { return d; }, + async update(_o: string, _id: string, d: any) { return d; }, + async delete() { return true; }, + async count() { return ROWS.length; }, + async bulkCreate(_o: string, r: any[]) { return r; }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + }; + if (opts.withAggregate !== false) { + driver.aggregate = async (_object: string, ast: any) => { + seen.aggregateAsts.push(structuredClone(ast)); + return [{ pushed_down: true }]; + }; + } + return driver; +} + +async function engineOver(driver: any) { + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + (engine.registry as any).registerObject({ + name: 'deal', + fields: { + stage: { type: 'text' }, amount: { type: 'number' }, owner: { type: 'text' }, created_at: { type: 'datetime' }, + }, + }); + return engine; +} + +const FILTERED: EngineAggregateOptions = { + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won', filter: { stage: 'won' } }, + { function: 'count', alias: 'n' }, + ], +}; + +describe('[#33698] engine.aggregate pushes a filtered measure down only on the aggregationFilter bit', () => { + it('bit true + aggregate(): the driver gets the call, the filter on the measure, and find() is not asked', async () => { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, { aggregationFilter: true })); + const rows = await engine.aggregate('deal', FILTERED); + expect(rows).toEqual([{ pushed_down: true }]); + expect(seen.findAsts).toHaveLength(0); + expect(seen.aggregateAsts).toHaveLength(1); + expect(seen.aggregateAsts[0].aggregations).toEqual([ + { function: 'sum', field: 'amount', alias: 'won', filter: { stage: 'won' } }, + { function: 'count', alias: 'n' }, + ]); + }); + + it('the filter the driver gets is the RESOLVED one: a {current_user_id} token is the caller\'s id, not its own text', async () => { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, { aggregationFilter: true })); + await engine.aggregate('deal', { + aggregations: [{ function: 'count', alias: 'mine', filter: { owner: '{current_user_id}' } }], + context: { userId: 'u1', isSystem: true }, + } as EngineAggregateOptions); + expect(seen.aggregateAsts).toHaveLength(1); + expect(seen.aggregateAsts[0].aggregations[0].filter).toEqual({ owner: 'u1' }); + }); + + for (const [label, supports] of [ + ['no bit (a driver that declares nothing)', {}], + ['bit false (TursoDriver remote mode)', { aggregationFilter: false }], + ['a truthy non-boolean is not the bit', { aggregationFilter: 'yes' }], + ] as const) { + it(`${label}: find() + in-memory, the filtered number, aggregate() never called`, async () => { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, supports as Record)); + const rows = await engine.aggregate('deal', FILTERED); + expect(rows).toEqual([{ won: 30, n: 3 }]); + expect(seen.aggregateAsts).toHaveLength(0); + expect(seen.findAsts).toHaveLength(1); + expect(seen.findAsts[0]).not.toHaveProperty('aggregations'); + }); + } + + it('bit true but no aggregate() method: find() + in-memory (the bit is ANDed with presence)', async () => { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, { aggregationFilter: true }, { withAggregate: false })); + expect(await engine.aggregate('deal', FILTERED)).toEqual([{ won: 30, n: 3 }]); + expect(seen.findAsts).toHaveLength(1); + }); + + it('the other forks still win: a non-UTC timezone with a date bucket keeps the rows path', async () => { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, { aggregationFilter: true, queryDateGranularity: { day: true } })); + await engine.aggregate('deal', { + groupBy: [{ field: 'created_at', dateGranularity: 'day' }], + aggregations: [{ function: 'count', alias: 'won', filter: { stage: 'won' } }], + timezone: 'Asia/Shanghai', + } as EngineAggregateOptions); + expect(seen.aggregateAsts).toHaveLength(0); + expect(seen.findAsts).toHaveLength(1); + }); + + it('control: with no filtered measure, the bit changes nothing — pushdown as before', async () => { + for (const supports of [{}, { aggregationFilter: true }]) { + const seen: Seen = { findAsts: [], aggregateAsts: [] }; + const engine = await engineOver(standIn(seen, supports)); + await engine.aggregate('deal', { aggregations: [{ function: 'count', alias: 'n', filter: {} }] }); + expect(seen.aggregateAsts).toHaveLength(1); + expect(seen.findAsts).toHaveLength(0); + } + }); +}); diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 9e62210aa02..1a3d92ebd1a 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -1323,22 +1323,30 @@ export class DeleteAndAggregateFacet { const hasDateBucket = structuredItems.some((g) => !!g?.dateGranularity); const tzRequiresInMemory = !!tz && tz !== 'UTC' && hasDateBucket; // [#10576] Per-aggregation filters (`aggregations[].filter`, the - // contract half of #10413) force the in-memory path: no driver compiles - // a conditional aggregate (SQL `FILTER (WHERE …)` / `CASE WHEN`) from - // this key today, and pushing it down would aggregate the UNFILTERED - // rows — the silent drop #10413 measured. Same correct-first two-tier - // shape as date bucketing and HAVING above: a driver that grows native - // support must advertise a capability flag, at which point this fork - // becomes its fallback tier. The driver faces also refuse the key - // loudly (NOT_IMPLEMENTED/501) if reached directly, so neither seam can - // drop it in silence. `{}` counts as no filter (the vacuous-filter - // convention `where` / `having` already follow). + // contract half of #10413) go to `driver.aggregate` only on a driver + // that declares it compiles them: [#33698] `supports.aggregationFilter` + // (spec `DriverCapabilities`), read together with the method's presence + // above, because a driver can carry `aggregate()` without compiling the + // key (its face refuses it loudly, NOT_IMPLEMENTED/501) and a subclass + // can inherit a compiler its own transport refuses (TursoDriver's remote + // mode turns the bit off). Pushing a filtered measure to any other + // driver would aggregate the UNFILTERED rows — the silent drop #10413 + // measured — so every driver without the bit keeps the in-memory path + // below, unchanged. Same correct-first two-tier shape as date bucketing + // and HAVING: the in-memory evaluation is the fallback tier, and the + // pushed-down conditional aggregate answers what it answers. The filter + // the driver receives is the lowered one (`resolveThenLowerWhere` + // above), and the read scope and tenant wall stay on the statement's + // `where`, so the measure filter only narrows inside them. `{}` counts + // as no filter (the vacuous-filter convention `where` / `having` + // already follow). const hasAggregationFilter = (Array.isArray(ast.aggregations) ? ast.aggregations : []) .some((a) => { const f = (a as { filter?: unknown })?.filter; return f != null && typeof f === 'object' && Object.keys(f).length > 0; }); - if (typeof drv.aggregate === 'function' && allStructuredSupported && !tzRequiresInMemory && !hasAggregationFilter) { + const aggregationFilterNative = drv?.supports?.aggregationFilter === true; + if (typeof drv.aggregate === 'function' && allStructuredSupported && !tzRequiresInMemory && (!hasAggregationFilter || aggregationFilterNative)) { // HAVING is engine-owned (#4286): applied AFTER aggregation, over // the aggregated row's own columns (aggregation aliases + groupBy // projections), identically on both paths. No driver implements it @@ -1379,11 +1387,10 @@ export class DeleteAndAggregateFacet { // the author's own measure name, i.e. a plausible wrong number // rather than a refusal. // - // Both driver refusals document themselves as "unreachable through - // `engine.aggregate`, which lowers in memory for every driver" - // (`driver-memory`'s `refusePerAggregationFilter`, `driver-sql`'s - // `unsupportedAggregationFilterError`); this is the line that makes - // that true. `having` goes with them: `applyHaving` below is the + // The driver refusals of the key (`driver-memory`'s + // `refusePerAggregationFilter`, the Turso remote transport's) document + // themselves as unreachable through `engine.aggregate`; this line, and + // the `aggregationFilter` gate above, are what make that true. `having` goes with them: `applyHaving` below is the // authority on it and no driver evaluates it in `find`. const rowsAst: QueryAST = { ...ast }; delete rowsAst.groupBy; diff --git a/packages/objectql/src/having-filter-null-ordering.test.ts b/packages/objectql/src/having-filter-null-ordering.test.ts new file mode 100644 index 00000000000..487d2823a3c --- /dev/null +++ b/packages/objectql/src/having-filter-null-ordering.test.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33698] A SQL NULL column fails an ordering operator (`$gt`, `$gte`, `$lt`, + * `$lte`, `$between`) on every face of the walker, exactly as a column the row + * does not carry does. + * + * Measured before the fix (the walker against `driver-sql`'s where compiler, + * 119 filters on SQLite and PostgreSQL 16): every divergence on a NULL column + * was one of these five operators. The value-less exit read `undefined` only, + * so `null` reached the JS comparison and coerced to `0` — `null <= 0`, + * `null >= 0`, `null > -5` are `true` — and `$between` failed neither bound + * for any comparand type. "Count where amount ≤ 0" counted every row with no + * amount. The spec says null is not ordered (`filter.zod.ts`), and SQL agrees. + * + * Three faces share the walker, and each is pinned: the per-measure filter + * (`matchesAggregationFilter`), `having` over an aggregated row + * (`applyHaving` — an empty group's `avg` / `min` / `max` is `null`), and the + * in-memory `where` for plugin drivers (`matchesDriverWhere`). + * + * What does NOT move, pinned beside it: the equality family, `$in` / `$nin`, + * `$exists` / `$null` / `$empty`, and a NULL comparand. + */ + +import { describe, expect, it } from 'vitest'; +import type { FilterCondition } from '@objectstack/spec/data'; +import { applyHaving, matchesAggregationFilter, matchesDriverWhere } from './having-filter.js'; + +/** `amount` NULL on r4 and absent on r5; `name`, `closed` and `t` NULL on r4. */ +const ROWS: ReadonlyArray> = [ + { id: 'r1', amount: 5, name: 'Beta', closed: '2026-01-10', t: '09:00' }, + { id: 'r2', amount: 0, name: 'alpha', closed: '2026-01-20', t: '11:30' }, + { id: 'r3', amount: -2, name: 'Zed', closed: '2026-02-01', t: '18:00' }, + { id: 'r4', amount: null, name: null, closed: null, t: null }, + { id: 'r5' }, +]; + +type Face = (filter: FilterCondition) => string[]; + +const FACES: Record = { + 'measure filter (matchesAggregationFilter)': (filter) => + ROWS.filter((row) => matchesAggregationFilter(row, filter, 0)).map((r) => String(r.id)), + 'having (applyHaving)': (filter) => applyHaving([...ROWS], filter).map((r) => String(r.id)), + 'plugin-driver where (matchesDriverWhere)': (filter) => + ROWS.filter((row) => matchesDriverWhere(row, filter)).map((r) => String(r.id)), +}; + +/** The ordering cases: what SQL selects, NULL and absent rows never among them. */ +const ORDERING: ReadonlyArray<[FilterCondition, string[]]> = [ + [{ amount: { $lte: 0 } }, ['r2', 'r3']], + [{ amount: { $lt: 1 } }, ['r2', 'r3']], + [{ amount: { $gte: 0 } }, ['r1', 'r2']], + [{ amount: { $gt: -5 } }, ['r1', 'r2', 'r3']], + [{ amount: { $between: [-1, 1] } }, ['r2']], + [{ name: { $between: ['A', 'z'] } }, ['r1', 'r2', 'r3']], + [{ closed: { $between: ['2026-01-01', '2026-01-31'] } }, ['r1', 'r2']], + [{ t: { $between: ['06:00', '12:00'] } }, ['r1', 'r2']], + // Under a negation the NULL row comes back: `$not` inverts the walker's + // answer for the row, as the in-memory path always has. + [{ $not: { amount: { $lte: 0 } } } as FilterCondition, ['r1', 'r4', 'r5']], +]; + +/** Operators whose answer on a NULL column was already right, and stays. */ +const UNCHANGED: ReadonlyArray<[FilterCondition, string[]]> = [ + [{ amount: 0 }, ['r2']], + [{ amount: null } as FilterCondition, ['r4', 'r5']], + [{ amount: { $eq: 0 } }, ['r2']], + [{ amount: { $ne: 0 } }, ['r1', 'r3', 'r4', 'r5']], + [{ amount: { $in: [0, 5] } }, ['r1', 'r2']], + [{ amount: { $nin: [0] } }, ['r1', 'r3', 'r4', 'r5']], + [{ amount: { $null: true } }, ['r4', 'r5']], + [{ amount: { $exists: true } }, ['r1', 'r2', 'r3']], +]; + +for (const [face, ids] of Object.entries(FACES)) { + describe(`[#33698] ${face}: a NULL column is not ordered`, () => { + for (const [filter, expected] of ORDERING) { + it(`${JSON.stringify(filter)} keeps ${expected.join(', ')}`, () => { + expect(ids(filter)).toEqual(expected); + }); + } + for (const [filter, expected] of UNCHANGED) { + it(`unchanged: ${JSON.stringify(filter)} keeps ${expected.join(', ')}`, () => { + expect(ids(filter)).toEqual(expected); + }); + } + }); +} + +describe('[#33698] having over an empty group: avg / min / max are null and fail an ordering test', () => { + it('an empty group\'s avg is not "≤ 0"', () => { + const groups = [ + { region: 'north', avg_amount: -3, n: 2 }, + { region: 'south', avg_amount: null, n: 0 }, + ]; + expect(applyHaving(groups, { avg_amount: { $lte: 0 } }).map((g) => g.region)).toEqual(['north']); + expect(applyHaving(groups, { avg_amount: { $null: true } }).map((g) => g.region)).toEqual(['south']); + }); +}); + +describe('[#33698] a NULL comparand answers as it did (the column, not the comparand, is not ordered)', () => { + it('the walker\'s answers for a null comparand do not move', () => { + const row = { amount: null }; + // `null >= null` is the JS comparison the walker always ran for these. + expect(matchesDriverWhere(row, { amount: { $gte: null } } as FilterCondition)).toBe(true); + expect(matchesDriverWhere(row, { amount: { $gt: null } } as FilterCondition)).toBe(false); + expect(matchesDriverWhere(row, { amount: { $between: [null, 5] } } as FilterCondition)).toBe(true); + }); +}); diff --git a/packages/objectql/src/having-filter.ts b/packages/objectql/src/having-filter.ts index ea2bfe2604f..1c5a8682bf1 100644 --- a/packages/objectql/src/having-filter.ts +++ b/packages/objectql/src/having-filter.ts @@ -1085,6 +1085,36 @@ const NO_VALUE_ANSWERED_BY_OPERATOR: ReadonlySet = new Set([ '$empty', ]); +/** + * [#33698] The ordering operators — the ones a SQL NULL column fails, exactly as + * a column the row does not carry fails them. + * + * {@link NO_VALUE_ANSWERED_BY_OPERATOR}'s early exit read `value === undefined` + * only, so a column holding SQL NULL — which is how a row from `driver.find()` + * carries it, and how an empty group's `avg` / `min` / `max` arrives at + * `having` — fell through to the JS comparison, where `null` coerces to `0` + * (`null <= 0`, `null >= 0`, `null > -5` are all `true`) and `$between` fails + * neither bound test for any comparand type (`null < 'A'` and `null > 'z'` are + * both `false`). So `count where amount <= 0` counted every row with no amount. + * The spec says null is not ordered (the comparison-operator comparand text in + * `filter.zod.ts`), and `driver-sql`'s where compiler answers that: measured + * against it on SQLite and PostgreSQL 16, these five operators were the only + * ones where the two disagreed on a NULL column. + * + * Narrow on purpose: the equality family and `$in` / `$nin` already answer a + * NULL column correctly (strict equality), the operators in + * {@link NO_VALUE_ANSWERED_BY_OPERATOR} keep their own answers, and a NULL + * COMPARAND (`{ $gte: null }`, or a `$between` bound that is null) answers as + * before — it is the column's value, not the comparand, that is not ordered. + */ +const NULL_IS_NOT_ORDERED_OPERATORS: ReadonlySet = new Set(['$gt', '$gte', '$lt', '$lte', '$between']); + +/** [#33698] Does the comparand of an ordering operator itself hold a null (its answer is left as it was)? */ +function orderingComparandHoldsNull(op: string, target: unknown): boolean { + if (op !== '$between') return target === null || target === undefined; + return !Array.isArray(target) || target.some((bound) => bound === null || bound === undefined); +} + /** * [#20099] The aggregated row's column set — the namespace `having` filters and * a `{ $field }` reference in it resolves against — read off the QUERY, so it @@ -2433,6 +2463,8 @@ function checkCondition( throw invalidFilterError(jsonColumnOperatorRefusalText(field, op, false).message); } if (value === undefined && !NO_VALUE_ANSWERED_BY_OPERATOR.has(op)) return false; + // [#33698] …and a SQL NULL column fails an ordering operator the same way. + if (value === null && NULL_IS_NOT_ORDERED_OPERATORS.has(op) && !orderingComparandHoldsNull(op, target)) return false; // [#20099] A `{ $field }` reference as the whole comparand of a scalar // comparison is RESOLVED against this row. The arms below would compare the // reference OBJECT itself — `500 > { $field: 'cap' }` is false, and `$ne` diff --git a/packages/objectql/src/in-memory-aggregation.ts b/packages/objectql/src/in-memory-aggregation.ts index 62caf1e3d8e..26a92d553d8 100644 --- a/packages/objectql/src/in-memory-aggregation.ts +++ b/packages/objectql/src/in-memory-aggregation.ts @@ -45,10 +45,12 @@ // aggregate. This module used to claim it "logs a warning if one is // present" — it never did; the key was silently ignored on every path, // which is exactly the defect #10413 measured. NOTE this fallback is the -// documented LOWERING for every driver: `engine.aggregate` routes any call -// whose aggregations carry a filter through here (no driver advertises -// native conditional aggregation today), and the driver faces refuse -// NOT_IMPLEMENTED/501 if reached directly with one. +// documented LOWERING for every driver without the capability: +// `engine.aggregate` routes a call whose aggregations carry a filter +// through here unless the driver both declares `supports.aggregationFilter` +// and has `aggregate()` (#33698; driver-sql does), and a driver face that +// compiles no conditional aggregate refuses NOT_IMPLEMENTED/501 if reached +// directly with one. // // Date bucketing uses ISO-8601 conventions (weeks start Monday). // diff --git a/packages/rest/src/aggregate-measure-filter-pushdown.test.ts b/packages/rest/src/aggregate-measure-filter-pushdown.test.ts new file mode 100644 index 00000000000..e5ba63a4a5a --- /dev/null +++ b/packages/rest/src/aggregate-measure-filter-pushdown.test.ts @@ -0,0 +1,268 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33698] A per-measure `filter` pushed down to driver-sql as a conditional + * aggregate answers the SAME numbers as the in-memory path it replaces — under + * the REAL security layer (`SecurityPlugin` on a real `ObjectQL` over a real + * `SqlDriver`), through `POST /api/v1/data/:object/query`. + * + * Two engines over identical data, identically secured: one on `SqlDriver` + * (`supports.aggregationFilter: true`, so `engine.aggregate` sends the + * filtered measures to `driver.aggregate`), one on a `SqlDriver` that reports + * the bit off (so the engine reads the rows with `find()` and aggregates them + * in memory — the path every driver without the bit keeps). Each query is + * asked of both, as the same member, and must answer the same rows and numbers. + * + * The rows the security layer withholds are the ones a measure filter could + * leak through if it were evaluated outside the statement's scope, so each is + * a row the filter WOULD match: + * + * - **another organization's row** (the tenant wall, `isolated` posture), + * written below the engine, `stage: 'won'` with a large amount; + * - **a row outside the member's read scope** (row-level security + * `region != 'HIDDEN'`), `stage: 'won'` with a large amount. + * + * Neither reaches a number on either path: the wall and the scope are the + * statement's `where`, and the pushed-down measure filter only narrows inside + * it. A field the member cannot read is refused in a measure filter on both + * paths alike (`403 PERMISSION_DENIED`). + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { RestServer } from './rest-server'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECT = 'rest_measure_pushdown_ledger'; + +const SYS_CTX = { isSystem: true, userId: 'usr_system', tenantId: DEFAULT_ORGANIZATION_ID }; + +const MEMBER_SET = PermissionSetSchema.parse({ + name: 'member_default', + label: 'Member', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + fields: { [`${OBJECT}.secret`]: { readable: false, editable: false } }, + rowLevelSecurity: [{ name: 'ledger_scope', object: OBJECT, operation: 'all', using: "record.region != 'HIDDEN'" }], +}); + +const MEMBER_CTX = { + userId: 'usr_member', positions: [], permissions: [MEMBER_SET.name], posture: 'MEMBER', tenantId: DEFAULT_ORGANIZATION_ID, +}; + +const ROWS = [ + { id: 'd1', region: 'NA', stage: 'won', amount: 10, secret: 's1' }, + { id: 'd2', region: 'NA', stage: 'won', amount: 20, secret: 's2' }, + { id: 'd3', region: 'NA', stage: 'open', amount: null, secret: 's3' }, + { id: 'd4', region: 'EU', stage: 'open', amount: 40, secret: 's4' }, + // Outside the member's read scope, and matched by every `won` measure. + { id: 'd5', region: 'HIDDEN', stage: 'won', amount: 1000, secret: 's5' }, +]; +/** Another organization's row, written below the engine; matched by every `won` measure. */ +const OTHER_TENANT_ROW = { id: 'd6', region: 'NA', stage: 'won', amount: 50000, secret: 's6', organization_id: 'org_other' }; + +/** The same driver with the bit reported off: the engine's in-memory path. */ +class InMemoryMeasureSqlDriver extends SqlDriver { + override get supports() { + return { ...super.supports, aggregationFilter: false }; + } +} + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +interface Face { + engine: ObjectQL; + calls: { aggregate: number; find: number }; + query: (body: Record) => Promise<{ status: number; body: any }>; +} + +async function boot(driver: SqlDriver): Promise { + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.measure-filter-pushdown-33698', + name: 'Measure filter pushdown', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + { + name: OBJECT, + label: 'Ledger', + sharingModel: 'public_read_write', + fields: { + region: { name: 'region', type: 'text' }, + stage: { name: 'stage', type: 'text' }, + amount: { name: 'amount', type: 'number' }, + secret: { name: 'secret', type: 'text' }, + }, + }, + ], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + // The `isolated` posture: the Layer 0 organization wall is on, and the + // plugin hands the engine the same posture for the driver's tenant scope. + tenancy: { posture: 'isolated' }, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? [MEMBER_SET].find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => [MEMBER_SET], + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + (engine as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceSource')] = () => services.security; + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + await engine.insert(OBJECT, ROWS.map((r) => ({ ...r })), { context: SYS_CTX } as never); + await engine.getDriverForObject(OBJECT)!.create(OBJECT, { ...OTHER_TENANT_ROW }); + + const calls = { aggregate: 0, find: 0 }; + const d = driver as any; + const find = d.find.bind(d); + const aggregate = d.aggregate.bind(d); + d.find = (o: string, ...rest: unknown[]) => { if (o === OBJECT) calls.find += 1; return find(o, ...rest); }; + d.aggregate = (o: string, ...rest: unknown[]) => { if (o === OBJECT) calls.aggregate += 1; return aggregate(o, ...rest); }; + + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => MEMBER_CTX; + rest.registerRoutes(); + const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/query'); + expect(route).toBeDefined(); + const query = async (body: Record) => { + const res = makeRes(); + await route!.handler({ params: { object: OBJECT }, body: JSON.parse(JSON.stringify(body)), query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + return { engine, calls, query }; +} + +const rowsOf = (body: any): Array> => + (Array.isArray(body) ? body : body?.records ?? []) as Array>; +const byRegion = (body: any) => + Object.fromEntries(rowsOf(body).map((r) => [String(r.region), Object.fromEntries(Object.entries(r).filter(([k]) => k !== 'region'))])); + +const SQLITE = { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as const; + +describe('[#33698] a pushed-down measure filter answers the in-memory path\'s numbers, under the real security layer', () => { + let pushed: Face; + let inMemory: Face; + + beforeAll(async () => { + pushed = await boot(new SqlDriver({ ...SQLITE } as any)); + inMemory = await boot(new InMemoryMeasureSqlDriver({ ...SQLITE } as any)); + }); + + afterAll(async () => { + for (const face of [pushed, inMemory]) { + try { await face?.engine.destroy(); } catch { /* noop */ } + } + }); + + /** Ask both faces; assert the path each took; return the pushed face's body after asserting the two agree. */ + async function both(body: Record) { + const before = { pushed: { ...pushed.calls }, inMemory: { ...inMemory.calls } }; + const a = await pushed.query(body); + const b = await inMemory.query(body); + expect(a.status, JSON.stringify(a.body)).toBe(200); + expect(b.status, JSON.stringify(b.body)).toBe(200); + // The pushed face aggregated in the driver; the other read rows. + expect(pushed.calls.aggregate - before.pushed.aggregate, 'pushed: driver.aggregate').toBe(1); + expect(pushed.calls.find - before.pushed.find, 'pushed: no row read').toBe(0); + expect(inMemory.calls.aggregate - before.inMemory.aggregate, 'in-memory: no driver.aggregate').toBe(0); + expect(inMemory.calls.find - before.inMemory.find, 'in-memory: one row read').toBe(1); + expect(byRegion(a.body)).toEqual(byRegion(b.body)); + return a.body; + } + + it('grouped: every function, the same rows and numbers — no other-organization row, no out-of-scope row', async () => { + const body = await both({ + groupBy: ['region'], + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won_sum', filter: { stage: 'won' } }, + { function: 'count', alias: 'won_n', filter: { stage: 'won' } }, + { function: 'avg', field: 'amount', alias: 'won_avg', filter: { stage: 'won' } }, + { function: 'min', field: 'amount', alias: 'won_min', filter: { stage: 'won' } }, + { function: 'max', field: 'amount', alias: 'won_max', filter: { stage: 'won' } }, + { function: 'count_distinct', field: 'stage', alias: 'big_stages', filter: { amount: { $gte: 15 } } }, + { function: 'count', alias: 'n' }, + ], + }); + // Hand-written: d1 + d2 in NA; nothing won in EU; no HIDDEN group at all; + // and neither 1000 (out of scope) nor 50000 (other organization) anywhere. + expect(byRegion(body)).toEqual({ + NA: { won_sum: 30, won_n: 2, won_avg: 15, won_min: 10, won_max: 20, big_stages: 1, n: 3 }, + EU: { won_sum: 0, won_n: 0, won_avg: null, won_min: null, won_max: null, big_stages: 1, n: 1 }, + }); + }); + + it('ungrouped: the filtered total is the member\'s, not the table\'s', async () => { + const body = await both({ + aggregations: [ + { function: 'sum', field: 'amount', alias: 'won_sum', filter: { stage: 'won' } }, + { function: 'sum', field: 'amount', alias: 'total' }, + ], + }); + expect(rowsOf(body)).toEqual([{ won_sum: 30, total: 70 }]); + }); + + it('a NULL amount fails an ordering filter on both paths (null is not ordered)', async () => { + const body = await both({ + groupBy: ['region'], + aggregations: [{ function: 'count', alias: 'small', filter: { amount: { $lte: 15 } } }], + }); + // NA: d1 only — d3's NULL amount is not "≤ 15" on either path. + expect(byRegion(body)).toEqual({ NA: { small: 1 }, EU: { small: 0 } }); + }); + + it('a measure filter on a field the member cannot read is refused alike: 403, and no rows', async () => { + const body = { aggregations: [{ function: 'count', alias: 'n', filter: { secret: 's1' } }] }; + for (const face of [pushed, inMemory]) { + const before = { ...face.calls }; + const res = await face.query(body); + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(JSON.stringify(res.body)).toContain('PERMISSION_DENIED'); + expect(res.body?.records).toBeUndefined(); + expect(face.calls).toEqual(before); + } + }); + + it('CONTROL the withheld rows are there: a system read counts them', async () => { + const all = await pushed.engine.find(OBJECT, { context: { isSystem: true, userId: 'usr_system' } } as never); + expect((all as any[]).map((r) => r.id).sort()).toEqual(expect.arrayContaining(['d5'])); + const raw = await pushed.engine.getDriverForObject(OBJECT)!.find(OBJECT, { where: { id: 'd6' } } as never); + expect((raw as any[]).map((r) => r.organization_id)).toEqual(['org_other']); + }); +}); diff --git a/packages/rest/src/aggregation-filter-where-doors.test.ts b/packages/rest/src/aggregation-filter-where-doors.test.ts index c0b798b5f49..b75b9afb421 100644 --- a/packages/rest/src/aggregation-filter-where-doors.test.ts +++ b/packages/rest/src/aggregation-filter-where-doors.test.ts @@ -499,12 +499,28 @@ describe('[#21299] POST /data/:object/query — every position answers a { $fiel // a declared field); the engine-side positions keep the fail-open // direction for a side with no declaration and answer, as #21255 and // #21242 pin. Recorded so a change on either side is seen. + // + // [#33698] Re-recorded (seat ruling A, 6893557132): SqlDriver declares + // `supports.aggregationFilter`, so the per-aggregation filter is compiled + // by the same where compiler and answers its `where` twin's refusal. On a + // driver without the bit the engine still evaluates it in memory, and + // `applyInMemoryAggregation` still answers 6. const NO_AUDIT = { ...MEDIA, name: 'ledger_noaudit', systemFields: { audit: false } }; const { post, engine } = await boot(true, NO_AUDIT as any, MEDIA_ROWS); const filter = { created_at: { $ne: { $field: 'photo' } } }; expect(answerOf(await post(whereTwin(filter)), 'n')).toEqual({ status: 400, code: 'INVALID_FILTER' }); - expect(answerOf(await post(perAggregation(filter)), 'm')).toEqual({ status: 200, total: 6 }); + expect(answerOf(await post(perAggregation(filter)), 'm')).toEqual({ status: 400, code: 'INVALID_FILTER' }); const rows = (await engine.find(NO_AUDIT.name, {})) as any[]; expect(sum(applyInMemoryAggregation(rows, perAggregation(filter) as never, undefined, NO_AUDIT.fields), 'm')).toBe(6); }); + + it('[#33698] the same posture on a driver WITHOUT aggregationFilter: the engine evaluates the measure in memory and answers 200', async () => { + const NO_AUDIT = { ...MEDIA, name: 'ledger_noaudit_rows', systemFields: { audit: false } }; + const { post, engine } = await boot(true, NO_AUDIT as any, MEDIA_ROWS); + const driver: any = (engine as any).getDriverForObject(NO_AUDIT.name); + const supports = driver.supports; + Object.defineProperty(driver, 'supports', { configurable: true, get: () => ({ ...supports, aggregationFilter: false }) }); + const filter = { created_at: { $ne: { $field: 'photo' } } }; + expect(answerOf(await post(perAggregation(filter)), 'm')).toEqual({ status: 200, total: 6 }); + }); }); diff --git a/packages/rest/src/rest-aggregate-compensated-sum.test.ts b/packages/rest/src/rest-aggregate-compensated-sum.test.ts index 7a228ad0753..d4b92295600 100644 --- a/packages/rest/src/rest-aggregate-compensated-sum.test.ts +++ b/packages/rest/src/rest-aggregate-compensated-sum.test.ts @@ -77,10 +77,22 @@ function makeRes() { type Path = 'native' | 'rows'; +/** [#33698] SqlDriver with `aggregationFilter` reported off, so a filtered measure keeps the rows path. */ +class RowsPathSqlDriver extends SqlDriver { + override get supports() { + return { ...super.supports, aggregationFilter: false }; + } +} + /** * `native`: SqlDriver aggregates and the engine applies `having` to its * answer. `rows`: a filtered aggregation sends the engine to the rows path, * where it aggregates `find()` rows itself and then applies `having`. + * + * [#33698] SqlDriver now compiles a filtered measure itself + * (`supports.aggregationFilter`), so this file's driver reports that bit off + * ({@link RowsPathSqlDriver}): a filtered aggregation still routes to the rows + * path here, and the two paths stay the ones their names say. */ function grouped(path: Path, having?: Record): EngineAggregateOptions { const aggregations: NonNullable = [ @@ -100,7 +112,7 @@ describe('[#20489] sum / avg — one double on both SQLite paths, engine and RES let post: (body: Record) => Promise; beforeAll(async () => { - driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); + driver = new RowsPathSqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); engine = new ObjectQL(); engine.registerDriver(driver, true); await engine.init(); diff --git a/packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts b/packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts index 9aa387b39b4..fe70da7302e 100644 --- a/packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts +++ b/packages/services/service-analytics/src/__tests__/objectql-echo-date-bucket.test.ts @@ -254,15 +254,19 @@ for (const cell of CELLS) { }); } - // [#21647] One of the two cells where the engine buckets in memory and - // the echo still prints, because the hook answers and the expression, - // run here, answers the face's rows (the last assertion). The other is + // [#21647] A measure filter: the echo still prints, because the hook + // answers and the expression, run here, answers the face's rows (the + // last assertion). [#33698] SqlDriver now compiles the filtered measure + // itself (`supports.aggregationFilter`), so the driver groups it as a + // conditional aggregate; the in-memory face of this case is // `driver-turso`'s remote face, pinned by code path in // `objectql-echo-bucket-enumeration.test.ts`. - it('a measure filter, which the engine aggregates in memory: the echo keeps the driver expression and runs with its params', async () => { + it('a measure filter, which the driver compiles as a conditional aggregate: the echo keeps the driver expression and runs with its params', async () => { const query = { cube: FILTERED.name, measures: ['big_sum'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }], order: { closed_on: 'asc' } }; const { res, ran } = await ask(query); - expect(ran.some((sql) => /group by/i.test(sql)), 'the driver grouped nothing').toBe(false); + expect(ran, 'the driver grouped the filtered measure').toHaveLength(1); + expect(ran[0]).toMatch(/group by/i); + expect(ran[0]).toMatch(/sum\(CASE WHEN \(.+\) THEN .+ END\)/); expect(tuples(res.rows, ['closed_on', 'big_sum'])).toEqual([['2026-01', 20], ['2026-02', 1], ['2026-03', 10], ['2026-04', 5]]); const dryRun = await analytics.generateSql(query as any); expect(dryRun.sql).toBe(res.sql); diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 97ab2741f32..735139d7a16 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -183,6 +183,7 @@ "data/DocumentSchemaValidation:jsonSchema", "data/DocumentSchemaValidation:validationAction", "data/DocumentSchemaValidation:validationLevel", + "data/DriverCapabilities:aggregationFilter", "data/DriverCapabilities:arrayFields [RETIRED]", "data/DriverCapabilities:autonumber", "data/DriverCapabilities:batchSchemaSync", diff --git a/packages/spec/src/contracts/data-driver.ts b/packages/spec/src/contracts/data-driver.ts index 29e25ff5d94..5460afa9b48 100644 --- a/packages/spec/src/contracts/data-driver.ts +++ b/packages/spec/src/contracts/data-driver.ts @@ -227,9 +227,14 @@ export interface IDataDriver { * deliberately no `queryAggregations` bit — and otherwise falls back to * `find()` plus in-memory grouping. Two things the engine keeps for itself * even when it dispatches here: `having` is applied AFTER this call, over the - * returned rows (#4286); and `aggregations[].filter` (#10576) or a non-UTC - * `timezone` with date bucketing (ADR-0053) force the in-memory path, so a - * driver never sees either on this road today. + * returned rows (#4286); and a non-UTC `timezone` with date bucketing + * (ADR-0053) forces the in-memory path, so a driver never sees it on this + * road. `aggregations[].filter` (#10576) reaches this method only on a driver + * that declares `supports.aggregationFilter` (#33698, `DriverCapabilities`), + * which then evaluates each measure's filter with the in-memory path's + * answers except where `DriverCapabilities.aggregationFilter` states a + * latitude (text compares by the backend collation, as in `where`); on every + * other driver it forces the in-memory path. * * What a driver returns: one row per group, keyed by the `groupBy` field * names and by each aggregation's `alias`, with the per-function value diff --git a/packages/spec/src/data/driver.test.ts b/packages/spec/src/data/driver.test.ts index 082d46d57e4..fe9a8032e73 100644 --- a/packages/spec/src/data/driver.test.ts +++ b/packages/spec/src/data/driver.test.ts @@ -58,12 +58,16 @@ const RETIRED_BITS = [ * it. `transactions` was retired because no code read it; this one is read by * `driverSupportsTransactions`, which every transaction entrance in the engine * now calls. It is not that key revived — see the tombstone pin below. + * + * `aggregationFilter` is the fifth, under the same rule: `engine.aggregate` + * reads it (with method presence) to send a per-measure filter to the driver. */ const LIVE_BITS = [ 'queryDateGranularity', 'autonumber', 'batchSchemaSync', 'transactionsUnsupported', + 'aggregationFilter', ] as const; describe('DriverCapabilitiesSchema', () => { @@ -73,6 +77,7 @@ describe('DriverCapabilitiesSchema', () => { autonumber: true, batchSchemaSync: true, transactionsUnsupported: true, + aggregationFilter: true, }; expect(() => DriverCapabilitiesSchema.parse(capabilities)).not.toThrow(); @@ -88,9 +93,15 @@ describe('DriverCapabilitiesSchema', () => { // [#18063] Absence is the whole point for `transactionsUnsupported`: a // driver that declares nothing keeps the transactions it has today. expect(parsed).not.toHaveProperty('transactionsUnsupported'); + // Absent = the engine aggregates a filtered measure in memory, as before the bit. + expect(parsed).not.toHaveProperty('aggregationFilter'); + }); + + it('refuses a non-boolean aggregationFilter', () => { + expect(DriverCapabilitiesSchema.safeParse({ aggregationFilter: 'yes' }).success).toBe(false); }); - it('declares exactly the audited shape: 4 live bits + 31 tombstones', () => { + it('declares exactly the audited shape: 5 live bits + 31 tombstones', () => { const shape = (DriverCapabilitiesSchema as unknown as { shape: Record }).shape; const keys = Object.keys(shape).sort(); expect(keys).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); @@ -191,7 +202,7 @@ describe('tsc channel: the retired bits are unwritable in DriverCapabilities', ( const props = new Map(capsType.getProperties().map((p) => [p.getName(), p])); // Anti-vacuity: the walked shape is the audited key set — 31 tombstones - // plus the live bits (4 since #18063 added `transactionsUnsupported`). + // plus the live bits (5 since `aggregationFilter`). expect([...props.keys()].sort()).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); const decl = capsAlias!.declarations?.[0]; diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 75d8a27236e..7c7871df30a 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -156,6 +156,10 @@ const capRemoved = (key: string, mechanism: string) => * - `transactionsUnsupported` — opt-OUT of `beginTransaction()` for a * transport that inherits the method from a base class it cannot honour; * the engine ANDs its negation with method presence. + * - `aggregationFilter` — opt-IN for a per-measure `aggregations[].filter` on + * `aggregate()`: the engine ANDs it with method presence, because a driver + * can carry `aggregate()` without compiling that key (and a subclass can + * inherit a compiler its own transport refuses). * * Everything else IS the method: aggregate pushdown gates on * `typeof driver.aggregate === 'function'`, schema sync on @@ -275,6 +279,65 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ */ transactionsUnsupported: z.boolean().optional().describe('Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false)'), + /** + * This driver's `aggregate()` evaluates a per-measure filter + * (`aggregations[].filter`, `AggregationNodeSchema.filter`) itself. + * + * The promise: for every filter the engine admits at that position, the + * driver's `aggregate()` reads, for each measure, exactly the rows of each + * group its filter selects (SQL `FILTER (WHERE …)` semantics: sibling + * measures keep the whole group, and a filter that selects no row of a group + * answers that function's empty-group value, `emptyGroupValueFor`), with the + * same answer as the engine's in-memory aggregation over the rows `find()` + * returns for the same `where`. The read scope and the tenant wall are the + * statement's `where` and stay on the whole statement; the measure filter + * only narrows inside it. + * + * The latitude the promise inherits rather than closes: TEXT comparison in + * a measure filter is the backend collation's, as it is for a `where` on the + * same datasource. A measure filter answers what its `where` twin answers + * there, not what the in-memory path answers, which compares text exactly, + * by UTF-16 code units. Concretely: + * + * - ordering a NON-temporal text column (`$gt` / `$gte` / `$lt` / `$lte` / + * `$between` on text) follows the collation on every backend; it is not + * promised in any case (the comparison-operator text in `filter.zod.ts`); + * - equality and membership on text (`$eq`, implicit equality, `$ne`, `$in`, + * `$nin`) follow the collation too, so on a case- or accent-insensitive + * collation `stage $eq 'won'` also selects `Won`, exactly as the `where` + * of the same datasource does. + * + * Measured (in-memory path against driver-sql's where compiler, 119 + * filters): SQLite, and PostgreSQL 16 with a `C.UTF-8` database collation, + * answer alike on every operator; PostgreSQL 16 with an ICU `en-US` database + * collation differs only in text ordering. NOT measured: MySQL, SQL Server + * and Oracle. The MySQL and SQL Server default collations are + * case-insensitive, so equality and membership on text are expected to + * fold case there. Numbers, booleans, dates, datetimes and times answer + * alike wherever measured. + * + * What the engine does with it: `engine.aggregate` sends an aggregate whose + * measures carry a filter to `driver.aggregate` only when this bit is `true` + * AND the driver has the method; otherwise it asks `find()` for the rows and + * aggregates them in memory (`applyInMemoryAggregation`), which is always + * correct and loads the scoped row set into the process. A driver without the + * bit keeps that path, so declaring nothing changes nothing. + * + * Why a bit and not method presence: `aggregate()` predates this key, and a + * driver can implement it without compiling a measure filter (the faces that + * do not compile it refuse it loudly, NOT_IMPLEMENTED / 501, when reached + * directly). And a subclass can inherit a compiler its own transport cannot + * run: the libSQL remote transport answers 501 for the key, so + * `TursoDriver` turns the bit off in remote mode. + * + * ⛔ Not a way to say "this filter, today". It describes the driver, is read + * at dispatch time, and a driver that could compile only some filters should + * not declare it. + * + * Optional; absence means `false`, like `batchSchemaSync`. + */ + aggregationFilter: z.boolean().optional().describe('`aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine\'s in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory)'), + // ============================================================================ // Retired capability bits (#4634, ADR-0049 enforce-or-remove) — 17.0.0 // ============================================================================