Skip to content

Commit 49c8e0f

Browse files
fix(driver-turso): remote aggregate group keys over a boolean answer true/false (#37152)
Fixes #37133 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:托管云(远程 libSQL 连接)上的报表、图表和问数按「是否完成」这类布尔字段分组时,分组值显示为 是/否(true/false),不再显示 1/0,和本地运行一致。 - 为什么做:托管云的驱动在分组统计时漏掉了普通读取已有的值转换,同一份数据在两种连接方式下答案不同。 - 出错会怎样:只影响分组统计返回的分组值写法,计数和合计不变;如有问题可直接撤回此改动,数据本身不受影响。 - 要你做什么:无。 ## What changes `TursoDriver.aggregate` on its remote face (`libsql://`, `https://`, `http://` URLs, the hosted construction) returned the libSQL transport's raw columns, so a group over a declared boolean answered `1` / `0` / `null` where the local face answers `true` / `false` / `null`. The remote branch now presents its group-key columns through the two inherited members the local face uses, `readPresentationKind` and `presentReadColumns` (driver-sql), keyed by the output column (`alias ?? field`), with the registries keyed by object name as remote `find()` and remote `distinct()` already read them. Every kind the shared presenter covers (boolean, date, time, datetime, audit timestamps, number) is presented the same way. Measures are not touched: counts and totals are numbers from libSQL already, and `min` / `max` over a boolean stay `0` / `1` (the ruled numeric aggregation domain, `SqlDriver.aggregate` [#11152]). Other remote grouped or projected reads checked for the same gap: - `distinct()` already presents its values (`readPresentationKind` + `presentReadValue`), so no change; the new suite pins it on the real engine. - `find()` / `findOne()` / `bulkUpdate()` / `create()` / `update()` / `upsert()` already go through `formatRemoteRow(s)`. - Window reads and query plans are refused on the remote face; the remaining raw `execute` calls are catalog and sequence reads, not object rows. First files to read, by risk: 1. `packages/drivers/driver-turso/src/turso-driver.ts`: the `aggregate()` remote branch and the new `presentRemoteGroupKeys` (the one behavioural hunk). 2. `packages/drivers/driver-turso/src/remote-aggregate-group-key-presentation.test.ts`: the acceptance suite on the real libSQL engine. Two-minute verification: `pnpm --filter @objectstack/driver-turso exec vitest run --maxWorkers=2 src/remote-aggregate-group-key-presentation.test.ts` answers 4/4 green; on `origin/main` the same file answers 3 failed, with `done: 0` / `done: 1` where `false` / `true` are expected. ## Tests New `remote-aggregate-group-key-presentation.test.ts`, every case on the REAL libSQL engine (`@libsql/client` over `file::memory:`, behind the remote face; not the better-sqlite3 stub): - a boolean group key answers `true` / `false` / `null`; - an aliased structured key (`{ field: 'done', alias: 'is_done' }`) is presented under the name the row carries; - the remote answer equals the local face's on the same data for five queries: boolean key, aliased key with `sum`, boolean + date keys, a number key, and `max` / `min` over the boolean (measures); - `distinct('done')` answers JSON booleans on both faces. <details><summary>Readings (final head d6e5f6c)</summary> - Before the fix (`origin/main` source, new test file only): `Tests 3 failed | 1 passed (4)`; the diff reads `- "done": false` / `+ "done": 0`, `- "done": true` / `+ "done": 1`. - After: `Tests 4 passed (4)`. - Package at d6e5f6c: `pnpm --filter @objectstack/driver-turso typecheck && test` (lock VERDICT command-exit 0): `Test Files 104 passed | 1 skipped (105)`, `Tests 2652 passed | 36 skipped (2688)`. `tsc --noEmit --listFiles` includes the new test file (count 1). - Derived gate families at d6e5f6c (`dispatch-gates.mjs --commands`): 69 run, each exit captured before any pipe; `--ran` reconciliation: `69 derived, 69 run, 0 NOT-MEASURED, 0 UNRUN`. 68 exited 0 on the first pass; `check-plugin-teardown-shape.mjs --self-test` exited 3 because its pinned positive-control commit was absent from this shallow clone, and exited 0 (`48 cases pass`) once that one commit was fetched. `check-nul-bytes`: OK. The wider CI families are CI's. - Ablation, one time, committed fix first: `scripts/ablation-replace.mjs` replaced `return this.presentReadColumns(rows, columns);` with `return rows;` (anchor 1 to 0, blob efbc1cc to c8375a638b14), the suite answered `Tests 3 failed | 1 passed (4)` (the three group-key cases red, the `distinct` case green as expected), and the restore read blob == HEAD (efbc1cc), `git diff HEAD` empty. The test imports `./turso-driver.js` from source, so no build sits in that path. </details> ## Acceptance notes - The card names the HTTP door as `/api/v1/data/:object/aggregate`. That path is not a route on this platform: on a booted server it falls into `GET /data/:object/:id` and answers `405 METHOD_NOT_ALLOWED` for POST (`Allowed: DELETE, GET, HEAD, PATCH`) and `400 VALIDATION_ERROR` for GET with `groupBy` (`Supported parameters: expand, select`). The aggregate door over HTTP is `POST /api/v1/data/:object/query` with `groupBy` / `aggregations` in the body (`packages/rest/src/crud-routes.ts`), which is what was checked below. - Not measured: `min` / `max` over a temporal column whose stored value is NOT canonical (a legacy epoch integer). The local face presents that through the column's temporal kind and the remote face does not, so the two could disagree there. On canonical storage they agree (measured: `max(due)` and `min(at)` over a `date` and a `datetime` read the same on both faces). Left as dispatched ("measures stay untouched"). - The hosted-shaped boot used a scratch Hrana v2 shim (below); its batch handling made the boot log `Batch schema sync failed, falling back to sequential` twice. That is the shim's, not the product's; the sequential sync completed and the server served. ## Verification HTTP door on a hosted-shaped boot. No `sqld` here (not installed, GitHub release downloads refused by the proxy, no Docker daemon), so what ran instead: 1. A scratch Hrana v2 JSON-pipeline server (about 100 lines, not committed) over the native `libsql` 0.5.29 engine on a `file` database, on 127.0.0.1. 2. `pnpm dev -- --fresh -p PORT --database 'libsql://127.0.0.1:SHIMPORT?tls=0'` (the CLI accepts `libsql://`, and `@libsql/client` reads `tls=0` as plain HTTP). The boot printed `Driver: TursoDriver(libsql) → libsql://127.0.0.1:SHIMPORT`, the remote face, with the showcase seed in place (`showcase_task.done`: 8 false, 2 true by `find()`). 3. Signed in as the seeded admin and sent `POST /api/v1/data/showcase_task/query` with `{"groupBy":["done"],"aggregations":[{"function":"count","alias":"c"}]}`. <details><summary>HTTP readings, same database across all three boots</summary> - Fixed build: `200 {"records":[{"done":false,"c":8},{"done":true,"c":2}],"total":2}`; aliased key `{"field":"done","alias":"is_done"}`: `200 {"records":[{"is_done":false,"c":8},{"is_done":true,"c":2}]}`. - Before leg: the presenter call ablated in source, driver-turso rebuilt, `ablation-dist-preflight` read the marker present in 2 built files, server restarted on the same database: `200 {"records":[{"done":0,"c":8},{"done":1,"c":2}]}`. This proves the HTTP door reaches this code with nothing upstream presenting the key. - Restore leg: source restored (blob == HEAD, `git status --porcelain` empty), rebuilt, preflight `--absent` read the marker absent from all 6 built files and the tree clean, server restarted: `200 {"records":[{"done":false,"c":8},{"done":true,"c":2}]}`. </details> Dispatched by: maintainer · os-bob · session_012dn2AecKpLaYkUtNRiqtby --- _Generated by [Claude Code](https://claude.ai/code/session_012dn2AecKpLaYkUtNRiqtby)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e792da commit 49c8e0f

3 files changed

Lines changed: 187 additions & 2 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/driver-turso': patch
3+
---
4+
5+
fix(driver-turso): remote aggregate group keys over a boolean answer true/false, as local mode does
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On the remote face of `TursoDriver` (a `libsql://`, `https://` or `http://` database, as hosted environments use), `aggregate()` returned group-key columns exactly as the libSQL client hands them back. A group over a declared boolean field came back as `1` / `0` (and `null`), where the local and replica faces answer `true` / `false` / `null`. Reports, charts and `aggregate_records` grouped by a field such as "done" showed `0` / `1` on a hosted environment.
11+
12+
Group-key columns now take the same read presentation `find()` applies to the column, keyed by the output column (`alias ?? field`), exactly as the local face does. Other declared kinds the shared presenter covers (date, time, datetime, audit timestamps, numbers) are presented the same way. Measures are unchanged: counts and totals are numbers as before, and `min` / `max` over a boolean still answer `0` / `1`.
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#37133] A group key on the remote face is presented as `find()` presents
5+
* the same column, and the grouped answer equals the local face's.
6+
*
7+
* `RemoteTransport.aggregate` hands back raw libSQL columns: a declared boolean
8+
* is the stored `1` / `0`. The local face presents every group key through the
9+
* one read presenter (`SqlDriver.presentReadColumns`), so one grouped query
10+
* answered `true` / `false` locally and `1` / `0` on a hosted environment.
11+
*
12+
* Every pin here runs on the REAL libSQL engine (`@libsql/client` over
13+
* `file::memory:`) behind the remote face, never the better-sqlite3 stub: the
14+
* defect is what the real client hands back, so a stub would only pin itself.
15+
* Measures are not presented by this fix and are pinned unchanged: a count is a
16+
* number on both faces, and `min` / `max` over a boolean stay `0` / `1` (the
17+
* ruled numeric aggregation domain, `SqlDriver.aggregate` [#11152]).
18+
*/
19+
20+
import { describe, it, expect, afterEach } from 'vitest';
21+
import { createClient } from '@libsql/client';
22+
import { TursoDriver } from './turso-driver.js';
23+
24+
type Row = Record<string, unknown>;
25+
26+
const TASK = {
27+
name: 'os37133_task',
28+
fields: {
29+
title: { type: 'text' },
30+
done: { type: 'boolean' },
31+
due: { type: 'date' },
32+
points: { type: 'number' },
33+
},
34+
};
35+
36+
const ROWS: Row[] = [
37+
{ title: 'a', done: true, due: '2026-01-05', points: 3 },
38+
{ title: 'b', done: true, due: '2026-01-05', points: 5 },
39+
{ title: 'c', done: false, due: '2026-02-10', points: 3 },
40+
{ title: 'd', done: null, due: null, points: null },
41+
];
42+
43+
/** A fresh copy per sync: neither face may see a definition the other one mutated. */
44+
const fresh = () => ({
45+
...TASK,
46+
fields: Object.fromEntries(Object.entries(TASK.fields).map(([k, v]) => [k, { ...v }])),
47+
});
48+
49+
const cleanups: Array<() => Promise<void>> = [];
50+
afterEach(async () => {
51+
for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
52+
});
53+
54+
async function seed(driver: TursoDriver): Promise<TursoDriver> {
55+
await driver.connect();
56+
cleanups.push(() => driver.disconnect());
57+
await driver.initObjects([fresh()] as never);
58+
for (const row of ROWS) await driver.create(TASK.name, { ...row });
59+
return driver;
60+
}
61+
62+
const localFace = async () => {
63+
const driver = await seed(new TursoDriver({ url: ':memory:' }));
64+
expect(driver.transportMode).toBe('local');
65+
return driver;
66+
};
67+
68+
const remoteFace = async () => {
69+
const client = createClient({ url: 'file::memory:' });
70+
const driver = await seed(new TursoDriver({ url: 'libsql://group-key-presentation.turso.io', client }));
71+
expect(driver.transportMode).toBe('remote');
72+
return driver;
73+
};
74+
75+
/** Order-independent comparison: neither face promises a group order. */
76+
const sorted = (rows: Row[]) => [...rows].sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
77+
78+
describe('[#37133] remote aggregate presents its group keys as find() does', () => {
79+
it('a boolean group key answers true / false / null, never 1 / 0', async () => {
80+
const remote = await remoteFace();
81+
const rows = await remote.aggregate(TASK.name, {
82+
groupBy: ['done'],
83+
aggregations: [{ function: 'count', alias: 'c' }],
84+
} as never);
85+
expect(sorted(rows)).toEqual(sorted([
86+
{ done: null, c: 1 },
87+
{ done: false, c: 1 },
88+
{ done: true, c: 2 },
89+
]));
90+
});
91+
92+
it('an aliased structured group key is presented under the name the row carries', async () => {
93+
const remote = await remoteFace();
94+
const rows = await remote.aggregate(TASK.name, {
95+
groupBy: [{ field: 'done', alias: 'is_done' }],
96+
aggregations: [{ function: 'count', alias: 'c' }],
97+
} as never);
98+
expect(sorted(rows)).toEqual(sorted([
99+
{ is_done: null, c: 1 },
100+
{ is_done: false, c: 1 },
101+
{ is_done: true, c: 2 },
102+
]));
103+
});
104+
105+
it('the remote answer equals the local answer on the same data', async () => {
106+
const local = await localFace();
107+
const remote = await remoteFace();
108+
const queries = [
109+
{ groupBy: ['done'], aggregations: [{ function: 'count', alias: 'c' }] },
110+
{ groupBy: [{ field: 'done', alias: 'is_done' }], aggregations: [{ function: 'sum', field: 'points', alias: 'total' }] },
111+
{ groupBy: ['done', 'due'], aggregations: [{ function: 'count', alias: 'c' }] },
112+
{ groupBy: ['points'], aggregations: [{ function: 'count', alias: 'c' }] },
113+
// Measures: a boolean aggregand stays in the ruled numeric domain on both faces.
114+
{ groupBy: ['due'], aggregations: [{ function: 'max', field: 'done', alias: 'any_done' }, { function: 'min', field: 'done', alias: 'all_done' }] },
115+
];
116+
for (const query of queries) {
117+
const want = await local.aggregate(TASK.name, query as never);
118+
const got = await remote.aggregate(TASK.name, query as never);
119+
expect(sorted(got), JSON.stringify(query)).toEqual(sorted(want));
120+
}
121+
// The ruled numeric answer is what both faces agree on, not a shared presentation slip.
122+
const measured = await remote.aggregate(TASK.name, queries[4] as never);
123+
expect(measured.map((r) => r.any_done).filter((v) => v !== null).every((v) => v === 0 || v === 1)).toBe(true);
124+
});
125+
126+
it('distinct over the boolean answers the presented values on both faces', async () => {
127+
const local = await localFace();
128+
const remote = await remoteFace();
129+
const want = await local.distinct(TASK.name, 'done');
130+
const got = await remote.distinct(TASK.name, 'done');
131+
expect([...got].map(String).sort()).toEqual([...want].map(String).sort());
132+
expect(got.filter((v) => v !== null).every((v) => typeof v === 'boolean')).toBe(true);
133+
});
134+
});

‎packages/drivers/driver-turso/src/turso-driver.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3314,13 +3314,52 @@ export class TursoDriver extends SqlDriver {
33143314
// [#21226] The rows are narrowed to the caller's tenant scope before they
33153315
// are grouped, as `SqlDriver.aggregate` scopes its builder.
33163316
const scope = this.remoteTenantScope(object, options);
3317-
return this.remoteReadExit(object, query, () =>
3318-
this.remoteTransport!.aggregate(object, this.toRemoteQuery(object, query, options), table, scope),
3317+
return this.presentRemoteGroupKeys(
3318+
object,
3319+
query,
3320+
await this.remoteReadExit(object, query, () =>
3321+
this.remoteTransport!.aggregate(object, this.toRemoteQuery(object, query, options), table, scope),
3322+
),
33193323
);
33203324
}
33213325
return super.aggregate(object, query, options);
33223326
}
33233327

3328+
/**
3329+
* [#37133] Present the group-key columns of a remote `aggregate()` answer
3330+
* with the presenter `find()` applies to the same column, so a group over a
3331+
* declared boolean answers `true` / `false`, never the stored `1` / `0`.
3332+
*
3333+
* The remote transport hands back raw libSQL columns, and the local face of
3334+
* this driver presents every group key through `SqlDriver.presentReadColumns`
3335+
* (keyed by the OUTPUT column, `alias ?? field`, with the kind
3336+
* `readPresentationKind` gives the FIELD). This applies those same two
3337+
* inherited members, so the faces cannot disagree on what a group key is.
3338+
* The presentation registries are keyed by object name on this face, as
3339+
* {@link formatRemoteRow} and `distinct()` read them.
3340+
*
3341+
* Measures are deliberately left as the transport answers them: a count or a
3342+
* total is already a number from libSQL, and `min` / `max` over a boolean are
3343+
* the ruled numeric domain (`SqlDriver.aggregate` [#11152]). A date-bucketed
3344+
* key never reaches here — the transport refuses it before anything is read.
3345+
*/
3346+
private presentRemoteGroupKeys(
3347+
object: string,
3348+
query: DriverQuery,
3349+
rows: Record<string, unknown>[],
3350+
): Record<string, unknown>[] {
3351+
const groupBy = Array.isArray(query?.groupBy) ? query.groupBy : [];
3352+
const columns = new Map(
3353+
groupBy.flatMap((g) => {
3354+
const field = typeof g === 'string' ? g : g?.field;
3355+
if (typeof field !== 'string') return [];
3356+
const kind = this.readPresentationKind(object, field);
3357+
return kind ? [[typeof g === 'string' ? g : (g.alias ?? field), kind] as const] : [];
3358+
}),
3359+
);
3360+
return this.presentReadColumns(rows, columns);
3361+
}
3362+
33243363
// ===================================
33253364
// Remote read-coercion helpers
33263365
// ===================================

0 commit comments

Comments
 (0)