Skip to content

Commit 23c42c4

Browse files
objectstack-fleet[bot]claudeos-support-ai
authored
fix(driver-sql): boot converges legacy text booleans on SQLite to 1 / 0 (#35076)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBLW6dHPW6sSheA32XPKZzPV)_ repo:objectstack#3 · os-support-ai · session_01WGufzg2evNa1V3zxrQq3KX Closes #34973 Clause-②: yes (widening: `@objectstack/driver-sql` exports `PendingSchemaWorkKind` from its index, and the CLI consumes it, so the union gains one published value, `normalize_boolean_storage`; boolean filters, sorts and groupBy on SQLite now answer legacy text rows as their boolean) Metadata-protocol: none ## 维护者速读 - **改了什么**:SQLite 上布尔/开关字段里旧版本留下的文本 `'true'` / `'false'`,启动时的 schema sync 会把它们改写成 `1` / `0`(第四个存储收敛步骤,和 datetime、time、JSON 回填并列);`os migrate plan` 会把这一步列成 `normalize_boolean_storage` 并给出行数。 - **为什么改**:这些旧行读出来是对的布尔值,但筛选 `= false`、`$in`、`!=`、`$nin`、排序和分组都拿原始文本去比,结果漏行或分错组(文本 `'false'` 在分组里显示成 true)。 - **风险与回滚**:每列一条带守卫的 `UPDATE`,只改这两个文本拼法,其他文本只计数和告警、绝不改写;第二次启动改写 0 行。没有回滚步骤,因为改写后语义不变,撤回只会恢复有缺陷的形态;回滚代码即可停止该步骤,已改写的行无需还原。 - **先看**:`packages/drivers/driver-sql/src/sql-driver-schema-sync.ts`(`backfillCanonicalBooleans` 的计数/采样/UPDATE 与 `previewBooleanConvergence`)、`packages/drivers/driver-sql/src/sql-driver-rotation.ts`(`initObjects` 里新增的一次调用)、`packages/cli/src/utils/schema-migrate.ts`(摘要行措辞)。 - **两分钟验证**:`pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-34916-boolean-text-read.test.ts`,预期 23 个测试全部通过。 - **需要你做的**:无,席位落地(L1-d 后由席位做 L2 契约复审)。 ## Premise (measured, wider than filed) Measured on `origin/main` `4443014630c` in the premise report on #34973 and restated in the claim amendment; nothing here goes beyond those measurements. - Only SQLite can hold text booleans, and only as `'true'` / `'false'`: the column's NUMERIC affinity folds the text `'1'` / `'0'` into integers and keeps `'true'` / `'false'` as TEXT. Postgres, MSSQL, MySQL and Oracle coerce or refuse the text (code reading; no rig in this container). - The card named `=` only. On those rows `=`, `$in`, `!=` and `$nin` all answer wrongly at the driver, the engine and the REST door; ORDER BY sorts them after every integer; aggregate groupBy presents a text `'false'` as true. - The engine cannot address the rows (a read presents them as booleans, and a `'false'` comparand narrows to `false`), so the fix is raw SQL in the driver. ## What changes - `sql-driver-schema-sync.ts`: `backfillCanonicalBooleans`, the fourth driver storage convergence. SQLite only, for an existing table's scalar `Field.boolean` / `Field.toggle` columns. Per column: one counting scan over the column's text cells sorts them into legacy `'true'` / `'false'` and other text. Only when the scan finds legacy text does the step take an id sample (up to 5) and run ONE `UPDATE … set col = case col when 'true' then 1 when 'false' then 0 end where typeof(col) = 'text' and col in ('true', 'false')`. The count, the sample, the `UPDATE` and the preview all read one shared predicate (`SQLITE_LEGACY_BOOLEAN_TEXT`). Failures are logged at `warn` and swallowed, the same as the sibling backfills, so the next boot tries again. - `sql-driver-schema-sync.ts`: `previewBooleanConvergence`, called from `previewDeferredSchemaWork`. It counts the same predicate and reports `{ kind: 'normalize_boolean_storage', columns, rows }`. - `sql-driver-rotation.ts`: one call beside the datetime, time and JSON backfills in `initObjects`, plus the host `Pick`. `sql-driver.ts`: the two host stubs (pointer docblocks only, because the facade sits under its line ceiling). - `schema-drift.ts`: `PendingSchemaWorkKind` gains `normalize_boolean_storage`, which counts as in place under the existing `isInPlaceSchemaWork` rule. - `packages/cli/src/utils/schema-migrate.ts`: the `os migrate plan` / `apply` summary read `N temporal column(s) to converge in place`, so with this change a boolean column would have been counted as temporal. It now reads `N column(s) to converge in place`. The amendment expected no CLI change, because the renderer itself is generic, and it is; the summary label was the one word that would have become false. - `content/docs/deployment/cli.mdx`: one example line and one paragraph for the new kind. A root changeset (driver-sql and cli, patch). ## Record and reversibility The seat ruling (22:57Z), quoted from the claim amendment: > route (a) is approved. backfillCanonicalBooleans becomes the fourth driver storage convergence, beside the datetime, time and JSON backfills: one guarded idempotent UPDATE per column, normalize_boolean_storage previewed under deferred DDL, non-canonical text withheld and warned. (1) Record: follow the convention, a count plus a capped id sample with no down step. Your reason holds, since an undo would only restore the broken form. - **Record:** for each table and field that changed, one `info` line with `{ table, field, rowsConverted, sampleIds }`, with at most 5 ids. - **No down step:** since #34965 a text row reads as its integer, so the rewrite keeps the meaning, and an undo would only bring back the form the filters miss. - **Withheld:** other text (`'TRUE'`, `'yes'`) is never rewritten. It is counted and logged at `warn` as `{ table, field, rowsWithheld }`. - **Atomicity:** each column is one atomic `UPDATE` on SQLite. ## Dry-run path - `os migrate plan` (deferred DDL) lists the step in place as `normalize_boolean_storage: COLUMNS — N row update(s)` and writes nothing. The count is the one the step would convert, never the withheld rows. - `os migrate apply` runs it after the confirmation, via the flush, which calls `initObjects`. - An ordinary boot runs it automatically. `OS_SKIP_SCHEMA_SYNC=1` skips it, because that boot takes the DDL-free `registerObjectMetadata` door (`registerSchemasWithoutDdl` in the objectql plugin), which reaches no backfill. ## Pins and ablations The pins live in `packages/drivers/driver-sql/src/sql-driver-34916-boolean-text-read.test.ts` (three `[#34973]` describes) and `packages/cli/src/utils/schema-migrate.pending-render.test.ts`. | Pin | Ablation A: backfill call removed | Ablation B: preview wiring removed | |---|---|---| | before the step, `= false` / `= true` miss the text rows | green (measures the defect) | green | | after `initObjects`, `=` finds them (toggle too) | **red** | green | | `$in`, `$ne`, `$nin`: wrong before, right after | **red** | green | | ORDER BY: text after integers before, sorted with its boolean after | **red** | green | | aggregate groupBy: 5 groups (text `'false'` as true) before, 3 after | **red** | green | | `info` record: `rowsConverted` + `sampleIds` per field | **red** | green | | second boot: first boot converted, second sends no converting UPDATE and logs nothing | **red** | green | | `skipSchemaSync` (`registerObjectMetadata`) leaves the text rows untouched | green (by design) | green | | other text withheld, warned once with the count | **red** | green | | plan counts only the convertible rows, never the withheld | green | **red** | | plan previews `normalize_boolean_storage` with its count, in place, and writes nothing | green | **red** | | apply (flush) converges, and a re-plan finds none | **red** | green | | CLI renders `deal [normalize_boolean_storage: won — 3 row update(s)]` in place | n/a | n/a | Ablation C, CLI summary wording (`column(s)` put back to `temporal column(s)`): `summarizePendingSchemaWork … never omits in-place work` went **red** (`Expected: "6 column(s) to converge in place"`). The 12 other tests stayed green. All three ablations went through `scripts/ablation-replace.mjs` in WRAP mode, plus an outer EXIT/INT/TERM trap, and the tests import `src/` directly (no `dist/`, so no rebuild leg). Each one was restored by blob: <details><summary>Ablation evidence</summary> ``` [A] packages/drivers/driver-sql/src/sql-driver-rotation.ts ablation-replace: ok mutation landed: anchor 1 -> 0, blob 73fd7d4 -> d791326b4a93 Tests 8 failed | 13 passed (21) ablation-replace: ok restored: blob == HEAD (73fd7d4) and `git diff HEAD` is empty [B] packages/drivers/driver-sql/src/sql-driver-schema-sync.ts ablation-replace: ok mutation landed: anchor 1 -> 0, blob d320ed4 -> 4b98e620a0c0 Tests 2 failed | 19 passed (21) ablation-replace: ok restored: blob == HEAD (d320ed4) and `git diff HEAD` is empty [C] packages/cli/src/utils/schema-migrate.ts ablation-replace: ok mutation landed: anchor 1 -> 0, blob 4a7a238 -> 90cfcf1b699a Tests 1 failed | 12 passed (13) ablation-replace: ok restored: blob == HEAD (4a7a238) and `git diff HEAD` is empty ``` </details> ## Tests All readings from the worktree `objectstack-issue-34973`, after merging `origin/main` `367e324eeb4` and rebuilding the cli closure (`turbo run build --filter='@objectstack/cli^...' --filter=@objectstack/cli`, 64/64 tasks). - driver-sql pin file at `383a794b4fd`: `Tests 21 passed (21)`. `30bcd609ea0` touches only the cli test. - `pnpm --filter @objectstack/driver-sql typecheck && vitest run` at `383a794b4fd`: `Test Files 260 passed | 13 skipped (273)`, `Tests 4366 passed | 251 skipped (4617)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/cli typecheck && vitest run --project unit` at `383a794b4fd`: `Test Files 426 passed (426)`, `Tests 6057 passed (6057)`, `VERDICT command-exit 0`. - At `30bcd609ea0`: cli `typecheck` exit 0 (`check:test-typecheck: OK`). The pending-render, lazy-driver-import and tier-partition files: `Tests 38 passed (38)`. - The cli `integration` layer is declared to CI: the diff touches no integration file and no spawn entry. ## Acceptance notes - The `skipSchemaSync` pin works at the driver: it calls the door the objectql plugin uses for that boot (`registerObjectMetadata`), and does not boot the plugin. It stays green under ablation A by design. - Postgres, MySQL, MSSQL and Oracle were not measured live (no rig here). That they cannot hold the text comes from code reading, recorded in the premise report. - At every boot, a converged column costs one counting scan over its text cells. That is the same order of cost as the sibling datetime backfill's guard count. ## Verification - `dispatch-gates --commands` derived 109 families for 9 paths (merge base `367e324ee`). I ran all 109 at `30bcd609ea0`: 108 exit 0, and `check:type-check-debt` is **NOT MEASURED** (verify-lock queue-timeout, exit 99; the lock was held by another worktree's suite run). It was exit 0 at `383a794b4fd`, and `30bcd609ea0` adds only test imports. `--ran` reconciliation: 109 derived, 108 run, 1 UNRUN (that family). CI's `Lint & Repo Gates` carries it. - `check:test-source-alias` was red at `383a794b4fd`: 7 guarded imports reached from the edited pending-render test. It is green at `30bcd609ea0`, after module-top side-effect imports were added (its printed remedy). The bare imports are no value imports, so the file stays in the `unit` tier. - `check-governed-merges --branch` at `30bcd609ea0`: NOT governed, 0 of 9 paths, 511 changed lines (+502 / -9), under 3000. - `overlap-check` at `30bcd609ea0`: `VERDICT clean exit 0` against `origin/main` and #35060, #34791 and #34717, which share `content/docs/deployment/cli.mdx` and merge cleanly. - Dogfood battery: n/a. The title has no `!`, and the Clause-② arm is `(widening)`. ## Delta round (head `db8bdd734bd`, after seat L2 PASS 6966769750) - `c26c7d7551a`, docs, folds seat should-fix 2: the closing sentence in `cli.mdx` now names all three in-place steps. It says only the MySQL widen is a table rebuild. - `dcbecc37966` merges `origin/main` (K = 17). `overlap-check` gives `VERDICT clean exit 0` against `origin/main` and #35060, #34791 and #34717. - `db8bdd734bd` folds seat nits 3, 4 and 5: - The withheld count excludes the canonical text `'1'` / `'0'` that a TEXT-affinity column stores. - `rowsConverted` falls back to the counted rows when a client's raw `UPDATE` reports no `changes` (driver-sqlite-wasm, knex `sqlite3`). - The `PendingSchemaWork.rows` docblock names `normalize_boolean_storage`. - Two new pins: - **A TEXT-affinity column:** `'1'` / `'0'` are not withheld, and the legacy `'true'` still converges. Ablation 3 puts the withheld formula back to `text_rows - legacy`: `Tests 1 failed | 22 passed (23)`. - **A client with no `changes`:** the record carries the counted rows. Ablation 4 puts the fallback back to `0`: `Tests 1 failed | 22 passed (23)`. - Each ablation was restored by copying the file back. - Readings at `db8bdd734bd`: the pin file shows `Tests 23 passed (23)`, and driver-sql `tsc --noEmit` exits 0. The full driver-sql suite was not re-run locally; CI's Test Core carries it. - Reviews: L1 delta ACCEPT 6966877056, and the seat delta L2 PASS 6967050006 carries the PASS forward. Seat should-fix 1 (the Turso remote face) went to triage as a follow-up. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzg2evNa1V3zxrQq3KX --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: os-support-ai <support@objectstack.ai>
1 parent dcbb363 commit 23c42c4

9 files changed

Lines changed: 584 additions & 14 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
'@objectstack/cli': patch
4+
---
5+
6+
fix(driver-sql): boot converges legacy text `'true'` / `'false'` in a SQLite boolean column to `1` / `0`, so boolean filters, sorts and groups find those rows
7+
8+
Clause-②: yes (widening: `@objectstack/driver-sql` exports `PendingSchemaWorkKind` from its index, and the CLI consumes it, so the union gains one published value, `normalize_boolean_storage`; boolean filters, sorts and groupBy on SQLite now answer legacy text rows as their boolean)
9+
Metadata-protocol: none
10+
11+
Before the engine stored the boolean a reading spells, a door that sent the text `'true'` / `'false'` (the console's inline grid) left that text in a SQLite `Field.boolean` or `Field.toggle` column. Since the previous release those rows read back as the right boolean, but every comparison ran against the raw text: `won = false` missed a stored `'false'`, `won = true` missed a stored `'true'`, `$in`, `$ne` and `$nin` answered wrongly, ORDER BY sorted the text after every integer, and an aggregate groupBy presented a text `'false'` as `true`.
12+
13+
Schema sync now converges those cells at boot, the fourth storage convergence beside the datetime, time and JSON backfills (`backfillCanonicalBooleans`):
14+
15+
- **SQLite only.** Postgres, MSSQL, MySQL and Oracle coerce or refuse the text, so no other dialect can hold such a row.
16+
- **One guarded `UPDATE` per column**: `'true'` becomes `1` and `'false'` becomes `0`, and nothing else is written. A second boot converts 0 rows.
17+
- **Other text is never rewritten.** A value such as `'yes'` or `'TRUE'` names no boolean the driver can read without guessing; it is counted and logged at `warn`, and boolean filters keep missing it until the value is corrected at the source.
18+
- **The record** is an `info` line per table and field with the rows converted and up to five of their ids. There is no down step: a text row already reads as its integer, so an undo would only restore the form the filters miss.
19+
- **Dry run.** Under `os migrate plan` the step is listed in place as `normalize_boolean_storage`, with its row count, and nothing is written; `os migrate apply` runs it after the confirmation. `OS_SKIP_SCHEMA_SYNC=1` skips it, as it skips every other schema-sync step.
20+
21+
`os migrate plan`'s summary line now reads `N column(s) to converge in place` instead of `N temporal column(s) …`, because a boolean column is counted there too.

‎content/docs/deployment/cli.mdx‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,6 +1173,7 @@ performed. So `plan` really is a dry run, and everything `apply` is about to do
11731173
11741174
In place (existing rows converged when you apply)
11751175
~ crm_contact [normalize_datetime_storage: signed_at — 1,240 row update(s)]
1176+
~ crm_deal [normalize_boolean_storage: won — 312 row update(s)]
11761177
11771178
Needs confirmation
11781179
~ crm_contact.email [relax_not_null]
@@ -1189,10 +1190,16 @@ column needs when the database predates the canonical UTC storage (ADR-0053
11891190
addendum D-B1..D-B4). It carries a row count because that is the number
11901191
deciding whether to run it now; on MySQL it reads `widen_datetime_columns` and
11911192
is an `ALTER … MODIFY` table rebuild that holds a metadata lock for its
1192-
duration.
1193-
1194-
Both are safe to apply — the convergence preserves every stored instant and is
1195-
idempotent — but only the second takes time proportional to your data.
1193+
duration. On SQLite it also lists `normalize_boolean_storage`: rows of a
1194+
`Field.boolean` or `Field.toggle` column that an older build stored as the text
1195+
`'true'` / `'false'` become `1` / `0`, so boolean filters, sorts and groups find
1196+
them. Any other text in such a column is left as stored and reported in the
1197+
log.
1198+
1199+
All three are safe to apply — the datetime convergence preserves every stored
1200+
instant, the boolean step rewrites only the two canonical spellings, and each is
1201+
idempotent — but only the MySQL widen is a table rebuild whose duration grows with
1202+
your data.
11961203
11971204
#### Runtime-owned indexes apply builds
11981205

‎packages/cli/src/utils/schema-migrate.pending-render.test.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@
1212
*/
1313

1414
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
15+
// `schema-migrate.ts` reaches these through guarded dynamic imports
16+
// (`schema-migration-plugins.ts`); loading them here pays the transform during
17+
// collection, never inside a case's clocked window (`check:test-source-alias`).
18+
import '@objectstack/driver-sql';
19+
import '@objectstack/driver-turso';
20+
import '@objectstack/platform-objects/plugin';
21+
import '@objectstack/plugin-security';
22+
import '@objectstack/rest';
23+
import '@objectstack/runtime';
24+
import '@objectstack/service-datasource';
1525
import {
1626
renderPendingSchemaWork,
1727
splitRefusedSchemaWork,
@@ -44,6 +54,7 @@ const IN_PLACE: PendingSchemaWork[] = [
4454
{ table: 'legacy', kind: 'widen_datetime_columns', columns: ['at', 'created_at'], rows: 42 },
4555
{ table: 'shift', kind: 'normalize_time_storage', columns: ['starts_at'], rows: 7 },
4656
{ table: 'shift_my', kind: 'widen_time_columns', columns: ['starts_at'], rows: 9 },
57+
{ table: 'deal', kind: 'normalize_boolean_storage', columns: ['won'], rows: 3 },
4758
];
4859

4960
describe('renderPendingSchemaWork (#3954)', () => {
@@ -82,6 +93,9 @@ describe('renderPendingSchemaWork (#3954)', () => {
8293
expect(out()).toContain('7 row update(s)');
8394
expect(out()).toContain('widen_time_columns: starts_at');
8495
expect(out()).toContain('9 row table rebuild');
96+
// The boolean convergence (#34973) is a row update in place, like the
97+
// temporal backfills.
98+
expect(out()).toContain('deal [normalize_boolean_storage: won — 3 row update(s)]');
8599
});
86100

87101
it('shows both sections when both kinds are pending', async () => {
@@ -110,8 +124,10 @@ describe('summarizePendingSchemaWork (#3954)', () => {
110124
const summary = await summarizePendingSchemaWork([...ADDITIVE, ...IN_PLACE]);
111125
expect(summary).toContain('1 table(s) to create');
112126
expect(summary).toContain('1 column(s) to add');
113-
expect(summary).toContain('5 temporal column(s) to converge in place');
114-
expect(summary).toContain('~1,234,625 rows');
127+
// [#34973] Not "temporal": a boolean column converges in place too.
128+
expect(summary).toContain('6 column(s) to converge in place');
129+
expect(summary).not.toContain('temporal');
130+
expect(summary).toContain('~1,234,628 rows');
115131
});
116132
});
117133

‎packages/cli/src/utils/schema-migrate.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2016,7 +2016,9 @@ export async function summarizePendingSchemaWork(pending: PendingSchemaWork[]):
20162016
if (inPlace.length > 0) {
20172017
const cols = inPlace.reduce((n, p) => n + p.columns.length, 0);
20182018
const rows = inPlace.reduce((n, p) => n + (p.rows ?? 0), 0);
2019-
parts.push(`${cols} temporal column(s) to converge in place (~${formatRows(rows)} rows)`);
2019+
// [#34973] "column(s)", not "temporal column(s)": the boolean storage
2020+
// convergence (`normalize_boolean_storage`) is counted here too.
2021+
parts.push(`${cols} column(s) to converge in place (~${formatRows(rows)} rows)`);
20202022
}
20212023
// [#30636] Named only when there are some, like the in-place count above.
20222024
const rebuilds = pending.filter((p) => p.kind === 'rebuild_table').length;

‎packages/drivers/driver-sql/src/schema-drift.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -361,8 +361,9 @@ export interface PendingSchemaWork {
361361
* How much data the step touches, when that is knowable up front and worth
362362
* knowing — absent for the additive kinds, which touch none.
363363
*
364-
* For `normalize_datetime_storage` it is the number of row-writes (summed
365-
* across `columns`, since each is its own `UPDATE`). For
364+
* For `normalize_datetime_storage` and `normalize_boolean_storage` it is the
365+
* number of row-writes (summed across `columns`, since each is its own
366+
* `UPDATE`). For
366367
* `widen_datetime_columns` it is the table's row count, because MySQL's
367368
* `ALTER … MODIFY` is a full rebuild holding a metadata lock — which is the
368369
* number that decides "now" versus "in a maintenance window".
@@ -398,6 +399,11 @@ export interface PendingSchemaWork {
398399
* section tells the operator the work is never data-losing, and that claim must
399400
* not silently come to cover a row rewrite.
400401
*
402+
* [#34973] `normalize_boolean_storage` rewrites rows in place too: the SQLite
403+
* boolean backfill, which turns legacy text `'true'` / `'false'` cells into
404+
* `1` / `0`. It is in place by the rule below, and `os migrate plan` renders
405+
* it as a row-update count beside the temporal ones.
406+
*
401407
* [#30636] Two more describe the one existing-table shape the additive path
402408
* cannot adopt — keyed by `_id`, with no `id` column (`existing-table-refusal.ts`):
403409
* `rebuild_table` drops and recreates it while it is EMPTY (in place: it is
@@ -418,6 +424,7 @@ export type PendingSchemaWorkKind =
418424
| 'add_columns'
419425
| 'normalize_datetime_storage'
420426
| 'normalize_time_storage'
427+
| 'normalize_boolean_storage'
421428
| 'widen_datetime_columns'
422429
| 'widen_time_columns'
423430
| 'rebuild_table'

0 commit comments

Comments
 (0)