From 43c9871aecafa1212654d8474b3a9b43d489226b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:24:42 +0000 Subject: [PATCH 01/12] wip(objectql,driver-sql,spec): zoned date bucketing pushdown (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .../driver-sql/src/sql-driver-aggregation.ts | 73 +++++++++++++- .../driver-sql/src/sql-driver-date-bucket.ts | 36 +++++-- .../driver-sql/src/sql-driver-top-level.ts | 42 +++++++- packages/drivers/driver-sql/src/sql-driver.ts | 29 +++++- .../src/engine-aggregate-timezone.test.ts | 98 ++++++++++++++++++- .../src/engine-delete-and-aggregate.ts | 68 ++++++++++--- packages/spec/src/contracts/data-driver.ts | 33 ++++++- packages/spec/src/data/data-engine.zod.ts | 10 +- packages/spec/src/data/driver.zod.ts | 38 +++++++ 9 files changed, 387 insertions(+), 40 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 1e090caea42..1e8180777fa 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -32,11 +32,11 @@ import { coreSqlDialectOf } from './sql-driver-oracle-dialect.js'; import { emptyGroupValueFor, isComposedReadableIds } from '@objectstack/spec/data'; import type { Knex } from 'knex'; import type { ComposedReadableIds, DriverOptions } from '@objectstack/spec/data'; -import type { DriverQuery } from '@objectstack/spec/contracts'; +import type { DriverAggregateQuery, DriverQuery } from '@objectstack/spec/contracts'; import { AGGREGATE_ACCUMULATION, AGGREGATE_ANSWER_KIND, aggregandOperandSql } from '@objectstack/core'; import type { AggregandColumnClass } from '@objectstack/core'; import { - refuseDateBucketedGroupBy, refuseDistinctAggregateWithoutField, unsupportedAggregationFilterError, + refuseDateBucketedGroupBy, refuseDistinctAggregateWithoutField, refuseZonedDateBucket, unsupportedAggregationFilterError, } from './sql-driver-top-level.js'; import type { ReadPresentationKind } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; @@ -65,6 +65,7 @@ export interface AggregationHost { getBuilder: SqlDriver['getBuilder']; readonly isMssql: SqlDriver['isMssql']; readonly isOracle: SqlDriver['isOracle']; + readonly isPostgres: SqlDriver['isPostgres']; readonly knex: SqlDriver['knex']; mapAggregateFunc: SqlDriver['mapAggregateFunc']; readonly numericFields: SqlDriver['numericFields']; @@ -78,11 +79,25 @@ export interface AggregationHost { /** The bodies of the "Aggregation" section of `SqlDriver`: a stateless facet, called by the class's stubs. */ 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[]> { + static async aggregate(this: Pick, object: string, query: DriverAggregateQuery, options?: DriverOptions): Promise[]> { // [relation group join] The related rows each relation joins, handed by // the engine (`objectql` `relation-group-join.ts`); read once, judged // before anything compiles. const relationJoins = relationGroupJoinsOf(query); + // [#33697] The reference zone the date buckets are read in + // (`DriverAggregateQuery.timezone`, ADR-0053 Phase 2 D2 as amended), judged + // before anything compiles. Absent or `UTC` is the UTC bucket every dialect + // has always run. Any other zone is bucketed only on PostgreSQL (the + // dialect `supports.zonedDateBucketing` names) and only as the runtime's + // resolved IANA area/location name for itself — the one spelling the + // database and the in-memory path read alike; the engine sends exactly + // that. Everything else is refused, never read as UTC. A query with no date + // bucket reads no zone, so it is not judged. + const bucketZone = zonedBucketOf(query); + if (bucketZone !== undefined) { + if (!this.isPostgres) refuseZonedDateBucket(bucketZone, 'dialect', `dialect '${(this.config as any).client}'`); + if (resolvedAreaZone(bucketZone) !== bucketZone) refuseZonedDateBucket(bucketZone, 'unresolved', 'driver-sql'); + } // [#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`. @@ -197,7 +212,12 @@ export class AggregationFacet { // gone. It had drifted from the declaration it was restating: `alias` was // missing from it and `dateGranularity` was widened to `string`, which is // what forced the `as any` on the `buildDateBucketExpr` call below. + // [#33697] The 1-based position of the select-list column the item + // being compiled projects: every item below adds exactly one column, + // and nothing is selected before the group keys. + let selectPosition = 0; for (const g of query.groupBy) { + if (typeof g === 'string' || (g && typeof g === 'object' && g.field)) selectPosition += 1; if (typeof g === 'string') { const column = columnOf(g); builder.groupBy(column); @@ -218,7 +238,7 @@ export class AggregationFacet { // moves. const outKey = g.alias ?? g.field; if (g.dateGranularity) { - const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity, table, columnOf(g.field)); + const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity, table, columnOf(g.field), bucketZone); if (!bucket) { // [#6212] Was a bare `throw new Error(...)`; see // {@link refuseDateBucketedGroupBy} for why it now carries the @@ -229,8 +249,21 @@ export class AggregationFacet { `dialect '${(this.config as any).client}'`, ); } - builder.groupByRaw(bucket.sql, bucket.bindings); builder.select(this.knex.raw(`${bucket.sql} as ${this.aliasIdentifierSql(outKey)}`, [...bucket.bindings])); + if (bucketZone !== undefined) { + // [#33697] Review item (a): a zoned bucket binds the zone as a + // VALUE, and PostgreSQL numbers each `?` as its own parameter, + // so spelling the expression again in the GROUP BY would leave + // `$1` in the select list and `$2` in the GROUP BY — two + // expressions to the planner, refused 42803. The bucket is + // stated once, in the select list, and grouped by its position + // there. Only this arm does it: ordinal GROUP BY is PostgreSQL's + // (and MySQL's / SQLite's), not SQL Server's or Oracle's, and + // the UTC buckets bind identifiers only. + builder.groupByRaw(String(selectPosition)); + } else { + builder.groupByRaw(bucket.sql, bucket.bindings); + } } else { const column = columnOf(g.field); builder.groupBy(column); @@ -542,6 +575,36 @@ export interface RelationGroupJoin { readonly resolvedAlias: string; } +/** + * [#33697] The non-UTC reference zone an `aggregate()` query's date buckets + * are read in, or `undefined` when there is none to read: no `timezone`, the + * `UTC` the engine never sends but a direct caller may, or a query with no + * `dateGranularity` item (no bucket reads a zone). + */ +function zonedBucketOf(query: DriverAggregateQuery): string | undefined { + const zone = query.timezone; + if (zone === undefined || zone === 'UTC') return undefined; + const bucketed = (query.groupBy ?? []).some((g) => typeof g === 'object' && g !== null && !!g.dateGranularity); + return bucketed ? zone : undefined; +} + +/** + * [#33697] The runtime's resolved IANA name for `zone` when it is an + * area/location name (contains `/`), else `undefined` — the test ADR-0053 + * Phase 2 D2 (as amended) states for what may be pushed down. A string the + * runtime cannot resolve throws there, and an offset (`+08:00`) or an + * abbreviation that resolves to itself (`EST5EDT`) has no `/`. + */ +function resolvedAreaZone(zone: string): string | undefined { + let resolved: string; + try { + resolved = new Intl.DateTimeFormat('en-US', { timeZone: zone }).resolvedOptions().timeZone; + } catch { + return undefined; + } + return resolved.includes('/') ? resolved : undefined; +} + /** * The joins on `query`, or `undefined` when it carries none. A parent that is * not a leaf the engine composed is refused before anything compiles, as an diff --git a/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts b/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts index e0cccd776e9..1ec2a13b027 100644 --- a/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts +++ b/packages/drivers/driver-sql/src/sql-driver-date-bucket.ts @@ -63,17 +63,26 @@ export interface DateBucketHost { } /** The body of `SqlDriver#buildDateBucketExpr`; the method's docblock there is its contract. */ -export function buildDateBucketExpr(this: Pick, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null, column: string = field): { sql: string; bindings: any[] } | null { +export function buildDateBucketExpr(this: Pick, field: string, granularity: 'day' | 'week' | 'month' | 'quarter' | 'year', table?: string | null, column: string = field, timezone?: string): { sql: string; bindings: any[] } | null { if (!this.dateGranularityCapabilities[granularity]) return null; // `field` is the FIELD — the registries (`temporalFieldKind`, the SQLite // repair) are keyed by it; `column` is the identifier the statement names, - // the remote column an `external.columnMap` maps the field to. + // the remote column an `external.columnMap` maps the field to. A zone + // binding is never mistaken for the field: a field is a snake_case machine + // name and the zone an area/location name, which contains `/`. if (column !== field) { - const bucket = buildDateBucketExpr.call(this, field, granularity, table); + const bucket = buildDateBucketExpr.call(this, field, granularity, table, field, timezone); return bucket && { sql: bucket.sql, bindings: bucket.bindings.map((b) => (b === field ? column : b)) }; } + // [#33697] A reference zone (ADR-0053 Phase 2 D2 as amended) is bucketed by + // the PostgreSQL arm only, the one dialect that declares + // `supports.zonedDateBucketing`; every other arm answers `null` for it + // rather than a UTC bucket under a zone's name. `aggregate` refuses before + // it asks, so this is the second wall, not the first. + if (timezone !== undefined && !this.isPostgres) return null; + const calendarDay = this.temporalFieldKind(table, field) === 'date'; if (this.isOracle) { @@ -96,13 +105,22 @@ export function buildDateBucketExpr(this: Pick this.dateFields; @@ -1248,7 +1268,7 @@ export class SqlDriver implements IDataDriver { sqliteTemporalArg: (...a) => this.sqliteTemporalArg(...a), temporalFieldKind: (...a) => this.temporalFieldKind(...a), }; - return buildDateBucketExpr.call(host, field, granularity, table, column); + return buildDateBucketExpr.call(host, field, granularity, table, column, timezone); } /** @@ -3731,7 +3751,7 @@ export class SqlDriver implements IDataDriver { * below is the contract's own, pinned at the type level in * `sql-driver-doors-declared-types.test.ts`. */ - aggregate(object: string, query: DriverQuery, options?: DriverOptions): Promise[]> { + aggregate(object: string, query: DriverAggregateQuery, options?: DriverOptions): Promise[]> { // [#29520 codemod] The body moved to `sql-driver-aggregation.ts` (see `AggregationHost`). return AggregationFacet.aggregate.call(aggregationHost.of(this), object, query, options); } @@ -9395,6 +9415,7 @@ export class SqlDriver implements IDataDriver { get getBuilder() { return driver.getBuilder.bind(driver); }, get isMssql() { return driver.isMssql; }, get isOracle() { return driver.isOracle; }, + get isPostgres() { return driver.isPostgres; }, get knex() { return driver.knex; }, mapAggregateFunc: (...a) => driver.mapAggregateFunc(...a), get numericFields() { return driver.numericFields; }, diff --git a/packages/objectql/src/engine-aggregate-timezone.test.ts b/packages/objectql/src/engine-aggregate-timezone.test.ts index cae834cd4bc..ba11f4e6745 100644 --- a/packages/objectql/src/engine-aggregate-timezone.test.ts +++ b/packages/objectql/src/engine-aggregate-timezone.test.ts @@ -2,11 +2,13 @@ // // ADR-0053 Phase 2 (D2): `engine.aggregate({ timezone })` routing. // -// Native driver date bucketing (`date_trunc`) is UTC-only, so a non-UTC -// reference timezone must force the in-memory path (uniform across drivers) -// while UTC / unset keeps the native fast path. These tests pin both halves -// using a driver that advertises native day bucketing and records whether its -// native `aggregate()` was taken. +// A driver that does NOT declare `supports.zonedDateBucketing` buckets +// natively in UTC only, so a non-UTC reference timezone must force the +// in-memory path while UTC / unset keeps the native fast path. These tests pin +// both halves using a driver that advertises native day bucketing and records +// whether its native `aggregate()` was taken. [#33697] D2 as amended: a driver +// that DOES declare it receives the zone, resolved by the runtime first — the +// last describe block pins that dispatch, spelling by spelling. import { describe, it, expect } from 'vitest'; import { ObjectQL } from './engine.js'; @@ -104,3 +106,89 @@ describe('engine.aggregate timezone routing (ADR-0053 Phase 2)', () => { ]); }); }); + +// [#33697] ADR-0053 Phase 2 D2 as amended: a driver declaring +// `supports.zonedDateBucketing` is handed the zone the RUNTIME resolves the +// request's string to, and only an area/location name; review items (d) and +// (e) on the card name the spellings. +describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => { + async function makeZonedEngine(zoned: boolean | undefined) { + const received: any[] = []; + let findCalls = 0; + const driver: any = { + name: 'zoned-mock', + version: '0.0.0', + supports: { + queryDateGranularity: { day: true, week: true, month: true, quarter: true, year: true }, + ...(zoned === undefined ? {} : { zonedDateBucketing: zoned }), + }, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find() { findCalls += 1; return ROWS.slice(); }, + async findOne() { return null; }, + 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() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + async aggregate(_object: string, ast: any) { received.push(ast); return []; }, + }; + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'deal', + fields: { closed_at: { type: 'datetime' }, amount: { type: 'number' } }, + } as any); + return { engine, received, finds: () => findCalls }; + } + + it.each([ + ['Asia/Taipei', 'Asia/Taipei'], + ['Europe/Berlin', 'Europe/Berlin'], + ['CST', 'America/Chicago'], + ['US/Eastern', 'America/New_York'], + ['Etc/GMT+5', 'Etc/GMT+5'], + ])('pushes %s down as the resolved name %s', async (asked, sent) => { + const { engine, received, finds } = await makeZonedEngine(true); + await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + expect(finds()).toBe(0); + expect(received).toHaveLength(1); + expect(received[0].timezone).toBe(sent); + }); + + it.each(['UTC', 'Etc/UTC', 'GMT', 'Zulu'])('reads %s as the UTC bucket: native, no zone sent', async (asked) => { + const { engine, received, finds } = await makeZonedEngine(true); + await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + expect(finds()).toBe(0); + expect(received).toHaveLength(1); + expect('timezone' in received[0]).toBe(false); + }); + + it.each(['EST5EDT', '+08:00', 'Bogus/Zone'])('keeps %s in memory: it resolves to no area/location name', async (asked) => { + const { engine, received, finds } = await makeZonedEngine(true); + await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + expect(received).toHaveLength(0); + expect(finds()).toBe(1); + }); + + it.each([false, undefined])('keeps a non-UTC zone in memory on a driver whose bit is %s', async (bit) => { + const { engine, received, finds } = await makeZonedEngine(bit); + await engine.aggregate('deal', { ...dayBucket, timezone: 'Asia/Taipei' } as any); + expect(received).toHaveLength(0); + expect(finds()).toBe(1); + }); + + it('sends no zone for a query with no date bucket', async () => { + const { engine, received } = await makeZonedEngine(true); + await engine.aggregate('deal', { + groupBy: ['closed_at'], + aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }], + timezone: 'Asia/Taipei', + } as any); + expect(received).toHaveLength(1); + expect('timezone' in received[0]).toBe(false); + }); +}); diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 7c7aad63c3f..b4a0aab2fec 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -1406,17 +1406,35 @@ export class DeleteAndAggregateFacet { if (!g?.dateGranularity) return true; // plain {field} object is fine return granularityCaps?.[g.dateGranularity] === true; }); - // ADR-0053 Phase 2 (D2): native driver date bucketing (driver-sql's - // `to_char` / `date_format` / `strftime`) is UTC-only — SQLite has no - // tz database and MySQL needs tz tables loaded, - // so pushing tz-aware bucketing down splits boundaries per dialect. When - // a non-UTC reference timezone is in play we therefore force the - // in-memory path: the date-range `where` still goes to the driver (only - // matching rows are fetched), but bucketing runs uniformly in JS so a - // row near a tz day-boundary lands identically on every driver. + // ADR-0053 Phase 2 D2, as amended for #33697 (maintainer ruling + // 「PG 在库里算,修订 ADR」): a non-UTC reference timezone is bucketed in + // the database by a driver that DECLARES zone-aware bucketing + // (`supports.zonedDateBucketing` — PostgreSQL in driver-sql), and in + // memory on every other driver, where the date-range `where` still goes + // to the driver and bucketing runs in JS (`applyInMemoryAggregation`). + // Both answer the same buckets; that parity is the amendment's + // acceptance rule. + // + // The zone is judged by what the RUNTIME resolves it to, never by the + // raw string (review items d and e on #33697): `Etc/UTC`, `GMT`, + // `Zulu` resolve to `UTC` and take the UTC path every driver serves; a + // name that resolves to an area/location (`Asia/Taipei`, `CST` → + // `America/Chicago`, `US/Eastern` → `America/New_York`, `Etc/GMT+5`) + // is pushed down AS the resolved name, the zone the in-memory path + // reads it as; a string the runtime cannot resolve, or one that + // resolves to no area/location (`+08:00`, `EST5EDT`), stays in memory, + // which answers it as it always has. The raw string never reaches a + // driver: the database reads those other spellings differently. const tz = query.timezone; const hasDateBucket = structuredItems.some((g) => !!g?.dateGranularity); - const tzRequiresInMemory = !!tz && tz !== 'UTC' && hasDateBucket; + const bucketZone = hasDateBucket ? judgeBucketZone(tz) : { kind: 'utc' as const }; + const zoneNative = bucketZone.kind === 'utc' + || (bucketZone.kind === 'area' && drv?.supports?.zonedDateBucketing === true); + const tzRequiresInMemory = !zoneNative; + // The query the driver's own `aggregate()` receives: the AST, plus the + // resolved zone when a zoned bucket is pushed down (`DriverAggregateQuery`). + const withBucketZone = (statement: T): T => + bucketZone.kind === 'area' ? { ...statement, timezone: bucketZone.zone } : statement; // [#10576] Per-aggregation filters (`aggregations[].filter`, the // contract half of #10413) go to `driver.aggregate` only on a driver // that declares it compiles them: [#33698] `supports.aggregationFilter` @@ -1454,7 +1472,7 @@ export class DeleteAndAggregateFacet { const joins = relationGroupJoinsAtBoundary(relationGroup, plannedRelationGroups, aggregateOptions); if (joins === null) return []; const statement = withoutJudgedRelationFields(ast, judgedRelationFields, query.groupBy); - const joined = await drv.aggregate(object, { ...statement, [RELATION_GROUP_JOINS]: joins }, aggregateOptions); + const joined = await drv.aggregate(object, withBucketZone({ ...statement, [RELATION_GROUP_JOINS]: joins }), aggregateOptions); assertRelationGroupRowsJoined(object, drv.name, joined, joins); relationGroup.outcome = { kind: 'joined' }; return applyHaving(joined, ast.having, havingColumnClasses); @@ -1466,7 +1484,7 @@ export class DeleteAndAggregateFacet { // natively today; one that grows native support must advertise a // capability flag, at which point this post-filter becomes the // fallback tier — the dateGranularity two-tier pattern. - const aggregated = await drv.aggregate(object, ast, aggregateOptions); + const aggregated = await drv.aggregate(object, withBucketZone(ast), aggregateOptions); return applyHaving(aggregated, ast.having, havingColumnClasses); } // In-memory fallback path: ask the driver for raw rows, then bucket + @@ -1516,3 +1534,31 @@ export class DeleteAndAggregateFacet { return opCtx.result as any[]; } } + +/** + * [#33697] How `engine.aggregate` reads a request's reference `timezone` for + * its date buckets (ADR-0053 Phase 2 D2 as amended): through the runtime's + * own resolution (the `resolvedOptions().timeZone` of an + * `Intl.DateTimeFormat`), the same resolution the in-memory bucketer applies. + * + * - `utc` — unset, or a name that resolves to `UTC` (`Etc/UTC`, `GMT`, + * `Zulu`): the UTC bucket every driver runs natively. + * - `area` — resolves to an IANA area/location name (contains `/`): pushed + * down as `zone`, the resolved name, to a driver that declares + * `supports.zonedDateBucketing`. + * - `memory` — the runtime cannot resolve it, or it resolves to an offset or + * an abbreviation with no `/` (`+08:00`, `EST5EDT`): bucketed in memory, + * which reads it as it always has. + */ +export function judgeBucketZone(timezone: string | undefined): + { kind: 'utc' } | { kind: 'area'; zone: string } | { kind: 'memory' } { + if (timezone === undefined || timezone === '' || timezone === 'UTC') return { kind: 'utc' }; + let resolved: string; + try { + resolved = new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone; + } catch { + return { kind: 'memory' }; + } + if (resolved === 'UTC') return { kind: 'utc' }; + return resolved.includes('/') ? { kind: 'area', zone: resolved } : { kind: 'memory' }; +} diff --git a/packages/spec/src/contracts/data-driver.ts b/packages/spec/src/contracts/data-driver.ts index 5460afa9b48..13ec284fe8c 100644 --- a/packages/spec/src/contracts/data-driver.ts +++ b/packages/spec/src/contracts/data-driver.ts @@ -53,6 +53,30 @@ import type { IntrospectedSchema } from './schema-diff-service.js'; */ export type DriverQuery = Omit; +/** + * DriverAggregateQuery — what {@link IDataDriver.aggregate} receives: a + * {@link DriverQuery} plus the one key only that verb reads. + * + * `timezone` is the reference zone a date `groupBy` item is bucketed on + * (ADR-0053 Phase 2 D2 as amended for #33697). The engine sets it only on a + * driver that declares `supports.zonedDateBucketing` (`DriverCapabilities`), + * and only to the zone's RESOLVED IANA area/location name (the + * `resolvedOptions().timeZone` of an `Intl.DateTimeFormat`, e.g. + * `America/Chicago` for `CST`) — never the raw request string, never `UTC`, + * which is the bucket a driver answers when the key is absent. A driver that + * reads it buckets an instant column on that zone's calendar, DST-correct, + * keeps a `Field.date` on its own calendar day, and refuses a zone it cannot + * bucket rather than reading it as UTC. + * + * Kept off {@link DriverQuery} on purpose: `find()` / `count()` take that type + * and no zone means anything to them, so a key they would silently drop is not + * declared where they read. + */ +export type DriverAggregateQuery = DriverQuery & { + /** Resolved IANA area/location zone to bucket dates on; absent = UTC. */ + timezone?: string; +}; + /** * IDataDriver - Comprehensive Database Driver Interface * @@ -228,8 +252,11 @@ export interface IDataDriver { * `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 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 + * (ADR-0053 Phase 2 D2 as amended) reaches this method only on a driver that + * declares `supports.zonedDateBucketing`, as the resolved zone name in + * {@link DriverAggregateQuery.timezone}; on every other driver it forces the + * in-memory path, so such a driver never sees a zone here. + * `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 @@ -252,7 +279,7 @@ export interface IDataDriver { * pipeline) or a looser return type stays assignable; what is refused is a * wrong argument order or a non-array result. */ - aggregate?(object: string, query: DriverQuery, options?: DriverOptions): Promise[]>; + aggregate?(object: string, query: DriverAggregateQuery, options?: DriverOptions): Promise[]>; // =========================================================================== // Bulk Operations diff --git a/packages/spec/src/data/data-engine.zod.ts b/packages/spec/src/data/data-engine.zod.ts index 189f89702c6..09603b6281e 100644 --- a/packages/spec/src/data/data-engine.zod.ts +++ b/packages/spec/src/data/data-engine.zod.ts @@ -503,8 +503,14 @@ export const EngineAggregateOptionsSchema = lazySchema(() => BaseEngineOptionsSc /** * Reference timezone (IANA name) for date bucketing (ADR-0053 Phase 2). * When set to a non-UTC zone, `groupBy` items carrying a `dateGranularity` - * bucket on that zone's calendar days. Unset or `'UTC'` keeps the UTC - * fast path (native driver `date_trunc`). + * bucket on that zone's calendar days. Unset, or a name the runtime resolves + * to `UTC` (`Etc/UTC`, `GMT`, `Zulu`), keeps the UTC path (the driver's + * native bucket). Any other zone is bucketed in the database by a driver + * that declares `supports.zonedDateBucketing` (PostgreSQL), which receives + * the RESOLVED area/location name (`CST` goes down as `America/Chicago`), + * and in memory otherwise — and always in memory for a string the runtime + * cannot resolve or that resolves to no area/location name (`+08:00`, + * `EST5EDT`). Both paths answer the same buckets (D2 as amended). */ timezone: z.string().optional(), /** diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 7c7871df30a..190f4d17db1 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -160,6 +160,10 @@ const capRemoved = (key: string, mechanism: string) => * `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). + * - `zonedDateBucketing` — opt-IN for a non-UTC reference zone on a date + * bucket of `aggregate()` (ADR-0053 Phase 2 D2 as amended): the engine ANDs + * it with method presence, because one driver class serves dialects with + * and without a tz database. * * Everything else IS the method: aggregate pushdown gates on * `typeof driver.aggregate === 'function'`, schema sync on @@ -338,6 +342,40 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ */ 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)'), + /** + * `aggregate()` buckets a date `groupBy` item on the calendar of a named + * IANA zone, DST-correct, when the query it receives carries one + * (`DriverAggregateQuery.timezone`, `contracts/data-driver.ts`) — ADR-0053 + * Phase 2 D2 as amended for #33697. + * + * What the engine does with it: `engine.aggregate` resolves the request's + * reference `timezone` through the runtime first (the `resolvedOptions()` + * name of an `Intl.DateTimeFormat`). A zone that resolves to `UTC` takes + * the UTC path every driver already serves. A zone that resolves to an + * area/location name (one containing `/`, such as `Asia/Taipei`, or + * `America/Chicago` for `CST`) is sent down WITH that resolved name when + * this bit is `true` and the driver has `aggregate()`; every other case + * (no bit, a name the runtime cannot resolve, an offset such as `+08:00`, + * an abbreviation that resolves to itself such as `EST5EDT`) keeps the + * in-memory aggregate (`applyInMemoryAggregation`), which answers it as it + * always has. The raw string never reaches a driver. + * + * What a driver that declares it owes: its buckets equal the in-memory + * buckets (`bucketDateKey` in `@objectstack/core`) for that zone, on both + * sides of a DST change; the labels stay the `queryDateGranularity` output + * contract above; a `Field.date` (a timezone-naive calendar day) is never + * zone-shifted; the zone is a bound value, never SQL text; and a zone it + * cannot bucket is refused loudly, never read as UTC. + * + * Why a bit and not method presence: one driver class can serve dialects + * that differ here. `SqlDriver` declares it on PostgreSQL (`AT TIME ZONE` + * over the server's tz database) and not on SQLite, which has no tz + * database, nor on MySQL, SQL Server or Oracle. + * + * Optional; absence means `false`, like `aggregationFilter`. + */ + zonedDateBucketing: z.boolean().optional().describe('`aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone in memory)'), + // ============================================================================ // Retired capability bits (#4634, ADR-0049 enforce-or-remove) — 17.0.0 // ============================================================================ From de122f4f416799e935631338907cc8cb70ef156a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:27:56 +0000 Subject: [PATCH 02/12] test(driver-sql): zoned date bucket parity against the in-memory labels (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- ...sql-driver-33697-zoned-date-bucket.test.ts | 214 ++++++++++++++++++ packages/spec/authorable-surface/data.json | 1 + 2 files changed, 215 insertions(+) create mode 100644 packages/drivers/driver-sql/src/sql-driver-33697-zoned-date-bucket.test.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-33697-zoned-date-bucket.test.ts b/packages/drivers/driver-sql/src/sql-driver-33697-zoned-date-bucket.test.ts new file mode 100644 index 00000000000..c2f4d6c1716 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-33697-zoned-date-bucket.test.ts @@ -0,0 +1,214 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33697] ADR-0053 Phase 2 D2 as amended: PostgreSQL buckets a non-UTC + * reference zone in the database, and its buckets equal the in-memory ones. + * + * `aggregate()` reads the zone from `DriverAggregateQuery.timezone`, which the + * engine sets only on a driver declaring `supports.zonedDateBucketing`, and + * only to the runtime's resolved area/location name. + * + * ## The cells + * + * - **sqlite**, every run (and **live mysql** where provisioned, which + * declares nothing here either): SQLite has no tz database, so it does not + * declare the bit and refuses a zoned bucket (NOT_IMPLEMENTED / 501) rather than read + * the zone as UTC. `UTC` and a query with no date bucket are served. + * - **live postgres**, where `OS_TEST_POSTGRES_URL` is provisioned (a named + * skip otherwise, red under `OS_EXPECT_LIVE_DIALECT_MATRIX=1`): it declares + * the bit, and every bucket `aggregate()` answers for a zone equals the + * label the in-memory path computes for the same row — `bucketDateKey` + * (`@objectstack/core`) with the zone for a `Field.datetime`, and with no + * zone for a `Field.date` (`in-memory-aggregation.ts` `bucketCalendarDay`). + * The rows cross both 2026 Europe/Berlin DST changes at a local midnight, + * a month, a quarter, a year and an ISO-week boundary; the zones are the + * ADR's parity set (Europe/Berlin, Asia/Taipei, America/New_York, which is + * WEST of UTC for the calendar-day axis) plus the card's review item (e) + * names (`America/Chicago`, what `CST` resolves to; `Etc/GMT+5`). A zone + * the runtime does not resolve to itself is refused (INVALID_QUERY / 400). + * + * Review item (a): the zone is a bound value, and the bucket binds it once — + * the GROUP BY names the select-list position — so PostgreSQL does not see two + * parameters and refuse with 42803. The multi-key case below puts the bucket + * second, after a plain key, under a `where` that binds values of its own. + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { bucketDateKey } from '@objectstack/core'; +import { SqlDriver } from '../src/index.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; + +const TABLE = 'os33697_zoned_bucket'; + +type Granularity = 'day' | 'week' | 'month' | 'quarter' | 'year'; +const GRANULARITIES: readonly Granularity[] = ['day', 'week', 'month', 'quarter', 'year']; + +/** Each row: a calendar day (`on`, `Field.date`), an instant (`at`, `Field.datetime`), a plain key. */ +const ROWS: ReadonlyArray<{ id: string; kind: string; on: string | null; at: string | null }> = [ + // Europe/Berlin, before the spring change (CET, +1): local 2026-03-29 00:30. + { id: 'r01', kind: 'a', on: '2026-03-29', at: '2026-03-28T23:30:00.000Z' }, + // After it (CEST, +2): local 2026-03-30 00:30; a +1 reading says 03-29. + { id: 'r02', kind: 'b', on: '2026-03-30', at: '2026-03-29T22:30:00.000Z' }, + // Month and quarter edge in CEST: local 2026-04-01 00:30 (Q2); +1 says 03-31 (Q1). + { id: 'r03', kind: 'a', on: '2026-04-01', at: '2026-03-31T22:30:00.000Z' }, + // Before the autumn change (CEST, +2): local 2026-10-25 00:30. + { id: 'r04', kind: 'b', on: '2026-10-25', at: '2026-10-24T22:30:00.000Z' }, + // After it (CET, +1): local 2026-10-26 00:30 (a Monday, ISO week 44). + { id: 'r05', kind: 'a', on: '2026-10-26', at: '2026-10-25T23:30:00.000Z' }, + // Month edge in CET: local 2026-11-01 00:30. + { id: 'r06', kind: 'b', on: '2026-11-01', at: '2026-10-31T23:30:00.000Z' }, + // Year edge east of UTC: Asia/Taipei 2026-01-01 00:30; Berlin 2025-12-31 17:30. + { id: 'r07', kind: 'a', on: '2026-01-01', at: '2025-12-31T16:30:00.000Z' }, + // West of UTC: America/New_York 2026-02-28 23:30 (EST, -5); UTC says 03-01. + { id: 'r08', kind: 'b', on: '2026-03-01', at: '2026-03-01T04:30:00.000Z' }, + // ISO week edge: Berlin Monday 2026-01-05 00:30 (W02); UTC Sunday (W01). + { id: 'r09', kind: 'a', on: '2024-12-30', at: '2026-01-04T23:30:00.000Z' }, + // The empty bucket. + { id: 'r10', kind: 'b', on: null, at: null }, +]; + +const ZONES = ['Europe/Berlin', 'Asia/Taipei', 'America/New_York', 'America/Chicago', 'Etc/GMT+5'] as const; + +/** The empty bucket, keyed out of band so it cannot collide with a real label. */ +const EMPTY = '(empty bucket)'; +const labelOf = (v: unknown): string => (v == null ? EMPTY : String(v)); + +/** What the in-memory path answers: label -> row count, for `column` bucketed by `g` in `zone`. */ +function inMemoryBuckets(column: 'on' | 'at', g: Granularity, zone: string): [string, number][] { + const counts = new Map(); + for (const row of ROWS) { + const v = row[column]; + // A `Field.date` is a calendar day and reads no zone (bucketCalendarDay). + const key = labelOf(v == null ? null : column === 'on' ? bucketDateKey(v, g) : bucketDateKey(v, g, zone)); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return [...counts].sort(); +} + +function bucketsOf(rows: readonly Record[], labelColumn: string): [string, number][] { + return rows.map((r): [string, number] => [labelOf(r[labelColumn]), Number(r.n)]).sort(); +} + +async function refusalOf(p: Promise): Promise<{ code?: string; status?: number }> { + try { + await p; + } catch (e) { + return e as { code?: string; status?: number }; + } + throw new Error('expected a refusal, got an answer'); +} + +function measure(cell: DialectCell): void { + describe(`[#33697] zoned date buckets on ${cell.label}`, () => { + let driver: SqlDriver; + + beforeAll(async () => { + driver = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.initObjects([ + { name: TABLE, fields: { kind: { type: 'text' }, on: { type: 'date' }, at: { type: 'datetime' } } }, + ]); + 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(); + }); + + if (cell.id !== 'pg') { + it('declares no zone-aware bucketing', () => { + expect(driver.supports.zonedDateBucketing).toBe(false); + }); + + it('refuses a zoned bucket NOT_IMPLEMENTED/501, never reading the zone as UTC', async () => { + const err = await refusalOf(driver.aggregate(TABLE, { + groupBy: [{ field: 'at', dateGranularity: 'month' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'Asia/Taipei', + })); + expect(err.code).toBe('NOT_IMPLEMENTED'); + expect(err.status).toBe(501); + }); + + it('serves UTC, and a zone on a query with no date bucket', async () => { + const utc = await driver.aggregate(TABLE, { + groupBy: [{ field: 'at', dateGranularity: 'year' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'UTC', + }); + expect(bucketsOf(utc as Record[], 'at')).toEqual(inMemoryBuckets('at', 'year', 'UTC')); + const plain = await driver.aggregate(TABLE, { + groupBy: ['kind'], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'Asia/Taipei', + }); + expect(bucketsOf(plain as Record[], 'kind')).toEqual([['a', 5], ['b', 5]]); + }); + return; + } + + it('declares zone-aware bucketing', () => { + expect(driver.supports.zonedDateBucketing).toBe(true); + }); + + it('the fixtures are zone-sensitive: every zone disagrees with UTC at some granularity, and every granularity in some zone', () => { + const differs = (zone: string, g: Granularity) => JSON.stringify(inMemoryBuckets('at', g, zone)) !== JSON.stringify(inMemoryBuckets('at', g, 'UTC')); + for (const zone of ZONES) expect(GRANULARITIES.some((g) => differs(zone, g)), zone).toBe(true); + for (const g of GRANULARITIES) expect(ZONES.some((zone) => differs(zone, g)), g).toBe(true); + }); + + for (const zone of ZONES) { + it.each(GRANULARITIES)(`${zone}: a Field.datetime buckets as the in-memory path does, by %s`, async (g) => { + const grouped = await driver.aggregate(TABLE, { + groupBy: [{ field: 'at', dateGranularity: g }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: zone, + }); + expect(bucketsOf(grouped as Record[], 'at')).toEqual(inMemoryBuckets('at', g, zone)); + }); + + it.each(GRANULARITIES)(`${zone}: a Field.date keeps its calendar day, by %s`, async (g) => { + const grouped = await driver.aggregate(TABLE, { + groupBy: [{ field: 'on', dateGranularity: g }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: zone, + }); + expect(bucketsOf(grouped as Record[], 'on')).toEqual(inMemoryBuckets('on', g, zone)); + }); + } + + it('binds the zone once: a bucket after a plain key, aliased, under a where with bindings', async () => { + const grouped = (await driver.aggregate(TABLE, { + where: { kind: { $in: ['a', 'b'] }, id: { $ne: 'zz' } }, + groupBy: ['kind', { field: 'at', dateGranularity: 'month', alias: 'm' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'Europe/Berlin', + })) as Record[]; + const want = new Map(); + for (const row of ROWS) { + const key = `${row.kind}|${labelOf(row.at == null ? null : bucketDateKey(row.at, 'month', 'Europe/Berlin'))}`; + want.set(key, (want.get(key) ?? 0) + 1); + } + const got = grouped.map((r): [string, number] => [`${r.kind}|${labelOf(r.m)}`, Number(r.n)]).sort(); + expect(got).toEqual([...want].sort()); + }); + + it.each(['CST', 'US/Eastern', '+08:00', 'EST5EDT', 'Bogus/Zone'])( + 'refuses %s INVALID_QUERY/400: only the resolved area/location name is bucketed', + async (zone) => { + const err = await refusalOf(driver.aggregate(TABLE, { + groupBy: [{ field: 'at', dateGranularity: 'day' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: zone, + })); + expect(err.code).toBe('INVALID_QUERY'); + expect(err.status).toBe(400); + }, + ); + }); +} + +for (const cell of DIALECT_CELLS) { + declareDialectCell(cell, 'zoned date bucket', measure); +} diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index f99d4facb2d..e4a78396fcb 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -219,6 +219,7 @@ "data/DriverCapabilities:transactionsUnsupported", "data/DriverCapabilities:update [RETIRED]", "data/DriverCapabilities:vectorSearch [RETIRED]", + "data/DriverCapabilities:zonedDateBucketing", "data/DriverConfig:capabilities", "data/DriverConfig:connectionString", "data/DriverConfig:name", From 76f6c1ee31b14b498cdf2a23bafecd97aef15478 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:28:29 +0000 Subject: [PATCH 03/12] docs(service-analytics): the dry-run zone refusal names both roads a zoned bucket takes (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .../objectql-echo-date-bucket.test.ts | 8 ++-- .../src/strategies/objectql-strategy.ts | 42 +++++++++++-------- 2 files changed, 30 insertions(+), 20 deletions(-) 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 fe70da7302e..e4860de4d06 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 @@ -36,9 +36,11 @@ * (`.github/workflows/ci.yml`), so the live cell is red-capable and runs in * CI. * - * [#21630] A non-UTC `timezone` makes the engine bucket in memory on that - * zone's calendar, on every driver, so no statement the database runs groups - * by those keys. The echo refuses there on every dialect: `/analytics/sql` + * [#21630] A non-UTC `timezone` makes the engine bucket on that zone's + * calendar: in the database on a driver that declares zone-aware bucketing + * (PostgreSQL, ADR-0053 Phase 2 D2 as amended for #33697) and in memory on + * every other, while the `dateBucketSql` hook renders the UTC bucket only. + * The echo refuses there on every dialect: `/analytics/sql` * answers `NOT_IMPLEMENTED` / 501 as a declared refusal, and `/analytics/query` * serves the same rows with no `sql`. It used to print `date_trunc`, which * PostgreSQL 16.14 ran on the session zone's calendar (timestamp keys, and at diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index 132270287f5..145efada32f 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -195,9 +195,12 @@ type BucketEchoRefusalCause = { zone: string } | { dialect: AnalyticsSqlDialect * refusal names its cause: * * - [#21630] **A non-UTC `timezone`, on every driver.** The engine then - * buckets in memory on that zone's calendar (ADR-0053 Phase 2, D2; - * `tzRequiresInMemory` in objectql's `engine.ts`): the driver only fetches - * the rows, and no statement the database runs groups by those keys. The + * buckets on that zone's calendar (ADR-0053 Phase 2 D2 as amended for + * #33697; `judgeBucketZone` and `tzRequiresInMemory` in objectql's + * `engine-delete-and-aggregate.ts`): in the database, with the zone bound, on + * a driver that declares `supports.zonedDateBucketing` (PostgreSQL), and in + * memory everywhere else. The `dateBucketSql` hook renders the UTC bucket + * only, so this echo has no expression for either road and refuses. The * `date_trunc('', col)` this used to print groups on the * database SESSION's calendar where it runs at all. Measured on PostgreSQL * 16.14 with the server at `Asia/Shanghai`, it answered timestamp keys such @@ -231,11 +234,12 @@ function bucketEchoRefused(dimension: string, granularity: string, cause: Bucket const err = new Error( `[analytics] cannot render display SQL for the "${granularity}" bucket of "${dimension}"` + ('zone' in cause - ? ` with timezone "${cause.zone}". The query itself is SERVED: the engine buckets it in memory on that ` + - `zone's calendar, so no statement the database runs groups by those bucket keys. Refusing rather than ` + - `printing one that groups on another calendar. Run the query itself (/analytics/query) to get its rows; ` + - `with timezone "UTC" or none, this dry run renders the expression the driver groups the bucket by, ` + - `where the driver has one.` + ? ` with timezone "${cause.zone}". The query itself is SERVED: the engine buckets it on that zone's ` + + `calendar, in the database where the driver declares zone-aware bucketing and in memory otherwise, ` + + `while this dry run renders only the UTC bucket expression. Refusing rather than printing one that ` + + `groups on another calendar. Run the query itself (/analytics/query) to get its rows; with timezone ` + + `"UTC" or none, this dry run renders the expression the driver groups the bucket by, where the driver ` + + `has one.` : (cause.dialect === 'unknown' ? `: the driver behind this datasource names no SQL dialect and renders no expression for it. A ` + `driver that runs no SQL, such as the in-memory or MongoDB driver, buckets it without one: the ` + @@ -795,8 +799,10 @@ export class ObjectQLStrategy implements AnalyticsStrategy { * and answers the face's bucket keys. [#21647] That expression is the only * thing a bucket is ever printed as. Where there is none, the echo refuses * ({@link bucketEchoRefused}), on every driver and every dialect: a non-UTC - * `timezone`, which the engine buckets in memory on that zone's calendar - * (#21630), and a hook that answers nothing at UTC, which is a driver that + * `timezone`, which the engine buckets on that zone's calendar, in the + * database on a driver declaring zone-aware bucketing and in memory + * otherwise, while the hook renders the UTC bucket only (#21630, #33697), + * and a hook that answers nothing at UTC, which is a driver that * runs no SQL, a granularity the driver leaves to the engine, or a host that * wires no hook (#21595 was SQLite's case of it). No bucket expression is * written here. @@ -947,13 +953,15 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // (`no such function`), and PostgreSQL answers a timestamp where the face // answers `2026-01`. // - // Asked only for a UTC or unset `timezone`. The driver's expression is a - // UTC bucket. [#21630] A non-UTC zone makes the engine bucket in memory on - // that zone's calendar instead, on every driver (ADR-0053 Phase 2, D2; - // `tzRequiresInMemory` in objectql's `engine.ts`, the same test on the same - // `timezone`), so no statement the database runs groups by those keys, and - // the echo refuses on every dialect before the hook is asked - // ({@link bucketEchoRefused}). + // Asked only for a UTC or unset `timezone`. The hook's expression is the + // UTC bucket. [#21630] A non-UTC zone makes the engine bucket on that + // zone's calendar instead (ADR-0053 Phase 2 D2 as amended for #33697): in + // the database with the zone bound on a driver that declares + // `supports.zonedDateBucketing`, in memory on every other. The hook renders + // neither, so the echo refuses on every dialect before the hook is asked + // ({@link bucketEchoRefused}). The test here is the raw string against + // `'UTC'`; the engine reads the runtime-resolved name, so a UTC alias such + // as `Etc/UTC` is served natively there and still refused here. // // [#21647] Where the hook answers nothing at UTC, the echo refuses too, on // every dialect. That is the engine's other in-memory condition, read off From b0ffde388d7a4dd34556653954a46f39d8132024 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:32:20 +0000 Subject: [PATCH 04/12] chore(spec): regenerate api-surface, export-origins and reference docs; changeset (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .changeset/33697-pg-zoned-date-bucketing.md | 16 ++++++++++++++++ content/docs/references/data/driver-nosql.mdx | 1 + content/docs/references/data/driver-sql.mdx | 1 + content/docs/references/data/driver.mdx | 2 ++ packages/spec/api-surface/contracts.json | 1 + packages/spec/export-origins/contracts.json | 1 + 6 files changed, 22 insertions(+) create mode 100644 .changeset/33697-pg-zoned-date-bucketing.md diff --git a/.changeset/33697-pg-zoned-date-bucketing.md b/.changeset/33697-pg-zoned-date-bucketing.md new file mode 100644 index 00000000000..e01ff4b44d7 --- /dev/null +++ b/.changeset/33697-pg-zoned-date-bucketing.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/driver-sql': patch +'@objectstack/objectql': patch +'@objectstack/service-analytics': patch +--- + +Clause-②: yes (widening) +Metadata-protocol: none + +PostgreSQL now buckets a non-UTC reference timezone in the database (ADR-0053 Phase 2 D2 as amended). A dashboard grouped by day, week, month, quarter or year in a zone such as `Asia/Taipei` or `Europe/Berlin` no longer pulls every scoped row into the application on PostgreSQL: the bucket is computed by `to_char((col)::timestamptz AT TIME ZONE $zone, …)` with the zone bound, DST-correct, and its labels equal the in-memory ones. A `Field.date` keeps its calendar day under every zone. + +- `@objectstack/spec`: new driver capability bit `supports.zonedDateBucketing`, and `DriverAggregateQuery` (a `DriverQuery` plus `timezone`), the query `IDataDriver.aggregate` receives. Additive; existing drivers keep compiling and keep today's path. +- `@objectstack/objectql`: `engine.aggregate` resolves the request's `timezone` through the runtime first. A name that resolves to `UTC` (`Etc/UTC`, `GMT`, `Zulu`) takes the native UTC path; an area/location name (`CST` resolves to `America/Chicago`) is pushed down as the resolved name to a driver that declares the bit; anything else stays in memory, as before. +- `@objectstack/driver-sql`: declares the bit on PostgreSQL only. SQLite (no tz database), MySQL, SQL Server and Oracle keep the in-memory path. A zoned `aggregate()` call made directly against a dialect without the bit is refused `NOT_IMPLEMENTED`/501, and a zone string that is not its own resolved area/location name is refused `INVALID_QUERY`/400, instead of being read as UTC. +- `@objectstack/service-analytics`: the `/analytics/sql` dry-run refusal for a non-UTC zone now says the query is bucketed in the database or in memory depending on the driver. diff --git a/content/docs/references/data/driver-nosql.mdx b/content/docs/references/data/driver-nosql.mdx index 81eb356ce1f..52e7fe23642 100644 --- a/content/docs/references/data/driver-nosql.mdx +++ b/content/docs/references/data/driver-nosql.mdx @@ -166,6 +166,7 @@ const result = AggregationPipelineSchema.parse(data); | **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) | +| **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone 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 0e33d1f5635..55de5022acc 100644 --- a/content/docs/references/data/driver-sql.mdx +++ b/content/docs/references/data/driver-sql.mdx @@ -79,6 +79,7 @@ const result = DataTypeMappingSchema.parse(data); | **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) | +| **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone 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 707842e7435..d4a05b0df5b 100644 --- a/content/docs/references/data/driver.mdx +++ b/content/docs/references/data/driver.mdx @@ -33,6 +33,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **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) | +| **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone 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. | @@ -89,6 +90,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **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) | +| **zonedDateBucketing** | `boolean` | optional | `aggregate()` buckets a date groupBy on the calendar of the resolved IANA zone the engine sends (DriverAggregateQuery.timezone), DST-correct, equal to the in-memory buckets (absence = false: the engine buckets a non-UTC zone 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/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 5f02b9e20ee..6eac04d5dfd 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -109,6 +109,7 @@ "DelegableScope (interface)", "DelegationNarrowing (type)", "DeployExecutionResult (interface)", + "DriverAggregateQuery (type)", "DriverQuery (type)", "EMBEDDER_SERVICE (const)", "EffectiveAccess (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 9fd8dab1644..b2ab00510a4 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -109,6 +109,7 @@ "DelegableScope": "src/contracts/security-service.ts#DelegableScope (interface)", "DelegationNarrowing": "src/contracts/security-service.ts#DelegationNarrowing (type)", "DeployExecutionResult": "src/contracts/deploy-pipeline-service.ts#DeployExecutionResult (interface)", + "DriverAggregateQuery": "src/contracts/data-driver.ts#DriverAggregateQuery (type)", "DriverQuery": "src/contracts/data-driver.ts#DriverQuery (type)", "EMBEDDER_SERVICE": "src/contracts/embedder.ts#EMBEDDER_SERVICE (const)", "EffectiveAccess": "src/contracts/security-service.ts#EffectiveAccess (interface)", From 6b076305493be7fd30d5f90130d571cbe00d1c40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:55:40 +0000 Subject: [PATCH 05/12] test(spec): the audited DriverCapabilities shape carries the sixth live bit (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- packages/spec/src/data/driver.test.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/spec/src/data/driver.test.ts b/packages/spec/src/data/driver.test.ts index fe9a8032e73..ef5a0e06ac1 100644 --- a/packages/spec/src/data/driver.test.ts +++ b/packages/spec/src/data/driver.test.ts @@ -61,6 +61,10 @@ const RETIRED_BITS = [ * * `aggregationFilter` is the fifth, under the same rule: `engine.aggregate` * reads it (with method presence) to send a per-measure filter to the driver. + * + * [#33697] `zonedDateBucketing` is the sixth, under the same rule: + * `engine.aggregate` reads it (with method presence) to send a date bucket in + * a non-UTC reference zone to the driver (ADR-0053 Phase 2 D2 as amended). */ const LIVE_BITS = [ 'queryDateGranularity', @@ -68,6 +72,7 @@ const LIVE_BITS = [ 'batchSchemaSync', 'transactionsUnsupported', 'aggregationFilter', + 'zonedDateBucketing', ] as const; describe('DriverCapabilitiesSchema', () => { @@ -78,6 +83,7 @@ describe('DriverCapabilitiesSchema', () => { batchSchemaSync: true, transactionsUnsupported: true, aggregationFilter: true, + zonedDateBucketing: true, }; expect(() => DriverCapabilitiesSchema.parse(capabilities)).not.toThrow(); @@ -95,13 +101,19 @@ describe('DriverCapabilitiesSchema', () => { expect(parsed).not.toHaveProperty('transactionsUnsupported'); // Absent = the engine aggregates a filtered measure in memory, as before the bit. expect(parsed).not.toHaveProperty('aggregationFilter'); + // [#33697] Absent = the engine buckets a non-UTC zone in memory, as before the bit. + expect(parsed).not.toHaveProperty('zonedDateBucketing'); }); it('refuses a non-boolean aggregationFilter', () => { expect(DriverCapabilitiesSchema.safeParse({ aggregationFilter: 'yes' }).success).toBe(false); }); - it('declares exactly the audited shape: 5 live bits + 31 tombstones', () => { + it('refuses a non-boolean zonedDateBucketing', () => { + expect(DriverCapabilitiesSchema.safeParse({ zonedDateBucketing: 'postgres' }).success).toBe(false); + }); + + it('declares exactly the audited shape: 6 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()); @@ -202,7 +214,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 (5 since `aggregationFilter`). + // plus the live bits (6 since `zonedDateBucketing`). expect([...props.keys()].sort()).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); const decl = capsAlias!.declarations?.[0]; From 3950826d398d3b66a3b6d3eaf9dac2a96aa8f139 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:59:26 +0000 Subject: [PATCH 06/12] feat(service-analytics,driver-sql): the dry run reads the zone as the engine does and prints PostgreSQL's zoned bucket (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .../driver-sql/src/sql-driver-class-head.ts | 4 +- packages/drivers/driver-sql/src/sql-driver.ts | 14 ++- .../objectql-echo-bucket-enumeration.test.ts | 62 +++++++++--- .../objectql-echo-date-bucket.test.ts | 81 +++++++++++---- .../src/analytics-service.ts | 15 ++- .../services/service-analytics/src/plugin.ts | 13 ++- .../src/strategies/objectql-strategy.ts | 99 +++++++++++++------ .../service-analytics/src/strategies/types.ts | 6 +- 8 files changed, 217 insertions(+), 77 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-class-head.ts b/packages/drivers/driver-sql/src/sql-driver-class-head.ts index 96615ce9e5f..2ef77c76d1f 100644 --- a/packages/drivers/driver-sql/src/sql-driver-class-head.ts +++ b/packages/drivers/driver-sql/src/sql-driver-class-head.ts @@ -147,8 +147,8 @@ export class ClassHeadFacet { } /** The body of `SqlDriver#dateBucketSql`; the method's docblock there is its contract. */ - static dateBucketSql(this: Pick, objectName: string, field: string, granularity: DateGranularityValue): string | null { - const bucket = this.buildDateBucketExpr(field, granularity, objectName); + static dateBucketSql(this: Pick, objectName: string, field: string, granularity: DateGranularityValue, timezone?: string): string | null { + const bucket = this.buildDateBucketExpr(field, granularity, objectName, field, timezone); return bucket ? this.knex.raw(bucket.sql, bucket.bindings).toQuery() : null; } diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 579a6af11f2..4f2d3d380d7 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -1287,18 +1287,26 @@ export class SqlDriver implements IDataDriver { * Reading the expression from here keeps this driver the one source of its * bucketing. The text is `buildDateBucketExpr`'s, unchanged, with each `??` * rendered by knex (`Raw.toQuery`) through this dialect's own identifier - * quoting. The expression binds identifiers only, so the text carries no + * quoting. The UTC expression binds identifiers only, so the text carries no * value placeholder. `objectName` goes in as the coercion key, as * `aggregate` passes it, so a SQLite `Field.datetime` column that may still * hold pre-canonical values renders the repair the GROUP BY runs (#3773), * and a `Field.date` renders its calendar day on every dialect (#21485). * + * [#33697] `timezone`, when given, is the resolved IANA area/location name + * the engine pushes a zoned bucket down with (ADR-0053 Phase 2 D2 as + * amended): the text is then the zoned expression {@link aggregate} groups + * by, with the zone rendered as a quoted literal (a zone name is not tenant + * data), and `null` on every dialect that does not declare + * `supports.zonedDateBucketing` — exactly where the engine buckets that zone + * in memory instead. + * * Read structurally by its caller, like {@link dialectName}. It is not a * member of the `IDataDriver` contract. */ - public dateBucketSql(objectName: string, field: string, granularity: DateGranularityValue): string | null { + public dateBucketSql(objectName: string, field: string, granularity: DateGranularityValue, timezone?: string): string | null { // [#29520 codemod] The body moved to `sql-driver-class-head.ts` (see `ClassHeadHost`). - return ClassHeadFacet.dateBucketSql.call(classHeadHost.of(this), objectName, field, granularity); + return ClassHeadFacet.dateBucketSql.call(classHeadHost.of(this), objectName, field, granularity, timezone); } /** diff --git a/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts b/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts index 07faf3ac24d..45139d9a880 100644 --- a/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts +++ b/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts @@ -48,12 +48,19 @@ * `DRIVER_ROWS` is keyed by it (`satisfies Record`), * and a case asserts the key sets are equal, so a new builtin with no row * fails typecheck and this file. - * - **timezone class**: UTC, unset, and any other zone. No enum declares - * them; the engine's `tzRequiresInMemory` does, inline. `ZONE_CLASSES` - * declares each class's probes and the tier the engine gives it, and a - * case asserts that tier on a driver that groups every granularity, so a - * probe the engine moves to another class is red. `Etc/UTC` is a probe of - * the in-memory class: the engine treats only the literal `UTC` as UTC. + * - **timezone class**: UTC (and every name the runtime resolves to it), + * unset, an IANA area/location zone, and a zone that resolves to no + * area/location name. No enum declares them; the engine's + * `judgeBucketZone` does (objectql `engine-delete-and-aggregate.ts`). + * `ZONE_CLASSES` declares each class's probes and the tier the engine + * gives it, and a case asserts that tier on a driver that groups every + * granularity, so a probe the engine moves to another class is red. + * [#33697] `Etc/UTC` and `GMT` are probes of the UTC class: the engine + * reads the resolved name (review item d). An area/location zone is + * pushed down, zone included, on a driver declaring + * `supports.zonedDateBucketing` (PostgreSQL) and bucketed in memory on + * every other, and each face asserts which (ADR-0053 Phase 2 D2 as + * amended); `CST` is a probe of it, asked of the hook as `America/Chicago`. * - **granularity**: `TimeUpdateInterval.options`, the enum * `timeDimensions[].granularity` parses (derived from `DateGranularity`). * The rows are generated from it, so a new granularity has its cells the @@ -175,13 +182,28 @@ const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return q type Tier = 'pushdown' | 'in-memory'; -/** The timezone classes, each with its probes and the tier the engine gives a date bucket in it. */ -const ZONE_CLASSES: ReadonlyArray<{ label: string; probes: ReadonlyArray; tier: Tier }> = [ - { label: 'UTC', probes: ['UTC'], tier: 'pushdown' }, +/** + * The timezone classes, each with its probes and the tier the engine gives a + * date bucket in it on a driver that does not declare + * `supports.zonedDateBucketing`. `zoned` marks the class a driver declaring + * it takes down instead, with the zone (see {@link tierOn}). + */ +const ZONE_CLASSES: ReadonlyArray<{ label: string; probes: ReadonlyArray; tier: Tier; zoned?: true }> = [ + { label: 'UTC', probes: ['UTC', 'Etc/UTC', 'GMT'], tier: 'pushdown' }, { label: 'unset', probes: [undefined], tier: 'pushdown' }, - { label: 'any other zone', probes: ['Asia/Shanghai', 'America/New_York', 'Etc/UTC'], tier: 'in-memory' }, + { label: 'an area/location zone', probes: ['Asia/Shanghai', 'America/New_York', 'CST'], tier: 'in-memory', zoned: true }, + { label: 'no area/location name', probes: ['+08:00', 'EST5EDT'], tier: 'in-memory' }, ]; +/** The tier the engine gives `zoneClass` on a driver whose `supports` is `supports`. */ +const tierOn = (zoneClass: (typeof ZONE_CLASSES)[number], supports: unknown): Tier => + zoneClass.zoned && (supports as { zonedDateBucketing?: unknown } | undefined)?.zonedDateBucketing === true + ? 'pushdown' + : zoneClass.tier; + +/** The runtime's resolved name for `zone`, the one the engine and the echo push down. */ +const resolvedZone = (zone: string): string => new Intl.DateTimeFormat('en-US', { timeZone: zone }).resolvedOptions().timeZone; + /** The surface of a driver this pin reads: the engine's inputs and the bridges' inputs. */ interface EnumeratedDriver { readonly name: string; @@ -390,14 +412,16 @@ async function serve(face: DriverFace) { return Array.isArray(result) ? result : (result as { rows: unknown[] }).rows; }; - /** The driver's own answer for this bucket, as the bridge receives it. */ - const expression = (granularity: string): string | undefined => { + /** The driver's own answer for this bucket, as the bridge receives it (with the resolved zone for a zoned one). */ + const expression = (granularity: string, zone?: string): string | undefined => { if (typeof driver.dateBucketSql !== 'function') return undefined; - const answered = driver.dateBucketSql(DEAL, 'closed_at', granularity); + const answered = zone === undefined + ? driver.dateBucketSql(DEAL, 'closed_at', granularity) + : driver.dateBucketSql(DEAL, 'closed_at', granularity, zone); return typeof answered === 'string' && answered !== '' ? answered : undefined; }; - return { ask, expression, run, release: async () => { await face.release?.(driver); } }; + return { ask, expression, run, supports: driver.supports, release: async () => { await face.release?.(driver); } }; } describe('[#21647] the echo of a date bucket: driver x timezone class x granularity', () => { @@ -444,7 +468,15 @@ describe('[#21647] the echo of a date bucket: driver x timezone class x granular const { tiers, rows, querySql, dryRun } = await served.ask(granularity, probe); expect(tiers, 'the engine reached the driver exactly once').toHaveLength(1); const [tier] = tiers; - const expression = served.expression(granularity); + // [#33697] Which road the engine takes for this class on this + // driver, D2 as amended: a face whose granularities all push + // down takes a zoned class down only with the bit. + if (zoneClass.zoned && tierOn(zoneClass, served.supports) === 'pushdown') { + expect(tier, 'a driver declaring zonedDateBucketing groups the zone itself').toBe('pushdown'); + } else if (zoneClass.tier === 'in-memory') { + expect(tier, 'a zone this driver does not bucket stays in memory').toBe('in-memory'); + } + const expression = served.expression(granularity, zoneClass.zoned ? resolvedZone(probe!) : undefined); const printed = expression !== undefined && (tier === 'pushdown' || 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 e4860de4d06..6c394853dc2 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 @@ -36,17 +36,19 @@ * (`.github/workflows/ci.yml`), so the live cell is red-capable and runs in * CI. * - * [#21630] A non-UTC `timezone` makes the engine bucket on that zone's - * calendar: in the database on a driver that declares zone-aware bucketing - * (PostgreSQL, ADR-0053 Phase 2 D2 as amended for #33697) and in memory on - * every other, while the `dateBucketSql` hook renders the UTC bucket only. - * The echo refuses there on every dialect: `/analytics/sql` + * [#21630] A non-UTC `timezone` makes the engine bucket in memory on that + * zone's calendar on every driver but one declaring zone-aware bucketing + * ([#33697] PostgreSQL, ADR-0053 Phase 2 D2 as amended, which groups it in the + * database and whose zoned expression the echo then prints and runs). Where it + * is bucketed in memory no statement the database runs groups by those keys, + * and the echo refuses there: `/analytics/sql` * answers `NOT_IMPLEMENTED` / 501 as a declared refusal, and `/analytics/query` * serves the same rows with no `sql`. It used to print `date_trunc`, which * PostgreSQL 16.14 ran on the session zone's calendar (timestamp keys, and at - * `America/New_York` other groupings than the face's). The live cells pin it - * on SQLite and PostgreSQL, and the dialect matrix below pins it on SQLite, - * PostgreSQL and MySQL through each driver's own hooks, with no server. + * `America/New_York` other groupings than the face's). The live cells pin the + * refusal on SQLite and the zoned pushdown on PostgreSQL, and the dialect + * matrix below pins both on SQLite, PostgreSQL and MySQL through each driver's + * own hooks, with no server. * * [#21647] At UTC, where the hook answers nothing (a host that wires no hook, * or a driver that renders no expression), the echo refuses too, on every @@ -280,9 +282,29 @@ for (const cell of CELLS) { // memory" lived here. Its one input was SQLite `week`, and both cells now // group all three, so it had none left: `week` runs in the case above. - // [#21595, #21630] One rule on every cell. The PostgreSQL cell asserted - // `date_trunc('month', closed_at)` here, a statement the engine did not - // run: it buckets a non-UTC zone in memory. + // [#21595, #21630] One rule on every cell that buckets a non-UTC zone in + // memory. The PostgreSQL cell asserted `date_trunc('month', closed_at)` + // here, a statement the engine did not run. [#33697] Since ADR-0053 + // Phase 2 D2's amendment PostgreSQL declares `supports.zonedDateBucketing` + // and groups the zone in the database, so that cell has the case after + // this one, and this one is SQLite's. + if (cell.id === 'pg') { + it.each(ZONED)('[#33697] timezone %s, which PostgreSQL buckets in the database: the echo prints the zoned expression the driver ran, and it runs', async (timezone, rows) => { + const query = bucketed('closed_at', 'month', { timezone }); + const { res, ran } = await ask(query); + expect(ran.filter((sql) => /group by/i.test(sql)), 'the driver grouped once').toHaveLength(1); + // The database's buckets are the zone's calendar, the rows the + // in-memory path answers (D2's parity rule). + expect(tuples(res.rows, ['closed_at', 'amount_sum'])).toEqual(rows); + const zoned = driver.dateBucketSql(DEAL, 'closed_at', 'month', timezone); + expect(zoned, 'the driver renders the zoned bucket').toContain(`AT TIME ZONE '${timezone}'`); + const dryRun = await analytics.generateSql(query as any); + expect(selectedBucket(dryRun.sql, 'closed_at')).toBe(zoned); + expect(res.sql).toBe(dryRun.sql); + expect(tuples(await run(dryRun.sql, dryRun.params), ['closed_at', 'amount_sum'])).toEqual(rows); + }); + return; + } it.each(ZONED)('[#21630] REFUSAL: timezone %s, which the engine buckets in memory: the dry run refuses, and the query serves its rows with no `sql`', async (timezone, rows) => { const query = bucketed('closed_at', 'month', { timezone }); const { res, ran } = await ask(query); @@ -313,11 +335,13 @@ for (const cell of CELLS) { * driver is constructed and never connected: its `dialectName` and * `dateBucketSql` answer from the client config alone, so this runs with no * server. The context is wired with them as `AnalyticsServicePlugin` wires its - * `sqlDialect` and `dateBucketSql` hooks. The rows are not asked here: the - * engine buckets a non-UTC zone in memory whatever the dialect, and the live - * cells above pin them. + * `sqlDialect` and `dateBucketSql` hooks, zone included. The rows are not + * asked here; the live cells above pin them. [#33697] A non-UTC zone refuses + * where the engine buckets it in memory (SQLite, MySQL), and prints the zoned + * expression where the driver groups it (PostgreSQL, ADR-0053 Phase 2 D2 as + * amended). */ -describe('[#21630] the echo of a date bucket, per dialect: a non-UTC timezone refuses, and UTC keeps the driver\'s expression', () => { +describe('[#21630] the echo of a date bucket, per dialect: a non-UTC timezone refuses where it is bucketed in memory, and UTC keeps the driver\'s expression', () => { const DIALECT_CONFIGS = [ { dialect: 'sqlite', config: { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } }, { dialect: 'postgres', config: { client: 'pg', connection: { host: '127.0.0.1', database: 'unconnected' }, pool: { min: 0 } } }, @@ -336,8 +360,8 @@ describe('[#21630] the echo of a date bucket, per dialect: a non-UTC timezone re const ctx = { getCube: (name: string) => (name === CUBE ? CUBES[0] : undefined), sqlDialect: () => (driver as any).dialectName, - dateBucketSql: (object: string, field: string, granularity: string) => - driver.dateBucketSql(object, field, granularity as any) ?? undefined, + dateBucketSql: (object: string, field: string, granularity: string, timezone?: string) => + driver.dateBucketSql(object, field, granularity as any, timezone) ?? undefined, } as unknown as StrategyContext; it('names its dialect', () => { @@ -345,6 +369,15 @@ describe('[#21630] the echo of a date bucket, per dialect: a non-UTC timezone re }); for (const [timezone] of ZONED) { + if (dialect === 'postgres') { + it.each(['month', 'week'])(`timezone ${timezone}, %s: the driver's zoned expression`, async (granularity) => { + const { sql } = await new ObjectQLStrategy().generateSql(bucketed('closed_at', granularity, { timezone }) as any, ctx); + const expected = driver.dateBucketSql(DEAL, 'closed_at', granularity as any, timezone); + expect(expected, 'the driver renders the zoned bucket').toContain(`AT TIME ZONE '${timezone}'`); + expect(selectedBucket(sql, 'closed_at')).toBe(expected); + }); + continue; + } it.each(['month', 'week'])(`timezone ${timezone}, %s: refuses`, async (granularity) => { const err = await refusalOf(new ObjectQLStrategy().generateSql(bucketed('closed_at', granularity, { timezone }) as any, ctx)); expect([err.code, err.status, err.refusal]).toEqual(['NOT_IMPLEMENTED', 501, true]); @@ -352,6 +385,18 @@ describe('[#21630] the echo of a date bucket, per dialect: a non-UTC timezone re }); } + // [#33697] A zone the runtime resolves to no IANA area/location name is + // bucketed in memory on every driver, so the echo refuses it on every + // dialect, PostgreSQL included; a UTC alias is the UTC expression. + it.each(['+08:00', 'EST5EDT'])('timezone %s (no area/location name): refuses', async (timezone) => { + const err = await refusalOf(new ObjectQLStrategy().generateSql(bucketed('closed_at', 'month', { timezone }) as any, ctx)); + expect([err.code, err.status, err.refusal]).toEqual(['NOT_IMPLEMENTED', 501, true]); + }); + it.each(['Etc/UTC', 'GMT'])('timezone %s (resolves to UTC): the driver\'s UTC expression', async (timezone) => { + const { sql } = await new ObjectQLStrategy().generateSql(bucketed('closed_at', 'month', { timezone }) as any, ctx); + expect(selectedBucket(sql, 'closed_at')).toBe(driver.dateBucketSql(DEAL, 'closed_at', 'month')); + }); + for (const timezone of ['UTC', undefined]) { it.each(['month', 'week'])(`timezone ${timezone ?? 'unset'}, %s: the driver's own expression`, async (granularity) => { const { sql } = await new ObjectQLStrategy().generateSql( @@ -385,7 +430,7 @@ describe('[#21647] REFUSAL: a host that wires no dateBucketSql hook', () => { }, ); - it('[#21630] REFUSAL: with a non-UTC timezone, it refuses: the engine buckets that in memory whatever the host wires', async () => { + it('[#21630] REFUSAL: with a non-UTC timezone, it refuses: no hook, no expression to print, whichever road the engine takes', async () => { const ctx = { getCube: (name: string) => (name === CUBE ? CUBES[0] : undefined) } as unknown as StrategyContext; const err = await refusalOf(new ObjectQLStrategy().generateSql(bucketed('closed_on', 'month', { timezone: 'Asia/Shanghai' }) as any, ctx)); expect([err.code, err.status, err.refusal]).toEqual(['NOT_IMPLEMENTED', 501, true]); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index d82955f55f1..6322bf7d3e9 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -1305,12 +1305,17 @@ export interface AnalyticsServiceConfig { * `DatasetScopedStrategyContext.dateBucketSql` (`strategies/types.ts`). * * Answered by the plugin from the driver that executes the aggregate. Asked - * only at a UTC or unset `timezone`: a non-UTC one is bucketed in memory, and - * the echo refuses it whatever is wired (#21630). At UTC, where this answers - * `undefined` or is not wired, the echo refuses the bucket too, on every - * dialect (#21647): it prints a bucket in no expression but the driver's. + * with no zone at a UTC or unset `timezone` (or a name the runtime resolves + * to `UTC`), and with the resolved area/location name for a zone the engine + * may push down (#33697, ADR-0053 Phase 2 D2 as amended): the driver answers + * the zoned expression where it declares `supports.zonedDateBucketing`, and + * `undefined` where the engine buckets that zone in memory. A zone the + * runtime resolves to no area/location name is bucketed in memory on every + * driver, and the echo refuses it without asking (#21630). Where this + * answers `undefined` or is not wired, the echo refuses the bucket too, on + * every dialect (#21647): it prints a bucket in no expression but the driver's. */ - dateBucketSql?: (object: string, field: string, granularity: string) => string | undefined; + dateBucketSql?: (object: string, field: string, granularity: string, timezone?: string) => string | undefined; /** * [#19995, ruling C] The data engine's judge-only `where` admission, * `IObjectQLEngine.judgeFilter` (#20157): would the engine admit this diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index dfb07badb09..e6710bbe7db 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -117,7 +117,7 @@ type DialectNamingDriver = { readonly dialectName?: unknown }; * property of the SQL driver family, not of every driver. */ type DateBucketingDriver = { - dateBucketSql?(objectName: string, field: string, granularity: string): unknown; + dateBucketSql?(objectName: string, field: string, granularity: string, timezone?: string): unknown; }; /** @@ -1427,13 +1427,20 @@ export class AnalyticsServicePlugin implements Plugin { * the engine's in-memory bucketing (it answers `null`), a throw. On * `undefined` the echo refuses the bucket (#21647): it prints a bucket in * no expression but the one answered here. + * + * [#33697] `timezone`, when given, is the resolved area/location zone the + * engine pushes a zoned bucket down with; the driver answers the zoned + * expression it groups by, or nothing where it buckets no zone (the engine + * buckets that zone in memory there). */ - const dateBucketSql = (objectName: string, field: string, granularity: string): string | undefined => { + const dateBucketSql = (objectName: string, field: string, granularity: string, timezone?: string): string | undefined => { try { const svc = ctx.getService('data'); const driver = svc?.getDriverForObject?.(objectName) as DateBucketingDriver | undefined; if (typeof driver?.dateBucketSql !== 'function') return undefined; - const rendered = driver.dateBucketSql(objectName, field, granularity); + const rendered = timezone === undefined + ? driver.dateBucketSql(objectName, field, granularity) + : driver.dateBucketSql(objectName, field, granularity, timezone); return typeof rendered === 'string' && rendered !== '' ? rendered : undefined; } catch { return undefined; diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index 145efada32f..b2e523c6cb7 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -194,13 +194,15 @@ type BucketEchoRefusalCause = { zone: string } | { dialect: AnalyticsSqlDialect * at a UTC or unset `timezone`. Everything else refuses here, and the * refusal names its cause: * - * - [#21630] **A non-UTC `timezone`, on every driver.** The engine then - * buckets on that zone's calendar (ADR-0053 Phase 2 D2 as amended for - * #33697; `judgeBucketZone` and `tzRequiresInMemory` in objectql's - * `engine-delete-and-aggregate.ts`): in the database, with the zone bound, on - * a driver that declares `supports.zonedDateBucketing` (PostgreSQL), and in - * memory everywhere else. The `dateBucketSql` hook renders the UTC bucket - * only, so this echo has no expression for either road and refuses. The + * - [#21630] **A non-UTC `timezone` the engine buckets in memory.** The + * engine buckets it on that zone's calendar in JS (ADR-0053 Phase 2 D2; + * `tzRequiresInMemory` in objectql's `engine-delete-and-aggregate.ts`): the + * driver only fetches the rows, and no statement the database runs groups by + * those keys. [#33697] Since D2's amendment that is every driver but one + * declaring `supports.zonedDateBucketing` (PostgreSQL), and on that one a + * zone the runtime resolves to no IANA area/location name (`+08:00`, + * `EST5EDT`); for a resolved area/location zone there, the hook answers the + * zoned expression the database groups by and the echo prints it. The * `date_trunc('', col)` this used to print groups on the * database SESSION's calendar where it runs at all. Measured on PostgreSQL * 16.14 with the server at `Asia/Shanghai`, it answered timestamp keys such @@ -234,12 +236,13 @@ function bucketEchoRefused(dimension: string, granularity: string, cause: Bucket const err = new Error( `[analytics] cannot render display SQL for the "${granularity}" bucket of "${dimension}"` + ('zone' in cause - ? ` with timezone "${cause.zone}". The query itself is SERVED: the engine buckets it on that zone's ` + - `calendar, in the database where the driver declares zone-aware bucketing and in memory otherwise, ` + - `while this dry run renders only the UTC bucket expression. Refusing rather than printing one that ` + - `groups on another calendar. Run the query itself (/analytics/query) to get its rows; with timezone ` + - `"UTC" or none, this dry run renders the expression the driver groups the bucket by, where the driver ` + - `has one.` + ? ` with timezone "${cause.zone}". The query itself is SERVED: the engine buckets it in memory on that ` + + `zone's calendar, because this datasource's driver does not bucket that zone in the database, so no ` + + `statement the database runs groups by those bucket keys. (A driver that declares zone-aware ` + + `bucketing, such as PostgreSQL, does, for a zone the runtime resolves to an IANA area/location name, ` + + `and this dry run then prints its expression.) Refusing rather than printing one that groups on ` + + `another calendar. Run the query itself (/analytics/query) to get its rows; with timezone "UTC" or ` + + `none, this dry run renders the expression the driver groups the bucket by, where the driver has one.` : (cause.dialect === 'unknown' ? `: the driver behind this datasource names no SQL dialect and renders no expression for it. A ` + `driver that runs no SQL, such as the in-memory or MongoDB driver, buckets it without one: the ` + @@ -258,6 +261,34 @@ function bucketEchoRefused(dimension: string, granularity: string, cause: Bucket return err; } +/** + * [#33697] How the echo reads a query's `timezone` for its date buckets: the + * way `engine.aggregate` reads it (objectql `judgeBucketZone`, + * `engine-delete-and-aggregate.ts`; ADR-0053 Phase 2 D2 as amended), through + * the runtime's own resolution. Restated here because the engine's predicate + * is not reachable from this package; `objectql-echo-bucket-enumeration.test.ts` + * holds the two together. + * + * - `utc` — unset, empty, or a name that resolves to `UTC`. + * - `area` — resolves to an IANA area/location name (contains `/`), `zone` + * being that resolved name: pushed down to a driver declaring + * `supports.zonedDateBucketing`, in memory on every other. + * - `memory` — the runtime cannot resolve it, or it resolves to an offset or + * an abbreviation with no `/`: in memory on every driver. + */ +function echoBucketZone(timezone: string | undefined): + { kind: 'utc' } | { kind: 'area'; zone: string } | { kind: 'memory' } { + if (timezone === undefined || timezone === '' || timezone === 'UTC') return { kind: 'utc' }; + let resolved: string; + try { + resolved = new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone; + } catch { + return { kind: 'memory' }; + } + if (resolved === 'UTC') return { kind: 'utc' }; + return resolved.includes('/') ? { kind: 'area', zone: resolved } : { kind: 'memory' }; +} + /** One `engine.aggregate` group key: a column, or a column bucketed by a granularity. */ export type AggregateGroupKey = string | { field: string; dateGranularity: string }; @@ -799,10 +830,9 @@ export class ObjectQLStrategy implements AnalyticsStrategy { * and answers the face's bucket keys. [#21647] That expression is the only * thing a bucket is ever printed as. Where there is none, the echo refuses * ({@link bucketEchoRefused}), on every driver and every dialect: a non-UTC - * `timezone`, which the engine buckets on that zone's calendar, in the - * database on a driver declaring zone-aware bucketing and in memory - * otherwise, while the hook renders the UTC bucket only (#21630, #33697), - * and a hook that answers nothing at UTC, which is a driver that + * `timezone` the engine buckets in memory on that zone's calendar (#21630; + * since #33697 a driver declaring zone-aware bucketing answers the zoned + * expression for a resolved area/location zone, and it is printed), and a hook that answers nothing at UTC, which is a driver that * runs no SQL, a granularity the driver leaves to the engine, or a host that * wires no hook (#21595 was SQLite's case of it). No bucket expression is * written here. @@ -953,15 +983,17 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // (`no such function`), and PostgreSQL answers a timestamp where the face // answers `2026-01`. // - // Asked only for a UTC or unset `timezone`. The hook's expression is the - // UTC bucket. [#21630] A non-UTC zone makes the engine bucket on that - // zone's calendar instead (ADR-0053 Phase 2 D2 as amended for #33697): in - // the database with the zone bound on a driver that declares - // `supports.zonedDateBucketing`, in memory on every other. The hook renders - // neither, so the echo refuses on every dialect before the hook is asked - // ({@link bucketEchoRefused}). The test here is the raw string against - // `'UTC'`; the engine reads the runtime-resolved name, so a UTC alias such - // as `Etc/UTC` is served natively there and still refused here. + // [#33697] The zone is read as the engine reads it (`echoBucketZone`, + // ADR-0053 Phase 2 D2 as amended): a UTC or unset `timezone`, or a name + // the runtime resolves to `UTC` (`Etc/UTC`, `GMT`), asks the hook for the + // UTC bucket. [#21630] A zone that resolves to an IANA area/location name + // asks the hook WITH the resolved name: a driver declaring + // `supports.zonedDateBucketing` answers the zoned expression the database + // groups by, and every other driver answers nothing, because the engine + // buckets that zone in memory there — so the echo refuses, naming the + // zone. A zone that resolves to no area/location name is bucketed in + // memory on every driver, and the echo refuses it before the hook is asked + // ({@link bucketEchoRefused}). // // [#21647] Where the hook answers nothing at UTC, the echo refuses too, on // every dialect. That is the engine's other in-memory condition, read off @@ -980,9 +1012,12 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // `driver-turso`'s remote face (it advertises no granularity, and inherits // the SQLite expression, which libSQL runs). const zone = query.timezone; - const inMemoryZone = zone && zone !== 'UTC' ? zone : undefined; + const bucketZone = echoBucketZone(zone); + const hook = (ctx as DatasetScopedStrategyContext).dateBucketSql; const driverBucketSql = (col: string, granularity: string): string | undefined => { - const answered = (ctx as DatasetScopedStrategyContext).dateBucketSql?.(tableName, col, granularity); + const answered = bucketZone.kind === 'area' + ? hook?.(tableName, col, granularity, bucketZone.zone) + : hook?.(tableName, col, granularity); return typeof answered === 'string' && answered !== '' ? answered : undefined; }; const dimExpr = (dim: string): string => { @@ -996,9 +1031,13 @@ export class ObjectQLStrategy implements AnalyticsStrategy { const col = this.resolveFieldName(cube, dim, 'dimension'); const gran = gransByDim.get(dim)?.[0]; if (!gran) return col; - if (inMemoryZone !== undefined) throw bucketEchoRefused(dim, gran, { zone: inMemoryZone }); + if (bucketZone.kind === 'memory') throw bucketEchoRefused(dim, gran, { zone: zone! }); const bucket = driverBucketSql(col, gran); - if (bucket === undefined) throw bucketEchoRefused(dim, gran, { dialect: sqlDialectFor(ctx, tableName) }); + if (bucket === undefined) { + throw bucketZone.kind === 'area' && typeof hook === 'function' + ? bucketEchoRefused(dim, gran, { zone: zone! }) + : bucketEchoRefused(dim, gran, { dialect: sqlDialectFor(ctx, tableName) }); + } return bucket; }; diff --git a/packages/services/service-analytics/src/strategies/types.ts b/packages/services/service-analytics/src/strategies/types.ts index c8c1711a5d4..3d2fdd2c22c 100644 --- a/packages/services/service-analytics/src/strategies/types.ts +++ b/packages/services/service-analytics/src/strategies/types.ts @@ -215,8 +215,12 @@ export interface DatasetScopedStrategyContext extends StrategyContext { * on the spec's {@link StrategyContext} for the reason `declaredFieldType` * is: nothing about it is an authorable surface, and a strategy that does * not know the hook keeps the behaviour it had. + * + * [#33697] With `timezone` (a resolved IANA area/location name), the zoned + * expression a driver declaring `supports.zonedDateBucketing` groups by, or + * `undefined` where the driver buckets no zone. */ - dateBucketSql?(objectName: string, field: string, granularity: string): string | undefined; + dateBucketSql?(objectName: string, field: string, granularity: string, timezone?: string): string | undefined; /** * [#19995] The ENGINE's own `where` admission verdict for `objectName`, * `IObjectQLEngine.judgeFilter` (#20157), or `undefined` when the host From 5b7fb2b0945ec735dbf4be32f6e89b0187e6e604 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:02:50 +0000 Subject: [PATCH 07/12] test(service-analytics): the enumerated driver surface takes the zone argument (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .../src/__tests__/objectql-echo-bucket-enumeration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts b/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts index 45139d9a880..22f9ac15915 100644 --- a/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts +++ b/packages/services/service-analytics/src/__tests__/objectql-echo-bucket-enumeration.test.ts @@ -209,7 +209,7 @@ interface EnumeratedDriver { readonly name: string; readonly supports?: unknown; readonly dialectName?: unknown; - dateBucketSql?(objectName: string, field: string, granularity: string): unknown; + dateBucketSql?(objectName: string, field: string, granularity: string, timezone?: string): unknown; connect(): Promise; aggregate(...args: unknown[]): Promise; find(...args: unknown[]): Promise; From 03414032f18a089c3b5759f627724f9511d36b22 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:37:45 +0000 Subject: [PATCH 08/12] test(objectql): the zoned-dispatch cases type their aggregate options (#33697) Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .../src/engine-aggregate-timezone.test.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/engine-aggregate-timezone.test.ts b/packages/objectql/src/engine-aggregate-timezone.test.ts index ba11f4e6745..b0b3397984e 100644 --- a/packages/objectql/src/engine-aggregate-timezone.test.ts +++ b/packages/objectql/src/engine-aggregate-timezone.test.ts @@ -11,6 +11,7 @@ // last describe block pins that dispatch, spelling by spelling. import { describe, it, expect } from 'vitest'; +import type { EngineAggregateOptions } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; /** @@ -112,6 +113,12 @@ describe('engine.aggregate timezone routing (ADR-0053 Phase 2)', () => { // request's string to, and only an area/location name; review items (d) and // (e) on the card name the spellings. describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => { + const zonedDayBucket = (timezone: string): EngineAggregateOptions => ({ + groupBy: [{ field: 'closed_at', dateGranularity: 'day' }], + aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }], + timezone, + }); + async function makeZonedEngine(zoned: boolean | undefined) { const received: any[] = []; let findCalls = 0; @@ -153,7 +160,7 @@ describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => ['Etc/GMT+5', 'Etc/GMT+5'], ])('pushes %s down as the resolved name %s', async (asked, sent) => { const { engine, received, finds } = await makeZonedEngine(true); - await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + await engine.aggregate('deal', zonedDayBucket(asked)); expect(finds()).toBe(0); expect(received).toHaveLength(1); expect(received[0].timezone).toBe(sent); @@ -161,7 +168,7 @@ describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => it.each(['UTC', 'Etc/UTC', 'GMT', 'Zulu'])('reads %s as the UTC bucket: native, no zone sent', async (asked) => { const { engine, received, finds } = await makeZonedEngine(true); - await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + await engine.aggregate('deal', zonedDayBucket(asked)); expect(finds()).toBe(0); expect(received).toHaveLength(1); expect('timezone' in received[0]).toBe(false); @@ -169,14 +176,14 @@ describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => it.each(['EST5EDT', '+08:00', 'Bogus/Zone'])('keeps %s in memory: it resolves to no area/location name', async (asked) => { const { engine, received, finds } = await makeZonedEngine(true); - await engine.aggregate('deal', { ...dayBucket, timezone: asked } as any); + await engine.aggregate('deal', zonedDayBucket(asked)); expect(received).toHaveLength(0); expect(finds()).toBe(1); }); it.each([false, undefined])('keeps a non-UTC zone in memory on a driver whose bit is %s', async (bit) => { const { engine, received, finds } = await makeZonedEngine(bit); - await engine.aggregate('deal', { ...dayBucket, timezone: 'Asia/Taipei' } as any); + await engine.aggregate('deal', zonedDayBucket('Asia/Taipei')); expect(received).toHaveLength(0); expect(finds()).toBe(1); }); @@ -187,7 +194,7 @@ describe('engine.aggregate zoned-bucket pushdown (#33697, D2 as amended)', () => groupBy: ['closed_at'], aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }], timezone: 'Asia/Taipei', - } as any); + } satisfies EngineAggregateOptions); expect(received).toHaveLength(1); expect('timezone' in received[0]).toBe(false); }); From 9f3caa4e3bdface5e4089b38b9143fc5450cb53f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:13:56 +0000 Subject: [PATCH 09/12] chore(changeset): declare Metadata-protocol added and grade @objectstack/spec minor The new DriverCapabilities key zonedDateBucketing moves the authorable-surface data shard, which the Check Changeset ratchet reads as a key added. Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .changeset/33697-pg-zoned-date-bucketing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/33697-pg-zoned-date-bucketing.md b/.changeset/33697-pg-zoned-date-bucketing.md index e01ff4b44d7..b55813bcfa0 100644 --- a/.changeset/33697-pg-zoned-date-bucketing.md +++ b/.changeset/33697-pg-zoned-date-bucketing.md @@ -1,12 +1,12 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/driver-sql': patch '@objectstack/objectql': patch '@objectstack/service-analytics': patch --- Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added — `supports.zonedDateBucketing` is a new key a driver author can write on `DriverCapabilities` (`DriverConfig.capabilities`), recorded in `packages/spec/authorable-surface/data.json`. PostgreSQL now buckets a non-UTC reference timezone in the database (ADR-0053 Phase 2 D2 as amended). A dashboard grouped by day, week, month, quarter or year in a zone such as `Asia/Taipei` or `Europe/Berlin` no longer pulls every scoped row into the application on PostgreSQL: the bucket is computed by `to_char((col)::timestamptz AT TIME ZONE $zone, …)` with the zone bound, DST-correct, and its labels equal the in-memory ones. A `Field.date` keeps its calendar day under every zone. From 2b76c7f405fee016617341186ed615f4957d16e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:14:52 +0000 Subject: [PATCH 10/12] chore(changeset): add the Skills-docs line beside Metadata-protocol added Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .changeset/33697-pg-zoned-date-bucketing.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/33697-pg-zoned-date-bucketing.md b/.changeset/33697-pg-zoned-date-bucketing.md index b55813bcfa0..0309755811b 100644 --- a/.changeset/33697-pg-zoned-date-bucketing.md +++ b/.changeset/33697-pg-zoned-date-bucketing.md @@ -7,6 +7,7 @@ Clause-②: yes (widening) Metadata-protocol: added — `supports.zonedDateBucketing` is a new key a driver author can write on `DriverCapabilities` (`DriverConfig.capabilities`), recorded in `packages/spec/authorable-surface/data.json`. +Skills-docs: none — no skill under `skills/**` teaches driver capability bits or where a zoned date bucket runs; the bit is read by the engine, and an app author writes the same `timezone` as before. PostgreSQL now buckets a non-UTC reference timezone in the database (ADR-0053 Phase 2 D2 as amended). A dashboard grouped by day, week, month, quarter or year in a zone such as `Asia/Taipei` or `Europe/Berlin` no longer pulls every scoped row into the application on PostgreSQL: the bucket is computed by `to_char((col)::timestamptz AT TIME ZONE $zone, …)` with the zone bound, DST-correct, and its labels equal the in-memory ones. A `Field.date` keeps its calendar day under every zone. From a7761658139140e45ab09b913e632b99385f6ed3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:31:00 +0000 Subject: [PATCH 11/12] docs(spec,service-analytics): state the non-declaring driver's refusal, the runtime-relative spellings and the hook's no-UTC answer Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- packages/services/service-analytics/src/strategies/types.ts | 4 +++- packages/spec/src/contracts/data-driver.ts | 5 ++++- packages/spec/src/data/data-engine.zod.ts | 4 +++- packages/spec/src/data/driver.zod.ts | 4 +++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/services/service-analytics/src/strategies/types.ts b/packages/services/service-analytics/src/strategies/types.ts index 3d2fdd2c22c..ef7143f7245 100644 --- a/packages/services/service-analytics/src/strategies/types.ts +++ b/packages/services/service-analytics/src/strategies/types.ts @@ -218,7 +218,9 @@ export interface DatasetScopedStrategyContext extends StrategyContext { * * [#33697] With `timezone` (a resolved IANA area/location name), the zoned * expression a driver declaring `supports.zonedDateBucketing` groups by, or - * `undefined` where the driver buckets no zone. + * `undefined` where the driver buckets no zone. An implementer that does not + * bucket the zone it is asked for answers `undefined`, never its UTC + * expression: the echo would print a statement grouped on the wrong calendar. */ dateBucketSql?(objectName: string, field: string, granularity: string, timezone?: string): string | undefined; /** diff --git a/packages/spec/src/contracts/data-driver.ts b/packages/spec/src/contracts/data-driver.ts index 13ec284fe8c..a25f7adfe3b 100644 --- a/packages/spec/src/contracts/data-driver.ts +++ b/packages/spec/src/contracts/data-driver.ts @@ -66,7 +66,10 @@ export type DriverQuery = Omit; * which is the bucket a driver answers when the key is absent. A driver that * reads it buckets an instant column on that zone's calendar, DST-correct, * keeps a `Field.date` on its own calendar day, and refuses a zone it cannot - * bucket rather than reading it as UTC. + * bucket rather than reading it as UTC. A driver that does NOT declare the bit + * is never sent the key by the engine; handed one by a direct caller, it + * refuses the zone the same way (driver-sql: `NOT_IMPLEMENTED` / 501) rather + * than answering the UTC bucket. * * Kept off {@link DriverQuery} on purpose: `find()` / `count()` take that type * and no zone means anything to them, so a key they would silently drop is not diff --git a/packages/spec/src/data/data-engine.zod.ts b/packages/spec/src/data/data-engine.zod.ts index 09603b6281e..fc6e6e404c9 100644 --- a/packages/spec/src/data/data-engine.zod.ts +++ b/packages/spec/src/data/data-engine.zod.ts @@ -510,7 +510,9 @@ export const EngineAggregateOptionsSchema = lazySchema(() => BaseEngineOptionsSc * the RESOLVED area/location name (`CST` goes down as `America/Chicago`), * and in memory otherwise — and always in memory for a string the runtime * cannot resolve or that resolves to no area/location name (`+08:00`, - * `EST5EDT`). Both paths answer the same buckets (D2 as amended). + * `EST5EDT`). Both paths answer the same buckets (D2 as amended). The + * spellings are examples as Node 22 resolves them; the rule is the + * runtime's resolution. */ timezone: z.string().optional(), /** diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 190f4d17db1..828b7a28d18 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -358,7 +358,9 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ * (no bit, a name the runtime cannot resolve, an offset such as `+08:00`, * an abbreviation that resolves to itself such as `EST5EDT`) keeps the * in-memory aggregate (`applyInMemoryAggregation`), which answers it as it - * always has. The raw string never reaches a driver. + * always has. The raw string never reaches a driver. Which spelling + * resolves to what is the runtime's tz data (the examples are as Node 22 + * resolves them); the rule is the resolution, not the list. * * What a driver that declares it owes: its buckets equal the in-memory * buckets (`bucketDateKey` in `@objectstack/core`) for that zone, on both From f9fa972988f4479ec681d3d56650ff957d73a428 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:55:52 +0000 Subject: [PATCH 12/12] chore(changeset): point the Skills-docs line at its follow-up card Claude-Session: https://claude.ai/code/session_01ADHkmPeEPFrWJ9cBKVtYb6 Co-authored-by: Claude --- .changeset/33697-pg-zoned-date-bucketing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/33697-pg-zoned-date-bucketing.md b/.changeset/33697-pg-zoned-date-bucketing.md index 0309755811b..7ecd8fbc1e9 100644 --- a/.changeset/33697-pg-zoned-date-bucketing.md +++ b/.changeset/33697-pg-zoned-date-bucketing.md @@ -7,7 +7,7 @@ Clause-②: yes (widening) Metadata-protocol: added — `supports.zonedDateBucketing` is a new key a driver author can write on `DriverCapabilities` (`DriverConfig.capabilities`), recorded in `packages/spec/authorable-surface/data.json`. -Skills-docs: none — no skill under `skills/**` teaches driver capability bits or where a zoned date bucket runs; the bit is read by the engine, and an app author writes the same `timezone` as before. +Skills-docs: follow-up #34597 PostgreSQL now buckets a non-UTC reference timezone in the database (ADR-0053 Phase 2 D2 as amended). A dashboard grouped by day, week, month, quarter or year in a zone such as `Asia/Taipei` or `Europe/Berlin` no longer pulls every scoped row into the application on PostgreSQL: the bucket is computed by `to_char((col)::timestamptz AT TIME ZONE $zone, …)` with the zone bound, DST-correct, and its labels equal the in-memory ones. A `Field.date` keeps its calendar day under every zone.