From 525e7ebec2b5c85d39f32a26fd792546b270d9dd Mon Sep 17 00:00:00 2001 From: Nils Kopal <47944423+n1k0m0@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:58:43 +0100 Subject: [PATCH] Introduce incompatible storage format v2 Store REAL/DOUBLE as binary64LE, align rows and scalar fields, reserve table page 0 for immutable metadata, use U32 overflow lengths, and compare typed little-endian index keys numerically. Preserve signed zero through SQL conversion and covering indexes. Reject legacy database formats explicitly. Add byte-level regression tests, native test runner integration, and current format/compatibility documentation. --- CHANGELOG.md | 15 ++ README.md | 18 +- config/config.schema.json | 10 +- config/minisql.example.json | 8 +- docs/acceptance/STORAGE_V2_2026-11-24.md | 85 ++++++++ docs/formats/FORMAT_COMPATIBILITY.md | 72 +++++- docs/formats/README.md | 122 +++++++---- docs/formats/btree-v1.md | 4 + docs/formats/btree-v2.md | 101 +++++++++ docs/formats/catalog-bootstrap-v1.md | 5 + docs/formats/catalog-v1.md | 5 + docs/formats/database-meta-v1.md | 4 + docs/formats/database-meta-v2.md | 123 +++++++++++ docs/formats/ddl-journal-v1.md | 2 +- docs/formats/heap-forwarding-v1.md | 4 + docs/formats/index-file-v1.md | 4 + docs/formats/index-file-v2.md | 101 +++++++++ docs/formats/overflow-v1.md | 5 + docs/formats/overflow-v2.md | 53 +++++ docs/formats/page-v1.md | 5 + docs/formats/paged-file-v1.md | 6 + docs/formats/row-v1.md | 4 + docs/formats/row-v2.md | 95 ++++++++ docs/formats/slotted-page-v1.md | 4 + docs/formats/slotted-page-v2.md | 54 +++++ docs/formats/sort-spill-v1.md | 4 + docs/formats/statistics-v1.md | 5 + docs/formats/storage-v2.md | 72 ++++++ docs/formats/table-file-v1.md | 4 + docs/formats/table-file-v2.md | 62 ++++++ docs/formats/wal-v1.md | 11 +- docs/module-catalog.json | 18 ++ docs/release/UPGRADE.md | 84 ++++--- docs/release/feature-matrix.json | 2 +- docs/release/upgrade-matrix.json | 34 ++- src/minisql/catalog/catalog.ml | 5 +- src/minisql/catalog/metadata.ml | 10 +- src/minisql/catalog/schema_history.ml | 3 +- src/minisql/common/float_codec.ml | 125 +++++++++++ src/minisql/common/format_version.ml | 38 ++++ src/minisql/common/version.ml | 4 +- src/minisql/config/model.ml | 4 +- src/minisql/config/validation.ml | 5 +- src/minisql/executor/dml.ml | 118 +++++----- src/minisql/executor/executor.ml | 3 +- src/minisql/executor/scan.ml | 11 +- src/minisql/planner/optimizer.ml | 2 +- src/minisql/server/database_manager.ml | 5 +- src/minisql/sql/values.ml | 30 ++- src/minisql/storage/btree.ml | 180 ++++++++++++++- src/minisql/storage/heap_file.ml | 23 +- src/minisql/storage/overflow.ml | 22 +- src/minisql/storage/page.ml | 2 + src/minisql/storage/row_codec.ml | 178 +++++++-------- src/minisql/storage/slotted_page.ml | 26 ++- src/minisql/storage/table_header.ml | 164 ++++++++++++++ src/minisql/tools/backup.ml | 3 +- src/tests/m10_overflow.ml | 12 +- src/tests/m50_release_contract.ml | 2 +- src/tests/m8_catalog.ml | 6 + src/tests/m8_config.ml | 18 ++ src/tests/m9_heap_file.ml | 15 +- src/tests/storage_v2_indexes.ml | 267 +++++++++++++++++++++++ src/tests/storage_v2_metadata.ml | 47 ++++ src/tests/storage_v2_overflow.ml | 59 +++++ src/tests/storage_v2_rows.ml | 195 +++++++++++++++++ src/tests/storage_v2_table.ml | 131 +++++++++++ test.ps1 | 12 + tests/baseline_m0_m10.py | 6 +- tests/manifest.json | 37 +++- tests/reference/m48_m50_layout.json | 2 +- tests/reference/storage_v2_layout.json | 20 ++ tests/run_all_tests.py | 57 ++++- tests/run_storage_v2.py | 143 ++++++++++++ tools/release/build_release.py | 2 +- 75 files changed, 2861 insertions(+), 336 deletions(-) create mode 100644 docs/acceptance/STORAGE_V2_2026-11-24.md create mode 100644 docs/formats/btree-v2.md create mode 100644 docs/formats/database-meta-v2.md create mode 100644 docs/formats/index-file-v2.md create mode 100644 docs/formats/overflow-v2.md create mode 100644 docs/formats/row-v2.md create mode 100644 docs/formats/slotted-page-v2.md create mode 100644 docs/formats/storage-v2.md create mode 100644 docs/formats/table-file-v2.md create mode 100644 src/minisql/common/float_codec.ml create mode 100644 src/minisql/common/format_version.ml create mode 100644 src/minisql/storage/table_header.ml create mode 100644 src/tests/storage_v2_indexes.ml create mode 100644 src/tests/storage_v2_metadata.ml create mode 100644 src/tests/storage_v2_overflow.ml create mode 100644 src/tests/storage_v2_rows.ml create mode 100644 src/tests/storage_v2_table.ml create mode 100644 tests/reference/storage_v2_layout.json create mode 100644 tests/run_storage_v2.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c39b7a4..4f110fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ and repair-candidate log from development is preserved in ## Unreleased +- introduced incompatible database/storage format 2; new binaries reject + format-1 databases instead of attempting an implicit conversion; +- store REAL and DOUBLE as exact eight-byte IEEE-754 binary64 little-endian + values, preserving finite bit patterns including signed zero and subnormals; +- align row starts and lengths to eight bytes, align fixed-width fields to + their natural widths, and validate zero padding during decoding; +- reserve every user table's logical page 0 for a checksummed `MSTB` header, + with heap and overflow pages starting at page 1; +- encode overflow lengths as U32, retain aligned U64 identifiers in the 48-byte + pointer, and protect the pointer with an additional CRC-32C; +- encode numeric SQL index components in little-endian and compare typed keys + numerically, including floating-point range and covering-index scans; +- add byte-golden, malformed-input, sorting, reopening and compatibility tests + through `test.ps1 -StorageV2` and the cumulative acceptance launcher. + ## 1.1.1 — 2026-10-31 - added bounded x64 byte-hash and lexicographic-comparison primitives for long diff --git a/README.md b/README.md index 7d2b66d..a7ee202 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,13 @@ MiniSQL is a transactional relational database management system written in [MiniLang](https://github.com/MiniLangProject/MiniLangCompilerPy) and compiled to native Windows x64 PE or Linux x64 ELF applications. +**Current development tree: storage format 2.** This unreleased change stores +REAL/DOUBLE as binary64LE, aligns rows, reserves table page 0 for metadata, uses +U32 overflow lengths and little-endian numeric index keys. Existing format-1 +databases are rejected and must be recreated. See the +[storage-v2 specification](docs/formats/storage-v2.md) and +[compatibility rules](docs/formats/FORMAT_COMPATIBILITY.md). + Browse the committed [GitHub-friendly API documentation](docs/api/markdown/README.md), or download the repository and open the [offline HTML reference](docs/api/html/index.html). Both documentation trees are generated directly from the MiniLang sources with @@ -28,14 +35,21 @@ The strict MiniDoc configuration rejects missing documentation; use `--check` to validate it without rewriting the committed reference. The frozen M0-M50 plan is complete. The accepted 1.0 baseline revision is -`M48-M50R3`; MiniSQL 1.1.1 retains database and wire format version 1. The -current tree was revalidated on 2026-09-02: Windows passed all +`M48-M50R3`; released MiniSQL 1.1.1 retained database and wire format version 1. +That baseline was revalidated on 2026-09-02: Windows passed all **106/106 cumulative phases**, including crash recovery, genuinely parallel same-database reads, concurrent clients, TLS integration, replication, fuzzing, soak tests, and deterministic release packaging; the focused Linux gate passed all storage, client/server, concurrent scheduling, authentication, and native TLS checks under WSL2. +Those historical results do not certify the new storage-v2 development changes. +Their focused binary-format gate is `./test.ps1 -StorageV2 -Target linux-x64` +or `./test.ps1 -StorageV2 -Target windows-x64` on the corresponding host. The +same five new format tests are included in the cumulative row/storage phase. +The [storage-v2 validation report](docs/acceptance/STORAGE_V2_2026-11-24.md) +records the focused native results and the platform limits of this development check. + > MiniSQL is an independently developed database engine. Version 1.0 has a > substantial project-specific test suite, but it has not received an > independent security or production audit. Validate it against your own diff --git a/config/config.schema.json b/config/config.schema.json index e51ffda..66f1a6b 100644 --- a/config/config.schema.json +++ b/config/config.schema.json @@ -235,23 +235,23 @@ }, "databaseFormatVersion": { "type": "integer", - "minimum": 1 + "const": 2 }, "tableFileFormatVersion": { "type": "integer", - "minimum": 1 + "const": 2 }, "indexFileFormatVersion": { "type": "integer", - "minimum": 1 + "const": 2 }, "walFormatVersion": { "type": "integer", - "minimum": 1 + "const": 1 }, "rowFormatVersion": { "type": "integer", - "minimum": 1 + "const": 2 } } }, diff --git a/config/minisql.example.json b/config/minisql.example.json index 66bf4c6..a81d916 100644 --- a/config/minisql.example.json +++ b/config/minisql.example.json @@ -49,11 +49,11 @@ "walSegmentBytes": 16777216, "textEncoding": "utf-8", "defaultCollation": "binary", - "databaseFormatVersion": 1, - "tableFileFormatVersion": 1, - "indexFileFormatVersion": 1, + "databaseFormatVersion": 2, + "tableFileFormatVersion": 2, + "indexFileFormatVersion": 2, "walFormatVersion": 1, - "rowFormatVersion": 1 + "rowFormatVersion": 2 }, "safety": { "allowRemoteWithoutAuthentication": false, diff --git a/docs/acceptance/STORAGE_V2_2026-11-24.md b/docs/acceptance/STORAGE_V2_2026-11-24.md new file mode 100644 index 0000000..d2b1cb0 --- /dev/null +++ b/docs/acceptance/STORAGE_V2_2026-11-24.md @@ -0,0 +1,85 @@ +# Storage-v2 development validation — 2026-11-24 + +## Scope and baseline + +This report covers the incompatible storage-format update based on MiniSQL +commit `7fdab6bd49e8ac344632528109efd7e06e635afd`. The requested changes are binary +REAL/DOUBLE storage, aligned rows, a mandatory table metadata page 0, U32 overflow +lengths, and little-endian numeric SQL index components with semantic ordering. +See [the format overview](../formats/storage-v2.md) for the persisted contract. + +Validation used MiniLang Compiler 1.3.10, compiler source commit +`8e64c9cfda92199b68ac5d3974fea445f12f6c39`, with native Linux x64 executables. +Test fixtures were isolated under ignored `build/` directories. Existing +databases were not converted or used as mutable fixtures. + +## Focused binary-format gate + +All five suites passed after the final SQL conversion and index corrections. + +The internal cross-platform runner is exposed through `test.ps1 -StorageV2`. +The native Linux invocation is: + +```sh +python tests/run_storage_v2.py --target linux-x64 --compiler ../MiniLangCompilerPy/mlc_win64.py +``` + +| Suite | Coverage | +|---|---| +| `storage_v2_metadata` | Metadata byte goldens, exact version tuple, old versions, mixed versions, flags and reserved fields | +| `storage_v2_rows` | IEEE-754 goldens, 128 finite bit patterns, signed zero, subnormals, natural alignment, zero padding, malformed rows, slot bounds/overlap and failure atomicity | +| `storage_v2_table` | Exact page-0 metadata, first data page 1, immutable header after growth, corruption, all physical open modes and legacy rejection | +| `storage_v2_overflow` | U32 boundary without allocating 4 GiB, independent pointer CRC golden, reserved bytes, damaged/truncated pointers and legacy rejection | +| `storage_v2_indexes` | I64 limits, 255/256, finite floating order, escaped/composite keys, uniqueness, splitting/ranges/reopen, covering results and signed-zero SQL conversions | + +The runner writes per-test compiler/runtime logs and machine-readable +`results.json`. A native pass requires both exit status 0 and the test's exact +success banner. Cross-compilation is explicitly recorded as `COMPILE_PASS` and +does not count as native execution. + +## Existing regression suites + +The following 17 suites passed natively during implementation: + +| Area | Passing suites | +|---|---| +| Configuration and catalog | `m8_config`, `m8_catalog` | +| Heap, rows, overflow and tree | `m9_row_codec`, `m9_heap_file`, `m10_overflow`, `m11_btree` | +| WAL, transactions and recovery | `m6_wal`, `m6_transaction`, `m7_checkpoint`, `m7_recovery` | +| SQL and schema integration | `m15_sql_engine`, `m23_index_integration`, `m24_schema_evolution` | +| Maintenance and migration | `m25_maintenance`, `m26_offline_migration` | +| Database contracts and encryption | `m50_release_contract`, `m79_security_at_rest` | + +The SQL and index integration suites were rerun after the signed-zero correction. +Maintenance covers VACUUM, REINDEX and interrupted-maintenance recovery. Migration +covers 4096-to-8192-byte page rewrites. Encryption coverage includes encrypted new +table headers, WAL, key rotation and encrypted backup/restore. + +## Signed-zero regression found during review + +The strengthened index test first reproduced loss of `-0.0` in a DOUBLE key, a +REAL key and an INCLUDE value before the index was built. SQL numeric promotion +and text conversion discarded the sign before row serialization. A second +reviewed path reconstructed a covered equality key from the search literal, +which cannot preserve the stored value's sign. + +The correction preserves floating inputs during conversion, restores a negative +zero sign for explicitly negative zero text, retains stored key bits, and reads +actual B+ tree entries for covered equality scans. The numeric comparator treats +both zero signs as equal; transient byte-hashed constraint keys normalize them. +The regression checks range and equality scans, composite equality, INCLUDE, +uniqueness and reopening against the heap's original binary64 bytes. + +## Static and platform checks + +- The repository's four static acceptance phases pass, including its 87-module + catalog, Apache headers, declaration documentation, configuration contracts and + independent Python binary/CRC reference vectors. +- `git diff --check` reports no whitespace errors. +- `storage_v2_rows` compiles for Windows x64 as a PE executable. Its CRT imports + include `_copysign`, `_finite`, `frexp` and `ldexp`. It was not executed on Windows. + +The historical 106-phase Windows release acceptance was not rerun in this Linux +workspace. Existing release-evidence documents remain historical evidence. The +normal cumulative launcher now includes the five focused storage-v2 tests in +its row/storage phase; this report makes no new full-Windows-release claim. diff --git a/docs/formats/FORMAT_COMPATIBILITY.md b/docs/formats/FORMAT_COMPATIBILITY.md index 2636ed8..62a5bb7 100644 --- a/docs/formats/FORMAT_COMPATIBILITY.md +++ b/docs/formats/FORMAT_COMPATIBILITY.md @@ -1,15 +1,63 @@ -# MiniSQL 1.0 format compatibility +# Format compatibility: unreleased storage v2 -MiniSQL 1.0 freezes database format version 1 and wire protocol version 1. -Individual files also carry their own magic, version, database identity, object -identity and checksums. Global configuration values are never used to reinterpret -an existing file. +The current development tree requires **database format 2**. Its product +version is still **1.1.1**; the earlier format-1 builds bearing that version and +their dated release evidence are unchanged. Persisted version fields, rather +than the product-version string, determine compatibility. -The M48 `wal.log.durable` marker is auxiliary and may be recreated. It does not -change `wal.log` encoding. Unknown future versions must be rejected rather than -guessed. +## Version boundaries -Automatic HA adds auxiliary `leader.epoch` and controller-owned `leader.lease` -records. Their v1 layouts are documented in `ha-fencing-records-v1.md`. They do -not alter database pages, WAL, backup archives, or wire protocol v1. Ordinary -non-HA databases do not require either record. +| Component | Current version | +|---|---:| +| Database metadata envelope and database format | 2 | +| User-table file header | 2 | +| Physical row record | 2 | +| Overflow pointer and chain page | 2 | +| B+ tree metadata/node payload | 2 | +| SQL index key and INCLUDE payload | 2 | +| Common page header | 1 | +| Paged-file superblock | 1 | +| WAL record framing | 1 | +| Generic protected-envelope header structure | 1 | +| Catalog envelope | 1 | +| Wire protocol | 1 | + +The slotted-page payload uses the aligned v2 allocation contract, selected by +the database/table format. Its common page-header version remains 1. The +generic protected-envelope structure has no independent outer version field: +the U16 at offset 8 is the enclosed format's version, which is 2 for `db.meta`. + +## Accepted and rejected input + +- A database created by this storage-v2 implementation opens only when all + required identities, supported versions, reserved fields and checksums agree. +- Existing database-format-1 files are rejected, including empty databases and + databases from earlier 1.1.1 builds. No compatibility decoder or automatic + upgrade is provided. +- Legacy table files without the required metadata page 0, row records with + version 1, overflow version 1, and B+ tree version 1 are rejected. +- Unknown versions or unsupported flags are rejected. Configuration defaults + cannot override persisted identity or reinterpret existing bytes. +- There is no supported downgrade of storage-v2 databases to format-1 engines. + +Schema versions remain separate from physical row-format versions: compatible +column evolution inside a storage-v2 database does not enable reading a +row-format-1 record. + +## WAL, backups and auxiliary records + +Unchanged WAL framing does not make old and new page images interchangeable. +Storage-v2 recovery operates on the current database and its matching page +images. Backup and WAL-archive framing also keep their existing versions, but +their contained database must pass the storage-v2 checks. No legacy-backup +import path is introduced by this patch. + +The durable-WAL marker and HA epoch/lease records retain their independent +layouts and do not select a storage generation. Existing statistics and +security-sidecar compatibility rules apply only after the enclosing database +has passed the database-format gate. + +The offline page-size rewrite operates between databases supported by the +current engine. It creates a new storage-v2 database; it is not a format-1 to +format-2 conversion tool. See [UPGRADE.md](../release/UPGRADE.md) for the +development-build policy. diff --git a/docs/formats/README.md b/docs/formats/README.md index b8c07b8..097c2f8 100644 --- a/docs/formats/README.md +++ b/docs/formats/README.md @@ -1,42 +1,80 @@ -# MiniSQL persisted format index - -All fixed-width fields use canonical little-endian encoding unless a format -explicitly says otherwise. Unknown versions, non-zero reserved fields, checksum -failures, and contradictory identities are fail-closed. - -- [Protected envelope v1](protected-envelope-v1.md) — M2 -- [Common page v1](page-v1.md) — M4 -- [Paged file v1](paged-file-v1.md) — M4 -- [Database metadata v1](database-meta-v1.md) — M8 -- [Table file v1](table-file-v1.md) — M8 -- [Index file v1](index-file-v1.md) — M11 -- [WAL record v1](wal-v1.md) — M6 -- [Checkpoint metadata v1](checkpoint-v1.md) — M7 -- [Database/catalog envelope v1](catalog-v1.md) — M8 -- [Catalog bootstrap v1](catalog-bootstrap-v1.md) — M8 -- [Row v1](row-v1.md) — M9 -- [Slotted-page payload v1](slotted-page-v1.md) — M9 -- [Heap forwarding v1](heap-forwarding-v1.md) — M9 -- [Overflow pointer/page v1](overflow-v1.md) — M10 -- [B+ tree index v1](btree-v1.md) — M11 -- [Schema history v1](schema-history-v1.md) — M14/M24 -- [DDL journal v1](ddl-journal-v1.md) — M14/M24 -- [Statistics v1](statistics-v1.md) — M17 -- [Wire protocol v1](wire-protocol-v1.md) — M18/M21 -- [Backup manifest v1](backup-manifest-v1.md) — M20 -- [Security catalog v1](security-catalog-v1.md) — M21 -- [Encryption envelope and records v1](encryption-envelope-v1.md) — M79 -- [Maintenance journal v1](maintenance-journal-v1.md) — M25 - -Existing paged files MUST derive page size and format identity from persisted -metadata and file headers, never from changed global defaults. M22-M24 do not -change page, WAL, or wire format. M25 introduces only the maintenance journal; -M26 rewrites into a fresh database rather than mutating format identity. - -- `audit-log-v1.md` - -- `secure-transport-v1.md` - -- `wal-archive-v1.md` -- [WAL durable marker v1](wal-durable-marker-v1.md) — M48 -- [MiniSQL 1.0 format compatibility](FORMAT_COMPATIBILITY.md) — M50 +# MiniSQL persisted formats + +This index describes the **unreleased storage-v2 development state**. The +product version remains **1.1.1** for this patch; that product label alone does +not identify the database format. Earlier release evidence and milestone +documents describe their original format-1 builds. + +All fixed-width numeric storage fields use little-endian encoding. Current +storage-v2 readers reject unsupported versions, noncanonical padding, +checksum failures and contradictory identities. Page sizes and format versions +come from persisted metadata, not from changed global defaults. + +## Current storage generation 2 + +| Component | Version / contract | Specification | +|---|---|---| +| Database metadata | `MSDBM001` envelope version 2; database/table/index/WAL/row tuple `2/2/2/1/2` | [Database metadata v2](database-meta-v2.md) | +| User-table file | Mandatory identity header on page 0; data pages start at 1 | [Table file v2](table-file-v2.md) | +| Rows | Version 2; aligned fields and binary64 REAL/DOUBLE | [Row v2](row-v2.md) | +| Slotted-page payload | Eight-byte-aligned allocations, selected by table format 2 | [Slotted-page payload v2](slotted-page-v2.md) | +| Overflow | Version 2; U32 total length and separate pointer CRC | [Overflow pointer/page v2](overflow-v2.md) | +| Index keys and leaf values | Typed little-endian numeric keys; INCLUDE payload version 2 | [SQL index keys and values v2](index-file-v2.md) | +| B+ tree metadata and nodes | Version 2 | [B+ tree v2](btree-v2.md) | + +Legacy database format 1 is explicitly rejected. There is no implicit +conversion, legacy import, or in-place upgrade in this development patch. +See [format compatibility](FORMAT_COMPATIBILITY.md) and the +[development upgrade guide](../release/UPGRADE.md). + +## Structural wrappers that remain version 1 + +These versions identify their own framing. A version-1 wrapper can carry +version-2 table or row content and does not make that content readable by an +older MiniSQL binary. + +| Wrapper | Current interpretation | +|---|---| +| [Protected envelope v1](protected-envelope-v1.md) | Same 32-byte CRC-protected header structure; each enclosed format selects its own version field. `db.meta` uses 2. | +| [Common page v1](page-v1.md) | Same 64-byte header; page type 6 identifies the new user-table header. | +| [Paged file / superblocks v1](paged-file-v1.md) | Same pair of 4096-byte superblocks; table/index payload versions are checked separately. The page-offset formula in the original spec is for plaintext records. | +| [WAL records v1](wal-v1.md) | Same 80-byte framing; page images contain current storage-v2 payloads. Encrypted records use the marker described in the encryption specification. | +| [Checkpoint v1](checkpoint-v1.md) | Same two 256-byte checkpoint slots. | +| [WAL durable marker v1](wal-durable-marker-v1.md) | Same optional durable-prefix record. | +| [Encryption envelope and records v1](encryption-envelope-v1.md) | Same nonce/ciphertext/tag framing; paged-file stride is `pageSize + 28` when encrypted. | +| [Heap forwarding v1](heap-forwarding-v1.md) | Same 24-byte record; row references in storage-v2 user tables must target pages 1 or later. | + +## Other independently versioned formats + +The catalog envelope remains `MSCAT001`, version 1, with scalable `BLB2` +continuation pages. The current relationship to `db.meta` is described in +[database metadata v2](database-meta-v2.md#catalog-companion). The original +[catalog](catalog-v1.md) and [bootstrap](catalog-bootstrap-v1.md) notes are +retained as historical M8 sketches. + +- [Schema history v1](schema-history-v1.md) +- [Schema extensions v1](schema-extensions-v1.md) +- [DDL journal v1](ddl-journal-v1.md) +- [Maintenance journal v1](maintenance-journal-v1.md) +- [Security catalog v1](security-catalog-v1.md) +- [Backup manifest v1](backup-manifest-v1.md) +- [WAL archive v1](wal-archive-v1.md) +- [Audit log v1](audit-log-v1.md) +- [HA fencing records v1](ha-fencing-records-v1.md) +- [Sort-spill framing v1](sort-spill-v1.md), whose current row payloads use row format 2 +- [Wire protocol v1](wire-protocol-v1.md) +- [Secure transport v1](secure-transport-v1.md) + +Optimizer statistics currently write sidecar version 5; this is independent of +database storage generation 2. The [statistics-v1 note](statistics-v1.md) +describes the historical baseline, not the current writer's complete layout. +Milestone-specific limits in older sidecar notes remain historical; current +serializers are authoritative for those independently evolved formats. + +## Archived storage-v1 material + +[Database metadata](database-meta-v1.md), [table files](table-file-v1.md), +[rows](row-v1.md), [slotted pages](slotted-page-v1.md), +[overflow](overflow-v1.md), [index files](index-file-v1.md), and +[B+ trees](btree-v1.md) are retained for historical reference. Their presence +does not indicate legacy read or conversion support. diff --git a/docs/formats/btree-v1.md b/docs/formats/btree-v1.md index 53342f1..2f3941b 100644 --- a/docs/formats/btree-v1.md +++ b/docs/formats/btree-v1.md @@ -1,5 +1,9 @@ # B+ tree format v1 +> Archived format-1 specification. The current engine implements +> [B+ tree v2](btree-v2.md) and rejects version-1 metadata and node payloads. +> No implicit conversion is provided. + An index is a standard paged file with `FILE_TYPE_INDEX`. Page 0 and page 1 are redundant metadata pages. Their payload begins at byte 64 with magic `MSBM`, version 1, uniqueness flags, generation, root/first-leaf/last-leaf page numbers, entry count and height. diff --git a/docs/formats/btree-v2.md b/docs/formats/btree-v2.md new file mode 100644 index 0000000..c8c099d --- /dev/null +++ b/docs/formats/btree-v2.md @@ -0,0 +1,101 @@ +# B+ tree format v2 + +Version 2 is a breaking storage format. Version-1 metadata and node payloads +are rejected; no implicit conversion is performed. All multi-byte numeric +fields below, including SQL key payloads, are little-endian. + +An index uses the shared paged-file wrapper with file type `2`. The first +8192 physical bytes contain two 4096-byte superblocks. Logical pages `0` and +`1` contain redundant tree metadata; nodes begin at logical page `2`. +For an unencrypted file, logical page `n` starts at `8192 + n * pageSize`. +The shared page-v1 header occupies bytes `0..63` of every logical page and +provides the page identity, generation, LSN, free-space bounds and CRC-32C. + +## Metadata pages + +The common page type is `3` (internal) and its flags are `0x8000` (metadata). +The common item count is zero, free-start is `128`, and free-end is page size. +Offsets in all tables are relative to the logical page. + +| Offset | Bytes | Field | +|---:|---:|---| +| 64 | 4 | ASCII `MSBM` | +| 68 | 2 | B+ tree format version `2` | +| 70 | 2 | Flags: `1` for unique, otherwise `0` | +| 72 | 8 | Tree generation | +| 80 | 8 | Root page number | +| 88 | 8 | First leaf page number | +| 96 | 8 | Last leaf page number | +| 104 | 4 | Total entry count | +| 108 | 2 | Tree height | +| 110 | 18 | Reserved, zero | + +An empty tree has zero height, entry count and all three page references. +Nonempty references are at least `2`. Publication alternates metadata pages. +New nodes are appended before the new generation is published. A full tree +open verifies the highest valid generation and can fall back to the older +independently valid generation if the latest referenced graph is damaged. + +## Leaf pages + +The common page type is `4` and flags are zero. + +| Offset | Bytes | Field | +|---:|---:|---| +| 64 | 4 | ASCII `MSBL` | +| 68 | 2 | Version `2` | +| 70 | 2 | Reserved, zero | +| 72 | 2 | Entry count | +| 74 | 2 | Reserved, zero | +| 76 | 8 | Previous leaf; zero means none | +| 84 | 8 | Next leaf; zero means none | +| 92 | 4 | Reserved, zero | +| 96 | variable | Consecutive leaf entries | + +Each entry is `U16 keyLength`, `U16 valueLength`, key bytes, then value bytes. +The next entry begins exactly `4 + keyLength + valueLength` bytes later. +Keys contain 1..256 bytes; values contain 1..3584 bytes. The current node +capacity is at most 10 entries, also on larger pages. The common item count +repeats the entry count and free-start points immediately after the last +entry. Free-end remains page size. + +## Internal pages + +The common page type is `3` and flags are zero. + +| Offset | Bytes | Field | +|---:|---:|---| +| 64 | 4 | ASCII `MSBI` | +| 68 | 2 | Version `2` | +| 70 | 2 | Positive node level | +| 72 | 2 | Separator count `N` | +| 74 | 2 | Reserved, zero | +| 76 | 8 | First child page | +| 84 | 4 | Reserved, zero | +| 88 | variable | Consecutive separator records | + +A separator record is `U16 keyLength`, `U16 reservedZero`, `U64 rightChild`, +then key bytes. There are `N + 1` children. The current implementation permits +2..12 children and therefore 1..11 separators. A separator equals the first +key in its right-hand child under the key comparator. + +## Key ordering and opaque values + +The reserved `MSK` key family carries the SQL key format defined in +`index-file-v2.md`. SQL numeric components are stored without a sign-bit flip +or a big-endian transform. The comparator interprets their types to preserve +signed numeric order, including values beyond MiniLang's scalar integer range. +It compares finite binary64 words directly without string conversions or +temporary decoded SQL values. Both floating zero signs compare equal. + +Text and binary components retain byte ordering and use self-delimiting zero +escapes. Composite keys compare component by component; a complete component +prefix sorts before its extensions. This does not change the SQL optimizer's +supported access paths: partial composite predicates still need an explicitly +implemented prefix-range plan. + +Raw keys outside the reserved `MSK` family retain lexicographic byte ordering. +When a raw and a SQL key are compared, the raw key sorts first, giving a stable +total order even in a mixed tree. An unknown version in the reserved family is +an error. Leaf values are always opaque bytes: equal keys use lexicographic +value ordering, even if a value happens to begin with the `MSK` marker. diff --git a/docs/formats/catalog-bootstrap-v1.md b/docs/formats/catalog-bootstrap-v1.md index 4174fc7..64a70e0 100644 --- a/docs/formats/catalog-bootstrap-v1.md +++ b/docs/formats/catalog-bootstrap-v1.md @@ -1,5 +1,10 @@ # Database and bootstrap catalog format v1 +> Historical M8 bootstrap design. The current catalog is not limited to one +> page. See [database metadata v2 and its catalog companion](database-meta-v2.md) +> for the current `db.meta` wrapper and `BLB2` continuation-page layout. The +> catalog envelope itself remains version 1. + `db.meta` is a paged file of type database metadata and file ID 1. The bootstrap catalog is a table paged file with file ID 2. Page zero stores a length-prefixed protected envelope. diff --git a/docs/formats/catalog-v1.md b/docs/formats/catalog-v1.md index b3e88d4..4225b97 100644 --- a/docs/formats/catalog-v1.md +++ b/docs/formats/catalog-v1.md @@ -1,5 +1,10 @@ # Database metadata and catalog envelope v1 +> Historical M8 note. The database envelope now uses version 2; see +> [database metadata v2](database-meta-v2.md). The separate catalog envelope +> remains version 1 and uses scalable continuation pages as described in that +> document. Its retained version does not permit opening format-1 databases. + M8 stores `db.meta` and `catalog/catalog.tbl` as MiniSQL paged files. Page 0 contains a protected envelope. diff --git a/docs/formats/database-meta-v1.md b/docs/formats/database-meta-v1.md index 7487e40..51e23b4 100644 --- a/docs/formats/database-meta-v1.md +++ b/docs/formats/database-meta-v1.md @@ -1,5 +1,9 @@ # Database metadata format v1 envelope +> Archived format-1 design note. The current unreleased engine requires +> [database metadata v2](database-meta-v2.md); this historical sketch is not its +> byte-level specification and does not imply legacy read or upgrade support. + `db.meta` contains two fixed-capacity superblock slots. Each slot contains: - magic and metadata format version diff --git a/docs/formats/database-meta-v2.md b/docs/formats/database-meta-v2.md new file mode 100644 index 0000000..6b9bebc --- /dev/null +++ b/docs/formats/database-meta-v2.md @@ -0,0 +1,123 @@ +# Database metadata format v2 + +This is the current **unreleased storage-v2** contract. Product version 1.1.1 +is unchanged by the development patch. Database-format-1 metadata is rejected; +this format provides no legacy conversion path. + +All multibyte numeric fields below are little-endian. Offsets are relative to +the structure named in each table. UUIDs and UTF-8 names are stored as raw +bytes rather than integer values. + +## Physical file and page wrapper + +`db.meta` is a [paged file](paged-file-v1.md) with file type 4 +(`DATABASE_META`) and file ID 1. Its two 4096-byte superblocks retain version 1. +Logical page 0 stores database metadata using common page-header version 1, +page type 5 (`CATALOG`): + +| Page offset | Bytes | Field | +|---:|---:|---| +| 0 | 64 | Common page header and its header/payload CRC-32C fields | +| 64 | 4 | Length `E` of the database metadata envelope | +| 68 | `E` | Complete `MSDBM001` envelope | +| `68 + E` | remaining | Zero-filled page tail written by the current serializer | + +The metadata envelope must fit in this page. For an unencrypted file, page 0 +starts at file offset 8192, the envelope at 8260, and its payload at 8292. +With TDE, those are logical offsets after authenticated page decryption; +physical page records use the `pageSize + 28` stride described in +[encryption-envelope-v1.md](encryption-envelope-v1.md). + +The new `MSTB` user-table header does not apply to `db.meta`, the bootstrap +catalog, or security metadata files. + +## Database metadata envelope + +The generic [protected-envelope v1](protected-envelope-v1.md) **header +structure** is unchanged. Its enclosed-format version is now 2: + +| Envelope offset | Bytes | Field | +|---:|---:|---| +| 0 | 8 | ASCII magic `MSDBM001` | +| 8 | 2 | Database metadata format version = 2 | +| 10 | 2 | Kind = 1 | +| 12 | 4 | Flags = 0; no flags are currently supported | +| 16 | 4 | Payload length `N` | +| 20 | 4 | CRC-32C of exactly the `N` payload bytes | +| 24 | 4 | CRC-32C of all 32 header bytes with this field zero | +| 28 | 4 | Reserved, zero | +| 32 | `N` | Database metadata payload | + +`E` must equal `32 + N`. The unchanged ASCII suffix `001` is part of the +format-family magic; it does not supersede the explicit U16 version field. +The page checksum and both envelope checksums are validated independently. + +## Payload + +| Payload offset | Bytes | Field / required value | +|---:|---:|---| +| 0 | 4 | Database page size: 4096, 8192, 16384 or 32768 | +| 4 | 4 | Configured WAL logical segment size in bytes | +| 8 | 2 | Database format version = 2 | +| 10 | 2 | Table-file format version = 2 | +| 12 | 2 | Index-file format version = 2 | +| 14 | 2 | WAL framing version = 1 | +| 16 | 2 | Physical row format version = 2 | +| 18 | 2 | Text encoding ID = 1 (UTF-8) | +| 20 | 2 | Default collation ID = 1 (binary) | +| 22 | 2 | Database-name length `L`, in UTF-8 bytes | +| 24 | 8 | Next object ID | +| 32 | 8 | Next transaction ID | +| 40 | 8 | Checkpoint LSN | +| 48 | 16 | Database UUID | +| 64 | 4 | Reserved, zero | +| 68 | 4 | Reserved, zero | +| 72 | 8 | Reserved, zero | +| 80 | `L` | UTF-8 database name, without a terminator | + +The payload length is exactly `80 + L`. The metadata codec accepts a nonempty +name of at most 255 UTF-8 bytes; database-creation APIs apply their stricter +identifier rules before encoding. Initial values are next-object ID 3, +next-transaction ID 1 and checkpoint LSN 0. The persisted U64 identifiers and +LSNs in this payload are constrained to the supported nonnegative MiniLang +scalar range, at most `2^60 - 1`. + +There are **no payload flag bits** in this layout. Bytes 64 through 79 are all +reserved zero; they must not be repurposed as feature flags. Unknown envelope +flags, nonzero reserved fields, an unsupported version tuple, invalid lengths, +checksum failures or contradictory database identity cause open failure. +The overflow format has its own version-2 fields and is selected by database +generation 2; this fixed payload has no separate overflow-version slot. + +## Catalog companion + +`catalog/catalog.tbl` remains a paged file of type 1, file ID 2. Its catalog +envelope is still `MSCAT001`, version 1, kind 2, flags 0. This is independent of +the version-2 database envelope and user-table files. + +Current catalog writers divide the entire encoded catalog envelope into +consecutive chunks. Each page has common type 5 and this continuation header: + +| Page offset | Bytes | Field | +|---:|---:|---| +| 64 | 4 | ASCII `BLB2` | +| 68 | 2 | Continuation format version = 1 | +| 70 | 2 | Reserved, zero | +| 72 | 8 | Total encoded envelope length | +| 80 | 8 | Zero-based chunk index | +| 88 | 8 | Total chunk-page count | +| 96 | 4 | Chunk length on this page | +| 100 | 4 | Reserved, zero | +| 104 | variable | Chunk bytes, at most `pageSize - 104` | + +The catalog is therefore not restricted to one page. Continuation pages repeat +global length and page count so missing, reordered and stale pages can be +detected. The reader's retained one-page catalog representation is an +independent catalog compatibility detail; it does not bypass the database-v2 +gate or permit opening a legacy database. + +`db.meta` owns database format identity and ID high-water marks. The catalog +UUID and object metadata, user-table headers and selected file superblocks +must agree with that identity. The implementation is in +[`metadata.ml`](../../src/minisql/catalog/metadata.ml) and +[`catalog.ml`](../../src/minisql/catalog/catalog.ml). diff --git a/docs/formats/ddl-journal-v1.md b/docs/formats/ddl-journal-v1.md index 6d9445f..d60b781 100644 --- a/docs/formats/ddl-journal-v1.md +++ b/docs/formats/ddl-journal-v1.md @@ -1,6 +1,6 @@ # DDL journal format v1 -`catalog/ddl.pending` is a CRC-32C protected envelope with magic `MSDDL001` and version 1. +`catalog/ddl.pending` is a CRC-32C protected envelope with magic `MSDDLJ01` and version 1. It contains status PREPARED or COMMITTED, whether a prior schema-history file existed, complete before-images of `db.meta`, bootstrap catalog and schema history, plus arrays of temporary paths, final paths, backup originals and backup paths. diff --git a/docs/formats/heap-forwarding-v1.md b/docs/formats/heap-forwarding-v1.md index 35488ec..25b20d3 100644 --- a/docs/formats/heap-forwarding-v1.md +++ b/docs/formats/heap-forwarding-v1.md @@ -1,5 +1,9 @@ # Heap forwarding record v1 +Storage generation 2 retains this record layout. Its target page must be at +least 1 because [user-table page zero](table-file-v2.md) is reserved for the +immutable identity header. The 24-byte record fits the v2 aligned slot contract. + Forwarding records are 24 bytes: magic `MSFW`, version 1, reserved zero, U64 page number, U32 slot ID, U16 generation and U16 reserved zero. Resolution is bounded to 64 links and rejects cycles. diff --git a/docs/formats/index-file-v1.md b/docs/formats/index-file-v1.md index 220371d..8251e6b 100644 --- a/docs/formats/index-file-v1.md +++ b/docs/formats/index-file-v1.md @@ -1,5 +1,9 @@ # Index file format v1 envelope +> Archived format-1 notes. See [SQL index keys and values v2](index-file-v2.md) +> and [B+ tree v2](btree-v2.md) for the current implementation. Legacy index +> metadata and v1 SQL-key/INCLUDE representations are unsupported. + Page zero contains: - index magic and index-file format version diff --git a/docs/formats/index-file-v2.md b/docs/formats/index-file-v2.md new file mode 100644 index 0000000..35c15b2 --- /dev/null +++ b/docs/formats/index-file-v2.md @@ -0,0 +1,101 @@ +# SQL index keys and values v2 + +SQL indexes are B+ trees described in `btree-v2.md`, with shared paged-file +superblocks. Catalog metadata owns the index key schema, table identity and +INCLUDE column order. Version 1 is not accepted by this format. + +## SQL key envelope + +| Offset | Bytes | Field | +|---:|---:|---| +| 0 | 3 | ASCII `MSK` (reserved typed-key family) | +| 3 | 1 | SQL key version `2` | +| 4 | variable | One or more self-delimiting typed components | + +The complete encoded key, including this prefix, is limited to 256 bytes. +Components have a one-byte tag followed by the payload below. + +| Tag | SQL types | Component payload | +|---:|---|---| +| `01` | NULL of any type | Empty | +| `02` | BOOLEAN | One byte: `00` or `01` | +| `03` | SMALLINT, INTEGER, BIGINT, DECIMAL, DATE, TIME, TIMESTAMP | Plain signed 64-bit two's-complement **little-endian** | +| `04` | REAL, DOUBLE | IEEE-754 binary64 **little-endian**, 8 bytes | +| `05` | CHAR, VARCHAR, TEXT | Escaped UTF-8 bytes followed by `00 00` | +| `06` | BINARY, VARBINARY, BLOB | Escaped raw bytes followed by `00 00` | + +DECIMAL uses its already-scaled integer value and temporal values use their +existing integer units; precision, scale and type identity remain catalog +metadata. REAL and DOUBLE both use the runtime's binary64 precision. NaN and +infinity are rejected by the codec and the typed-key validator. + +Every zero byte in a variable-width payload is encoded as `00 FF`. Other +bytes are unchanged. The terminator is `00 00`, so adjacent components remain +unambiguous, including empty values and embedded zero bytes. + +### Numeric ordering + +The key comparator reads numeric payloads as values. Integers compare signed +high words and then unsigned low words; floating values compare IEEE-754 +magnitude words with the order reversed for negative values. No stored sign +bit is flipped and no key integer is stored big-endian. Different component +tags sort by tag number; a valid SQL index fixes each position's type through +its catalog schema, while NULL sorts first at that position. + +Persisted keys and INCLUDE values preserve both floating zero signs. The tree +comparator equates their numerical values for searches and uniqueness. Only +ephemeral constraint hash keys canonicalize zero, because byte hashing has no +numeric comparator. Covering equality scans return the actual stored keys, +not a reconstruction from the search literal, so looking up positive zero +still returns a stored negative zero with its original bits. + +Examples: + +```text +INTEGER 1: 4D 53 4B 02 03 01 00 00 00 00 00 00 00 +INTEGER -1: 4D 53 4B 02 03 FF FF FF FF FF FF FF FF +INTEGER 256: 4D 53 4B 02 03 00 01 00 00 00 00 00 00 +DOUBLE 0.1: 4D 53 4B 02 04 9A 99 99 99 99 99 B9 3F +TEXT Nils: 4D 53 4B 02 05 4E 69 6C 73 00 00 +``` + +## Ordinary leaf values + +The physical row reference occupies exactly 12 bytes. Every multi-byte field +is little-endian. + +| Offset | Bytes | Field | +|---:|---:|---| +| 0 | 4 | Heap page number | +| 4 | 2 | Slot ID | +| 6 | 2 | Slot generation | +| 8 | 4 | Table ID | + +An index without INCLUDE columns ends at byte 12. The stable slot generation +guards against treating a reused slot as the previous row. + +## Covering leaf values + +| Offset | Bytes | Field | +|---:|---:|---| +| 0 | 12 | Physical row reference | +| 12 | 3 | ASCII `MSI` | +| 15 | 1 | INCLUDE payload version `2` | +| 16 | variable | One typed component per catalog-ordered INCLUDE column | + +INCLUDE components use the same tags and payload widths as keys, without an +`MSK` prefix. Their REAL/DOUBLE payloads are binary64 and are decoded directly +for index-only scans; no textual floating representation or float-specific +heap fallback remains. The payload does not duplicate column names or count. +Absent or mismatched version markers, truncated components, trailing bytes, +non-finite floating data and catalog type mismatches are corruption errors. +Leaf values remain limited to 3584 bytes on every supported page size. + +## Regression coverage + +`src/tests/storage_v2_indexes.ml` checks byte goldens, signed INT64 limits, +255/256 ordering, IEEE-754 finite extremes/subnormals, zero signs, malformed +encodings, composite prefix bounds, escaped bytes, opaque value tie ordering, +unique/range/reopen behavior and rejection of v1 metadata. Its SQL scenarios +compare floating index-only results to heap results, verify INCLUDE values +bit for bit, and repeat reads after reopen and mutation. diff --git a/docs/formats/overflow-v1.md b/docs/formats/overflow-v1.md index 0b93ec3..4483d38 100644 --- a/docs/formats/overflow-v1.md +++ b/docs/formats/overflow-v1.md @@ -1,5 +1,10 @@ # Overflow pointer and page format v1 +> Archived format-1 design notes. The current byte layout, including the U32 +> length and independent pointer CRC, is specified in +> [overflow v2](overflow-v2.md). Version-1 pointers and chain pages are rejected; +> the historical summary below is not the current serializer contract. + ## External pointer — 48 bytes The pointer stores magic/version, file ID, first page, total length (U32), owner ID, diff --git a/docs/formats/overflow-v2.md b/docs/formats/overflow-v2.md new file mode 100644 index 0000000..09ddcc7 --- /dev/null +++ b/docs/formats/overflow-v2.md @@ -0,0 +1,53 @@ +# Overflow pointer and page format v2 + +Storage generation 2 deliberately rejects v1 pointers and overflow pages. All +fixed-width numeric fields are little-endian. Large TEXT/BLOB values retain the +existing page-chain representation; their total byte length is now explicitly +U32 in both the row pointer and every chain page. + +## External pointer: 48 bytes + +Offsets are relative to the start of the external value in a row. The row aligns +this pointer to eight bytes, so its U64 identifiers are naturally aligned. + +| Offset | Bytes | Field | +|---:|---:|---| +| 0 | 4 | ASCII `MSOP` | +| 4 | 2 | version = 2 | +| 6 | 2 | reserved, zero | +| 8 | 8 | file ID | +| 16 | 8 | first logical overflow page | +| 24 | 4 | total value length, U32 | +| 28 | 4 | reserved alignment bytes, zero | +| 32 | 8 | owner ID | +| 40 | 4 | CRC-32C of the complete external value | +| 44 | 4 | CRC-32C of all 48 pointer bytes, this field zeroed | + +The four bytes at 28 are not the high word of a length. Values larger than +4,294,967,295 bytes are rejected before allocation. An empty value has length +zero, no chain, and first page `UINT64_MAX`. Pointer CRC validation is independent +of the containing row's page checksum and the external value's checksum. + +## Chain pages + +Each page begins with the common 64-byte `MSPG` header, type 2. The user table's +logical page zero is reserved for its table header; overflow chains use data +pages following it. + +| Page offset | Bytes | Field | +|---:|---:|---| +| 64 | 4 | ASCII `MSOV` | +| 68 | 2 | version = 2 | +| 70 | 2 | reserved, zero | +| 72 | 8 | owner ID | +| 80 | 8 | next page; `UINT64_MAX` terminates the chain | +| 88 | 4 | chunk byte length | +| 92 | 4 | total value byte length, U32 | +| 96 | 4 | zero-based sequence number | +| 100 | 4 | reserved, zero | +| 104 | variable | chunk bytes | + +A page carries at most `pageSize - 104` chunk bytes. The reader checks page +identity, version, checksums, owner, sequence, length and termination before +returning a value. The SQL writer externalizes TEXT/BLOB values larger than +`pageSize / 4`; that policy is unchanged. diff --git a/docs/formats/page-v1.md b/docs/formats/page-v1.md index be1e174..7c57f19 100644 --- a/docs/formats/page-v1.md +++ b/docs/formats/page-v1.md @@ -1,5 +1,10 @@ # Page format v1 +Storage generation 2 retains this 64-byte header. Its payload contracts are +versioned separately; page type 6 identifies the +[user-table metadata page](table-file-v2.md). Header version 1 alone does not +identify a legacy database or make new payloads compatible with older readers. + All fields are little-endian. Header size is 64 bytes. | Offset | Size | Field | diff --git a/docs/formats/paged-file-v1.md b/docs/formats/paged-file-v1.md index 59c9ec4..a265e3d 100644 --- a/docs/formats/paged-file-v1.md +++ b/docs/formats/paged-file-v1.md @@ -1,5 +1,11 @@ # Paged file format v1 +Storage generation 2 retains this superblock layout. The offsets below describe +plaintext pages. With feature bit 0 set, physical page records have stride +`pageSize + 28`; see [encryption-envelope-v1.md](encryption-envelope-v1.md). +Current user-table and index payloads follow [table v2](table-file-v2.md) and +[B+ tree v2](btree-v2.md), independently of the superblock version. + A paged file has a fixed 8192-byte metadata region independent of its persisted page size. diff --git a/docs/formats/row-v1.md b/docs/formats/row-v1.md index 03993b3..58937e3 100644 --- a/docs/formats/row-v1.md +++ b/docs/formats/row-v1.md @@ -1,5 +1,9 @@ # Row format v1 +> Archived format-1 specification. Current rows use aligned fields and binary +> floating-point values described in [row v2](row-v2.md). Version-1 records are +> rejected, including their former decimal-text floating representation. + All fixed-width fields are little-endian. | Offset | Size | Field | diff --git a/docs/formats/row-v2.md b/docs/formats/row-v2.md new file mode 100644 index 0000000..22eee4c --- /dev/null +++ b/docs/formats/row-v2.md @@ -0,0 +1,95 @@ +# Row format v2 + +Version 2 is intentionally incompatible with row format v1. Readers reject an +`MSRW` record whose row format version is not 2. All fixed-width integers and +floating-point values use little-endian byte order. Every row starts at an +eight-byte-aligned offset in its containing slotted page, and its encoded length +is a multiple of eight bytes. + +## Header + +Offsets below are relative to the start of the row. + +| Offset | Size | Field | +|---:|---:|---| +| 0 | 4 | ASCII magic `MSRW` | +| 4 | 2 | U16 row format version = 2 | +| 6 | 2 | U16 schema version, 1..65535 | +| 8 | 2 | U16 stored column count, 1..4095 | +| 10 | 2 | U16 NULL-bitmap byte count: `ceil(columnCount / 8)` | +| 12 | 2 | U16 directory offset: `align8(16 + nullBitmapBytes)` | +| 14 | 2 | Reserved zero | + +The NULL bitmap begins at byte 16. Column `i` uses bit `i % 8`, least-significant +bit first, in bitmap byte `i / 8`. Unused bitmap bits are zero. Zero bytes fill +the gap between the bitmap and the aligned directory. + +## Column directory and value alignment + +Each directory entry is eight bytes: U16 type code, U16 flags, U16 value offset, +and U16 value length. Value offsets are relative to the row start. The directory +is followed by the values in column order. Immediately before each non-NULL +value, its offset is rounded up to the alignment below; the introduced padding +must be zero. + +| Type code | SQL type | Width / representation | Alignment | +|---:|---|---|---:| +| 1 | BOOLEAN | One byte, 0 or 1 | 1 | +| 2 | SMALLINT | Signed 16-bit | 2 | +| 3 | INTEGER | Signed 32-bit | 4 | +| 4 | BIGINT | Signed 64-bit, two's complement | 8 | +| 5 | REAL | IEEE-754 binary64 | 8 | +| 6 | DOUBLE | IEEE-754 binary64 | 8 | +| 7 | DECIMAL | Signed 64-bit coefficient; scale comes from schema | 8 | +| 8 | CHAR | UTF-8, padded with ASCII spaces to declared byte length | 1 | +| 9 | VARCHAR | UTF-8 | 1 | +| 10 | TEXT | UTF-8 or external pointer | 1 / 8 | +| 11 | BINARY | Exact-length raw bytes | 1 | +| 12 | VARBINARY | Raw bytes | 1 | +| 13 | BLOB | Raw bytes or external pointer | 1 / 8 | +| 14 | DATE | Signed 32-bit epoch-day count | 4 | +| 15 | TIME | Signed 64-bit microsecond count | 8 | +| 16 | TIMESTAMP | Signed 64-bit epoch-microsecond count | 8 | + +Flags are exactly 0 for an inline value, 1 for SQL NULL, or 2 for an external +TEXT/BLOB pointer. Other values, including the combination 3, are invalid. A NULL +must agree with the bitmap, have length zero, and use the current value cursor +without adding padding. External pointers use eight-byte alignment regardless +of whether the logical column is TEXT or BLOB. An empty inline string has length +zero, flag 0, and a clear NULL bit. + +The row ends at the next eight-byte boundary after its last value. All tail +padding is zero. Readers reject noncanonical value offsets, nonzero directory, +inter-value or tail padding, extra tail blocks, truncated values, and rows whose +length is not a multiple of eight. The U16 fields limit encoded row size to +65528 bytes; the containing page imposes the smaller practical inline limit. + +## Floating-point values + +Both REAL and DOUBLE retain MiniSQL's existing logical binary64 precision. Each +uses eight binary bytes, rather than v1's decimal text rendering. The codec +preserves positive and negative zero, subnormals, and the entire 53-bit +significand. NaN and infinities are rejected on input and when decoding stored +bytes, giving SQL comparisons and indexes a defined finite-value domain. + +The implementation uses native `frexp`, `ldexp`, and `copysign` with exact +integer mantissa packing. It does not inspect MiniLang's tagged-value object +layout or convert through decimal text. Linux uses libm and Windows uses the +CRT. The same byte layout is produced on both targets. + +## Example + +For schema version 1 with `(BIGINT 1, TEXT 'Nils', BOOLEAN true)`, the directory +begins at 24, values are at offsets 48, 56 and 60, and total row length is 64: + +```text +4d 53 52 57 02 00 01 00 03 00 01 00 18 00 00 00 +00 00 00 00 00 00 00 00 04 00 00 00 30 00 08 00 +0a 00 00 00 38 00 04 00 01 00 00 00 3c 00 01 00 +01 00 00 00 00 00 00 00 4e 69 6c 73 01 00 00 00 +``` + +The 16-byte header is followed by the one-byte bitmap and seven zero alignment +bytes, three directory entries, thirteen value bytes, and three zero tail bytes. +Schema-compatible decoding still accepts an older stored column prefix; missing +trailing columns are materialized by the executor from schema defaults. diff --git a/docs/formats/slotted-page-v1.md b/docs/formats/slotted-page-v1.md index a6f5d31..bca7be1 100644 --- a/docs/formats/slotted-page-v1.md +++ b/docs/formats/slotted-page-v1.md @@ -1,5 +1,9 @@ # Slotted-page payload format v1 +> Archived unaligned payload contract. Current tables use +> [slotted-page payload v2](slotted-page-v2.md), selected by database/table +> format 2 even though the common page-header version remains 1. + The common MiniSQL page header occupies bytes 0-63. Slots begin at byte 64 and are 8 bytes: | Relative offset | Size | Field | diff --git a/docs/formats/slotted-page-v2.md b/docs/formats/slotted-page-v2.md new file mode 100644 index 0000000..cd5a345 --- /dev/null +++ b/docs/formats/slotted-page-v2.md @@ -0,0 +1,54 @@ +# Slotted-page payload format v2 + +The common MiniSQL page header remains bytes 0..63. Each slot-directory entry +is eight bytes, starting at `64 + 8 * slotId`: + +| Relative offset | Size | Field | +|---:|---:|---| +| 0 | 2 | U16 record offset relative to the page, divisible by 8 | +| 2 | 2 | U16 logical record length, excluding allocation padding | +| 4 | 2 | U16 slot state | +| 6 | 2 | U16 generation, 1..65535 | + +All integer fields use little-endian byte order. Slot states retain their +defined values: 0 live, 1 deleted, 2 forwarding root, 3 internal forwarding, +and 4 moved. These are enumerated states, not combinable flags. Deleted slots +have zero offset and length. Their generation advances on deletion; generation +65535 is retired rather than wrapped. + +## Aligned allocation + +Each nondeleted record occupies `align8(logicalLength)` bytes. Its body begins +at an eight-byte-aligned offset. Any bytes between its logical end and the end +of this allocation must be zero. This permits arbitrary nonempty record bodies, +including forwarding records and catalog payloads, without changing what a +caller reads back from the slot. Row-format-v2 bodies already have aligned +lengths and therefore need no additional slot-level padding. + +The slot directory grows upward while aligned record allocations grow downward +from the page end. `freeStart = 64 + 8 * slotCount`; `freeEnd` is eight-byte +aligned. The reusable contiguous free-space count is `freeEnd - freeStart`. +An insertion requires the aligned allocation plus eight directory bytes when +no deleted slot can be reused. Insert, update and compaction all use the same +allocation-size calculation. + +Validation includes padding bytes in overlap and compactness checks: allocated +ranges must cover exactly `[freeEnd, pageSize)` without gaps or overlap, and all +padding must be zero. Nonaligned offsets, malformed lengths or nonzero padding +are rejected even when the common page checksums are otherwise valid. + +Compaction can relocate bodies but preserves slot IDs and generations. All +mutations are built on a working page and validated before replacing the input, +so a failed insertion or update leaves the original bytes unchanged. + +## Example + +On an empty 4096-byte page, inserting a three-byte record allocates eight bytes +at offset 4088. Its slot records length 3, and bytes 4091..4095 are zero padding. +After a nine-byte record is inserted, that record owns sixteen bytes beginning +at 4072. The two slots occupy 16 bytes and the two allocations occupy 24 bytes; +the remaining free space is `4096 - 64 - 16 - 24 = 3992` bytes. + +The page-header version is unchanged. Database/table format version 2 selects +this payload contract. Legacy databases are rejected; this patch provides no +legacy import or in-place conversion. diff --git a/docs/formats/sort-spill-v1.md b/docs/formats/sort-spill-v1.md index 856e54c..fb7fe2f 100644 --- a/docs/formats/sort-spill-v1.md +++ b/docs/formats/sort-spill-v1.md @@ -1,5 +1,9 @@ # External sort spill v1 +The current storage-v2 engine retains this spill container version and encodes +its contained rows with [row format 2](row-v2.md). This is not a legacy-row +compatibility path; spill files are temporary process-local work products. + Temporary M46 sort runs use magic `MSSPILL1` and version 1. The fixed 16-byte header contains the magic, version, projected-value count, order-value count, and a reserved zero field. Each row is encoded with the existing row codec and diff --git a/docs/formats/statistics-v1.md b/docs/formats/statistics-v1.md index dd8f377..f3ca332 100644 --- a/docs/formats/statistics-v1.md +++ b/docs/formats/statistics-v1.md @@ -1,3 +1,8 @@ # Statistics format v1 +> Historical statistics baseline. The current writer uses sidecar version 5; +> see the [development upgrade guide](../release/UPGRADE.md). Statistics +> versions are independent of [database storage v2](database-meta-v2.md), and +> this short v1 sketch is not a complete description of the current writer. + File: `catalog/statistics.tbl`. Protected-envelope magic `MSSTAT01`, version 1, kind 50. The payload stores database UUID, generation, table records and column records. Native-range lengths/counts are bounded before allocation. CRC failure, unknown reserved fields, wrong identity and trailing data are fatal. diff --git a/docs/formats/storage-v2.md b/docs/formats/storage-v2.md new file mode 100644 index 0000000..c87c4e3 --- /dev/null +++ b/docs/formats/storage-v2.md @@ -0,0 +1,72 @@ +# Storage format 2 + +This is the normative format for the current development tree. It is an +intentional compatibility break: databases created with storage format 1 do not +open with this implementation. There is no automatic format-1 migration. + +## Changes + +| Area | Format 2 contract | Detailed layout | +|---|---|---| +| REAL / DOUBLE | Both use 8-byte IEEE-754 binary64, little-endian; no decimal text conversion | [Row v2](row-v2.md) | +| Alignment | Row start and length are multiples of 8; fixed-width values are naturally aligned; every padding byte is zero | [Row v2](row-v2.md), [slotted pages v2](slotted-page-v2.md) | +| User tables | Logical page 0 is a mandatory immutable `MSTB` metadata page; data pages start at 1 | [Table file v2](table-file-v2.md) | +| Overflow | Total length is U32 at pointer offset 24; the aligned pointer remains 48 bytes and has its own CRC-32C | [Overflow v2](overflow-v2.md) | +| SQL indexes | Signed integral components use I64LE; floating components use binary64LE; typed comparison supplies numeric ordering | [Index file v2](index-file-v2.md), [B+ tree v2](btree-v2.md) | + +REAL retains its existing MiniSQL binary64 precision; this change does not narrow +it to binary32. The floating codec preserves finite values exactly, including +subnormals and both zero signs. NaN and infinities are rejected. Index comparison +treats both zero signs as equal; an INCLUDE payload preserves the value's sign. + +Little-endian numeric index bytes are not lexicographically sortable. For +example, integer 255 ends in the component bytes `ff 00 00 00 00 00 00 00`, while +256 uses `00 01 00 00 00 00 00 00`. The typed B+ tree comparator still orders 255 +before 256. SQL keys begin with `MSK` and byte 2; raw keys outside this reserved +family retain their bytewise ordering. Leaf values remain opaque byte strings. + +The 48-byte overflow pointer intentionally retains four zero alignment bytes at +offset 28, so the owner ID remains U64-aligned at offset 32. They are reserved +bytes, not part of the U32 length. The last four bytes now protect the pointer +itself with CRC-32C. The maximum external length remains 4,294,967,295 bytes. + +## Version identities + +`minisql.common.format_version` is the single registry for the affected formats. + +| Identifier | Version | +|---|---:| +| Database metadata envelope and database identity | 2 | +| Table header | 2 | +| Row | 2 | +| Overflow pointer and chain page payload | 2 | +| Index metadata, B+ tree payload, typed key and INCLUDE payload | 2 | +| Generic superblock, common page and WAL framing | 1 | +| Wire protocol | 1 | + +Configuration defaults and persisted database metadata require the version tuple +`database=2, table=2, index=2, wal=1, row=2`. Changing a configuration file or a +version field does not convert old data. Unknown versions and mixed old/new +identities are rejected. The generic 32-byte protected-envelope structure is +unchanged; its database-specific version field is now 2. + +## Validation + +Run the focused gate on its native host: + +```powershell +./test.ps1 -StorageV2 -Target linux-x64 -Compiler ../MiniLangCompilerPy/mlc_win64.py +``` + +Use `-Target windows-x64` on Windows. The internal portable runner also supports +`--integration` to include the relevant catalog, heap, overflow, B+ tree, WAL, +recovery, SQL, schema-evolution, maintenance, migration and encryption suites. +Every invocation uses fresh directories under `build/storage-v2/gates` and saves +compiler logs, test logs and `results.json`. `--compile-only` explicitly records +a compilation check without claiming native execution. + +The new format tests cover exact byte vectors, old-format rejection, checksummed +corruptions, alignment and padding, full signed integer range, floating-point +edge cases, index ordering/uniqueness, persistence after reopening, and index-only +results compared bit for bit against heap values. Historical release acceptance +reports remain historical evidence; they are not a new Windows acceptance run. diff --git a/docs/formats/table-file-v1.md b/docs/formats/table-file-v1.md index f2806c0..884132e 100644 --- a/docs/formats/table-file-v1.md +++ b/docs/formats/table-file-v1.md @@ -1,5 +1,9 @@ # Table file format v1 envelope +> Archived format-1 design note. The implemented current layout is +> [table file v2](table-file-v2.md), with a mandatory immutable header page 0. +> The current engine does not read or convert legacy table files. + Page zero contains redundant/validated table identity metadata: - table magic and table-file format version diff --git a/docs/formats/table-file-v2.md b/docs/formats/table-file-v2.md new file mode 100644 index 0000000..393c53b --- /dev/null +++ b/docs/formats/table-file-v2.md @@ -0,0 +1,62 @@ +# Table file format v2 + +Every user/heap table reserves logical page **0** for an immutable table header. +Heap and overflow pages begin at page 1. An empty table therefore consists of +the two 4096-byte paged-file superblocks and one logical page. Catalog and +security files use their own page formats despite sharing the paged-file table +type; they do not contain this user-table header. + +The paged-file superblock and common page-header formats remain version 1. +Database, table and physical row formats are version 2. A table with no header, +heap data on page zero, or an older table/row version is rejected; there is no +implicit upgrade or legacy decoder. + +## Immutable page-zero layout + +All multibyte integers are little-endian. Offsets below are relative to the +decrypted logical page, whose size is `P`. + +| Offset | Bytes | Field | +|---:|---:|---| +| 0 | 64 | Common page header: type 6 (`TABLE_META`), file ID, page number 0, page LSN 0, creation generation, item count 0, free-start 128, free-end `P`, flags 0 | +| 64 | 4 | ASCII magic `MSTB` | +| 68 | 2 | Table format version = 2 | +| 70 | 2 | Occupied table-header bytes = 128 | +| 72 | 16 | Database UUID, raw bytes | +| 88 | 8 | Table/file object ID | +| 96 | 4 | Database page size `P` | +| 100 | 2 | Checksum algorithm ID = 1 (CRC-32C) | +| 102 | 2 | Physical row format version = 2 | +| 104 | 8 | Nonzero immutable creation generation | +| 112 | 8 | First permitted heap/overflow page = 1 | +| 120 | 8 | Reserved, zero | +| 128 | `P - 128` | Reserved, zero | + +The common page header contains the payload CRC-32C at offset 56 and header +CRC-32C at offset 60. Its payload CRC covers bytes 64 through `P - 1`, including +all table metadata and the reserved tail. No duplicate checksum is necessary. +The table ID, database UUID and page size must match the selected superblock. +The common header generation must equal the persisted creation generation, +which cannot exceed the current superblock generation. + +Page zero is created and made durable before any data allocation. It does not +store mutable page-count or free-page hints: the selected superblock owns the +physical allocation frontier, while derived heap-page directories exclude +page zero. This avoids a second potentially stale allocation authority. + +## Physical offsets and encryption + +For unencrypted paged files, page zero begins at file offset 8192, and logical +page `n` begins at `8192 + n * P`. With page encryption enabled, the superblocks +remain plaintext and each logical page is stored in a record of `P + 28` bytes: +12-byte nonce, `P` bytes of ciphertext, and 16-byte GCM tag. The table header is +inside the encrypted page-zero payload and is checked after authentication. + +## Open and maintenance requirements + +Writable, shared read-only and database-managed read-only user-table opens all +verify page-zero checksums, identity, versions and reserved fields. Catalog +startup validation additionally compares the physical table identity with the +database/catalog identity. DDL creation, heap creation, VACUUM/rewrite and +offline page-size migration create a fresh valid page-zero header before +inserting rows. Row IDs and heap-page directories cannot reference page zero. diff --git a/docs/formats/wal-v1.md b/docs/formats/wal-v1.md index d640389..68f39e2 100644 --- a/docs/formats/wal-v1.md +++ b/docs/formats/wal-v1.md @@ -1,5 +1,9 @@ # WAL record format v1 +Storage generation 2 retains this framing. Current page-image payloads contain +the matching [storage-v2](README.md#current-storage-generation-2) page content; +the retained WAL version does not provide cross-generation database recovery. + All fields are little-endian. M6 stores records consecutively in one physical file. The configured segment size defines logical segment number and offset only. @@ -21,8 +25,13 @@ configured segment size defines logical segment number and offset only. | 56 | 8 | pageLSN | | 64 | 4 | payload CRC-32C | | 68 | 4 | header CRC-32C with this field zeroed | -| 72 | 8 | reserved, zero | +| 72 | 8 | zero for plaintext; ASCII `TDE1WAL1` for an encrypted payload | Payload bytes immediately follow. M6 types are 1 `TX_BEGIN`, 2 `PAGE_IMAGE`, 3 `TX_COMMIT` and 4 `TX_ABORT`; 5/6 reserve checkpoint begin/end. Non-page records use zero file/page IDs. A page-image payload is a complete verified page whose identity and pageLSN match the header. + +Encrypted payload framing is nonce (12 bytes), ciphertext, and GCM tag +(16 bytes), as defined in [encryption-envelope-v1.md](encryption-envelope-v1.md). +The record flags retain their application meaning; encryption is identified by +the separate marker at offset 72. diff --git a/docs/module-catalog.json b/docs/module-catalog.json index 4e61886..e3255bb 100644 --- a/docs/module-catalog.json +++ b/docs/module-catalog.json @@ -504,6 +504,24 @@ "package": "minisql.tools.encryption", "component": "tools.encryption", "targetMilestone": "M79" + }, + { + "path": "src/minisql/common/format_version.ml", + "package": "minisql.common.format_version", + "component": "common.format_version", + "targetMilestone": "StorageV2" + }, + { + "path": "src/minisql/common/float_codec.ml", + "package": "minisql.common.float_codec", + "component": "common.float_codec", + "targetMilestone": "StorageV2" + }, + { + "path": "src/minisql/storage/table_header.ml", + "package": "minisql.storage.table_header", + "component": "storage.table_header", + "targetMilestone": "StorageV2" } ] } diff --git a/docs/release/UPGRADE.md b/docs/release/UPGRADE.md index 31e7f0a..f55c2f9 100644 --- a/docs/release/UPGRADE.md +++ b/docs/release/UPGRADE.md @@ -1,26 +1,58 @@ -# MiniSQL 1.0 upgrade guide - -All accepted M8–M49 databases use database format 1 and can be opened directly by -MiniSQL 1.0. The first open may create auxiliary files introduced by later -milestones, such as the security catalog or durable WAL marker. - -Always make a verified backup before upgrading. Run the consistency checker -before and after. Page-size changes require an offline source-to-target rewrite; -never edit `db.meta` or file headers manually. Downgrading after using a feature -unknown to the older engine is not supported even when the physical format is -unchanged. - -The native CRC-32C acceleration is an executable-only change. It preserves the -Castagnoli polynomial, initial/final XOR, and incremental state exactly, so it -requires no database rewrite and remains readable by earlier format-1 binaries. - -Optimizer statistics use sidecar format 5 to persist the bounded sample count, -compact numeric/date equi-depth bounds, integral or hashed most-common values, -and joint distinct counts plus tuple MCVs for composite index keys. The -current reader accepts format 1 as an exact full-table sample, format 2 as -sampled statistics without range bounds, and format 3 as bounds without the new -distributions, plus format 4 as the legacy integral distribution layout. A -subsequent `ANALYZE` atomically writes format 5. This does not -change database page format 1 or wire protocol 1. Older MiniSQL binaries do not -understand a format-5 statistics sidecar; remove only -`catalog/statistics.tbl` and rerun `ANALYZE` after a deliberate downgrade. +# Unreleased storage-v2 development guide + +This development patch intentionally changes the database format to **2**. +The product-version string remains **1.1.1**. Existing 1.1.1 release artifacts +and historical test reports refer to their original builds; their database +compatibility and acceptance evidence have not been relabeled as storage-v2 +evidence. + +## Existing databases are rejected + +The current engine does not open database-format-1 files, including databases +created by the M8-M50 milestones or earlier 1.0.0, 1.1.0 and 1.1.1 builds. +It supplies **no automatic upgrade, legacy import or in-place conversion**. +The development format is intended for newly created databases. Existing data +must continue to be accessed with its compatible older build; no data-transfer +procedure is promised by this patch. + +Changing configuration defaults or editing a version number cannot convert a +database. The representation changed for REAL/DOUBLE values, row alignment, +table page zero, overflow pointers and numeric index keys. Retain existing +files separately when trying this development tree. New storage-v2 databases +cannot be opened by format-1 binaries. + +## What changed and what retained its framing + +The required database/table/index/WAL/row version tuple is `2/2/2/1/2`. +Overflow pointers and chain pages also use version 2. `db.meta` uses the same +32-byte protected-envelope structure, with its own envelope version set to 2. +User tables reserve page zero for their checked immutable identity header. + +The 64-byte common page header, 4096-byte superblock slots, WAL record framing, +wire protocol, and encryption-record framing retain their existing versions. +These retained wrappers can contain new storage-v2 data; they do not provide +cross-generation compatibility. The catalog envelope and auxiliary metadata +retain their independently defined versions. + +## Tools and backups + +The consistency checker and backup/restore paths enforce the current database +format. A backup created by the current engine contains a storage-v2 database; +an unchanged backup-manifest or archive version is not a legacy-import path. +WAL page images must belong to the matching database generation and identity. + +Offline page-size rewriting is available between databases already supported +by this engine. It creates a fresh storage-v2 target and verifies it before +publication. It is **not** a format-1 to format-2 upgrader. Supported database +page sizes remain 4096, 8192, 16384 and 32768 bytes. + +Optimizer-statistics sidecar evolution is independent of this change: the +writer uses version 5 and its reader retains the supported earlier statistics +representations. Such sidecar compatibility is evaluated only after a database +passes the storage-v2 format gate. Removing a sidecar cannot make the database +compatible with an older engine. + +See the [format index](../formats/README.md), +[compatibility contract](../formats/FORMAT_COMPATIBILITY.md), and +[machine-readable matrix](upgrade-matrix.json) for the current development +state. Dated release reports remain historical evidence for their named builds. diff --git a/docs/release/feature-matrix.json b/docs/release/feature-matrix.json index a90af8d..312887f 100644 --- a/docs/release/feature-matrix.json +++ b/docs/release/feature-matrix.json @@ -13,6 +13,6 @@ "windows-x64": "complete 106-phase release gate and concurrent-server acceptance", "linux-x64": "focused portable gate with concurrent multi-client server and native TLS; full 106-phase release matrix remains Windows-specific" }, - "databaseFormatVersion": 1, + "databaseFormatVersion": 2, "wireProtocolVersion": 1 } diff --git a/docs/release/upgrade-matrix.json b/docs/release/upgrade-matrix.json index d127c68..8807465 100644 --- a/docs/release/upgrade-matrix.json +++ b/docs/release/upgrade-matrix.json @@ -1,15 +1,31 @@ { "matrixVersion": 1, "targetVersion": "1.1.1", - "databaseFormatVersion": 1, + "developmentState": "unreleased-storage-v2", + "databaseFormatVersion": 2, + "formatVersions": { + "database": 2, + "table": 2, + "index": 2, + "row": 2, + "overflow": 2, + "wal": 1, + "page": 1, + "superblock": 1, + "protectedEnvelopeStructure": 1, + "wire": 1 + }, "entries": [ - {"source": "M8-M20", "open": true, "automaticAdditions": ["security catalog", "audit metadata", "durable WAL marker"]}, - {"source": "M21-M31", "open": true, "automaticAdditions": ["durable WAL marker", "schema extensions when needed"]}, - {"source": "M32-M47", "open": true, "automaticAdditions": ["durable WAL marker"]}, - {"source": "1.0.0", "open": true, "automaticAdditions": []}, - {"source": "1.1.0", "open": true, "automaticAdditions": []}, - {"source": "1.1.1", "open": true, "automaticAdditions": []} + {"source": "M8-M20", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "M21-M31", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "M32-M50", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "1.0.0", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "1.1.0", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "1.1.1 (earlier format-1 build)", "sourceDatabaseFormatVersion": 1, "open": false, "automaticAdditions": []}, + {"source": "1.1.1 (current unreleased storage-v2 build)", "sourceDatabaseFormatVersion": 2, "open": true, "automaticAdditions": []} ], - "pageSizeChange": "offline rewrite only", - "downgrade": "not supported after use of newer logical features" + "automaticStorageUpgrade": false, + "legacyDatabaseImport": "not implemented", + "pageSizeChange": "offline rewrite between supported storage-v2 databases only", + "downgrade": "storage-v2 databases cannot be opened by storage-v1 binaries" } diff --git a/src/minisql/catalog/catalog.ml b/src/minisql/catalog/catalog.ml index ae535fb..7eee15f 100644 --- a/src/minisql/catalog/catalog.ml +++ b/src/minisql/catalog/catalog.ml @@ -14,6 +14,7 @@ import minisql.config.model as config_model import minisql.platform.file as file_api import minisql.storage.page as page import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.superblock as superblock import minisql.transaction.checkpoint as checkpoint import minisql.transaction.wal as wal @@ -465,7 +466,7 @@ end function function validateTableFiles(path, databaseMetadata, catalogState) for each table in catalogState.tables tablePath = tableFilePath(path, table.tableId) - opened = try(paged_file.open(tablePath)) + opened = try(table_header.open(tablePath)) if typeof(opened) == "error" then return fail(CORRUPT_DATA, "validateTableFiles", "table file is missing or unreadable for table " + table.name) end if valid = opened.fileType == superblock.FILE_TYPE_TABLE and opened.fileId == table.tableId and opened.pageSize == databaseMetadata.pageSize and bytesEqual(opened.databaseId, databaseMetadata.databaseId) paged_file.close(opened) @@ -643,7 +644,7 @@ function createTable(database, name, definitions) physicalPath = tableFilePath(database.path, tableId) if file_api.pathExists(physicalPath) then return fail(OBJECT_EXISTS, "createTable", "table file already exists") end if - physical = paged_file.create(physicalPath, database.metadata.pageSize, superblock.FILE_TYPE_TABLE, tableId, database.metadata.databaseId) + physical = table_header.create(physicalPath, database.metadata.pageSize, tableId, database.metadata.databaseId) paged_file.close(physical) oldTables = database.catalog.tables diff --git a/src/minisql/catalog/metadata.ml b/src/minisql/catalog/metadata.ml index be65b99..c929e8a 100644 --- a/src/minisql/catalog/metadata.ml +++ b/src/minisql/catalog/metadata.ml @@ -6,6 +6,7 @@ package minisql.catalog.metadata // Licensed under the Apache License, Version 2.0; see the LICENSE file. import minisql.common.endian as endian +import minisql.common.format_version as format_version import minisql.storage.checksum as checksum /// Versioned catalog metadata codecs. Decoders validate kind, version, bounds, @@ -17,7 +18,7 @@ const UNSUPPORTED_FORMAT = 9003 const CORRUPT_DATA = 9004 /// Defines the database format version constant used by the minisql catalog metadata module. -const DATABASE_FORMAT_VERSION = 1 +const DATABASE_FORMAT_VERSION = format_version.DATABASE /// Defines the catalog format version constant used by the minisql catalog metadata module. const CATALOG_FORMAT_VERSION = 1 /// Defines the database kind constant used by the minisql catalog metadata module. @@ -199,8 +200,8 @@ function createDatabase(name, databaseId, pageSize, walSegmentBytes, databaseFor validateDatabaseId(databaseId, "createDatabase") if typeof(pageSize) != "int" or pageSize < 4096 or pageSize > 32768 then return fail(INVALID_ARGUMENT, "createDatabase", "invalid pageSize") end if if typeof(walSegmentBytes) != "int" or walSegmentBytes < 4096 then return fail(INVALID_ARGUMENT, "createDatabase", "invalid walSegmentBytes") end if - if databaseFormatVersion != 1 or tableFileFormatVersion != 1 or indexFileFormatVersion != 1 or walFormatVersion != 1 or rowFormatVersion != 1 then - return fail(UNSUPPORTED_FORMAT, "createDatabase", "only format version 1 is supported") + if databaseFormatVersion != format_version.DATABASE or tableFileFormatVersion != format_version.TABLE or indexFileFormatVersion != format_version.INDEX or walFormatVersion != format_version.WAL or rowFormatVersion != format_version.ROW then + return fail(UNSUPPORTED_FORMAT, "createDatabase", "storage format v2 is required; existing v1 databases must be recreated") end if return DatabaseMetadata(name, bytes(databaseId), pageSize, walSegmentBytes, databaseFormatVersion, tableFileFormatVersion, indexFileFormatVersion, walFormatVersion, rowFormatVersion, 3, 1, 0) end function @@ -252,10 +253,11 @@ end function /// @param encoded encoded value consumed by this operation. function decodeDatabase(encoded) envelope = checksum.decodeEnvelope(encoded, databaseMagic(), DATABASE_FORMAT_VERSION, DATABASE_KIND) + if envelope.flags != 0 then return fail(UNSUPPORTED_FORMAT, "decodeDatabase", "unsupported metadata flags") end if payload = envelope.payload if len(payload) < 80 then return fail(CORRUPT_DATA, "decodeDatabase", "database metadata payload too short") end if if endian.readU16LE(payload, 18) != 1 or endian.readU16LE(payload, 20) != 1 then return fail(UNSUPPORTED_FORMAT, "decodeDatabase", "unsupported encoding or collation") end if - if endian.readU32LE(payload, 64) != 0 or endian.readU32LE(payload, 68) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeDatabase", "reserved fields are non-zero") end if + if endian.readU32LE(payload, 64) != 0 or endian.readU32LE(payload, 68) != 0 or endian.readU32LE(payload, 72) != 0 or endian.readU32LE(payload, 76) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeDatabase", "reserved fields are non-zero") end if nameLength = endian.readU16LE(payload, 22) if len(payload) != 80 + nameLength then return fail(CORRUPT_DATA, "decodeDatabase", "name length mismatch") end if metadata = createDatabase( diff --git a/src/minisql/catalog/schema_history.ml b/src/minisql/catalog/schema_history.ml index 65bfaa4..b9be585 100644 --- a/src/minisql/catalog/schema_history.ml +++ b/src/minisql/catalog/schema_history.ml @@ -16,6 +16,7 @@ import minisql.storage.btree as btree import minisql.storage.checksum as checksum import minisql.storage.heap_file as heap_file import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.superblock as superblock /// Durable schema/constraint sidecar and transactional DDL journal. @@ -2127,7 +2128,7 @@ function createPlannedFiles(transaction, prepared) for each plan in prepared.createFiles deleteIfExists(plan.temporaryPath) if plan.fileKind == superblock.FILE_TYPE_TABLE then - file = paged_file.create(plan.temporaryPath, transaction.database.metadata.pageSize, superblock.FILE_TYPE_TABLE, plan.fileId, transaction.database.metadata.databaseId) + file = table_header.create(plan.temporaryPath, transaction.database.metadata.pageSize, plan.fileId, transaction.database.metadata.databaseId) paged_file.close(file) else tree = btree.create(plan.temporaryPath, transaction.database.metadata.pageSize, plan.fileId, transaction.database.metadata.databaseId, plan.unique) diff --git a/src/minisql/common/float_codec.ml b/src/minisql/common/float_codec.ml new file mode 100644 index 0000000..92d1709 --- /dev/null +++ b/src/minisql/common/float_codec.ml @@ -0,0 +1,125 @@ +//! Exact finite IEEE-754 binary64 codecs for persistent MiniSQL values. + +package minisql.common.float_codec +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +import minisql.common.endian as endian +import std.math as math + +const INVALID_ARGUMENT = 9001 +const CORRUPT_DATA = 9004 +const TYPE_MISMATCH = 9017 +const WIDTH = 8 +const FRACTION_UNIT = 4503599627370496 + +// frexp/ldexp scale by powers of two exactly. They avoid dependence on the +// runtime's tagged/boxed float representation and never render decimal text. +#if TARGET_OS == "windows" +/// Splits a native double into its exact binary significand and exponent. +extern function nativeFrexp(value as double, exponent as bytes) from "msvcrt.dll" symbol "frexp" returns double +/// Scales a native double by an integral power of two. +extern function nativeLdexp(value as double, exponent as i32) from "msvcrt.dll" symbol "ldexp" returns double +/// Copies the sign bit, including the sign of zero. +extern function nativeCopySign(value as double, signValue as double) from "msvcrt.dll" symbol "_copysign" returns double +/// Reports whether the native value is finite without unordered comparisons. +extern function nativeFinite(value as double) from "msvcrt.dll" symbol "_finite" returns i32 +#else +/// Splits a native double into its exact binary significand and exponent. +extern function nativeFrexp(value as double, exponent as bytes) from "libm.so.6" symbol "frexp" returns double +/// Scales a native double by an integral power of two. +extern function nativeLdexp(value as double, exponent as i32) from "libm.so.6" symbol "ldexp" returns double +/// Copies the sign bit, including the sign of zero. +extern function nativeCopySign(value as double, signValue as double) from "libm.so.6" symbol "copysign" returns double +/// Reports whether the native value is finite without unordered comparisons. +extern function nativeFinite(value as double) from "libm.so.6" symbol "finite" returns i32 +#endif + +/// Reports whether an encoded binary64 has a finite exponent, after bounds checks. +/// @param source Input byte buffer. +/// @param offset Start of the eight-byte value. +function isFiniteEncoded(source, offset) + endian.validateRange(source, offset, WIDTH, "float_codec.isFiniteEncoded") + high = endian.readU32LE(source, offset + 4) + return ((high >> 20) & 2047) != 2047 +end function + +/// Encodes a finite number without changing zero's sign or losing subnormal bits. +/// @param value MiniLang numeric value; integers convert to binary64 by normal numeric semantics. +function encodeFloat64LE(value) + if typeof(value) != "float" and typeof(value) != "int" then return error(TYPE_MISMATCH, "common.float_codec.encodeFloat64LE: expected number") end if + if nativeFinite(value) == 0 then return error(TYPE_MISMATCH, "common.float_codec.encodeFloat64LE: non-finite value") end if + exponentBytes = bytes(4, 0) + fraction = nativeFrexp(value, exponentBytes) + if typeof(fraction) != "float" and typeof(fraction) != "int" then return error(TYPE_MISMATCH, "common.float_codec.encodeFloat64LE: native float conversion failed") end if + // SQL storage rejects NaN/infinity above so indexes have a finite order. + negative = nativeCopySign(1.0, value) < 0 + magnitude = nativeCopySign(fraction, 1.0) + storedExponent = 0 + mantissa = 0 + if magnitude != 0 then + exponent = endian.readI32LE(exponentBytes, 0) + if exponent < -1021 then + // Subnormal significand is value * 2^1074. Using the frexp fraction + // avoids creating an unrepresentable intermediate scaling factor. + mantissa = math.toIntExact(nativeLdexp(magnitude, exponent + 1074)) + else + storedExponent = exponent + 1022 + mantissa = math.toIntExact(nativeLdexp(magnitude, 53)) - FRACTION_UNIT + end if + end if + low = mantissa & 0xFFFFFFFF + high = (mantissa >> 32) | (storedExponent << 20) + if negative then high = high | 0x80000000 end if + output = bytes(WIDTH, 0) + endian.writeU32LE(output, 0, low) + endian.writeU32LE(output, 4, high) + return output +end function + +/// Writes a complete finite binary64 only after value and destination validation. +/// @param destination Output byte buffer. +/// @param offset Start of the eight-byte destination. +/// @param value Numeric value to encode. +function writeFloat64LE(destination, offset, value) + endian.validateRange(destination, offset, WIDTH, "float_codec.writeFloat64LE") + encoded = encodeFloat64LE(value) + copyBytes(destination, offset, encoded, 0, WIDTH) + return true +end function + +/// Decodes finite binary64, preserving negative zero and the full 53-bit significand. +/// @param source Input byte buffer. +/// @param offset Start of the eight-byte value. +function decodeFloat64LE(source, offset) + endian.validateRange(source, offset, WIDTH, "float_codec.decodeFloat64LE") + low = endian.readU32LE(source, offset) + high = endian.readU32LE(source, offset + 4) + exponent = (high >> 20) & 2047 + if exponent == 2047 then return error(CORRUPT_DATA, "common.float_codec.decodeFloat64LE: non-finite value") end if + mantissa = (high & 0xFFFFF) * 4294967296 + low + power = -1074 + if exponent != 0 then + mantissa = mantissa + FRACTION_UNIT + power = exponent - 1075 + end if + value = nativeLdexp(toFloat(mantissa), power) + if (high & 0x80000000) != 0 then return nativeCopySign(value, -1.0) end if + return value +end function + +/// Returns this module's stable registry name. +function componentName() + return "common.float_codec" +end function + +/// Returns the storage generation that introduced this module. +function targetMilestone() + return "StorageV2" +end function + +/// Reports that the binary64 codec is available. +function isImplemented() + return true +end function diff --git a/src/minisql/common/format_version.ml b/src/minisql/common/format_version.ml new file mode 100644 index 0000000..551cf56 --- /dev/null +++ b/src/minisql/common/format_version.ml @@ -0,0 +1,38 @@ +//! Defines the incompatible storage generation independently of the wire protocol. + +package minisql.common.format_version +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +/// Database generation requiring binary floats, aligned rows and table metadata pages. +const DATABASE = 2 +/// User-table format with a mandatory identity page at logical page zero. +const TABLE = 2 +/// Index format with typed, little-endian numeric keys and semantic comparison. +const INDEX = 2 +/// Row encoding with aligned values and little-endian IEEE-754 binary64 floats. +const ROW = 2 +/// Overflow encoding with a U32 value length and an independent pointer checksum. +const OVERFLOW = 2 +/// The existing WAL framing is unchanged; its page images carry storage generation two. +const WAL = 1 +/// The common logical page header remains byte-compatible with its original layout. +const PAGE = 1 +/// The fixed redundant superblock layout remains unchanged. +const SUPERBLOCK = 1 + +/// Returns this module's stable component identity. +function componentName() + return "common.format_version" +end function + +/// Identifies the storage-generation work that introduced this module. +function targetMilestone() + return "StorageV2" +end function + +/// Reports that the version registry is implemented. +function isImplemented() + return true +end function diff --git a/src/minisql/common/version.ml b/src/minisql/common/version.ml index ae767e9..fa4ce54 100644 --- a/src/minisql/common/version.ml +++ b/src/minisql/common/version.ml @@ -5,6 +5,8 @@ package minisql.common.version // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0; see the LICENSE file. +import minisql.common.format_version as format_version + /// Central product, wire-protocol, and database-format identity. Persisted and const PRODUCT_NAME = "MiniSQL" @@ -17,7 +19,7 @@ const REVISION = "M48-M50R3" /// Defines the wire protocol version constant used by the minisql common version module. const WIRE_PROTOCOL_VERSION = 1 /// Defines the database format version constant used by the minisql common version module. -const DATABASE_FORMAT_VERSION = 1 +const DATABASE_FORMAT_VERSION = format_version.DATABASE /// Performs the product name operation for this module. /// Takes no caller-supplied inputs. Returns the produced value or propagates a structured error from validation or delegated operations. diff --git a/src/minisql/config/model.ml b/src/minisql/config/model.ml index e9512ec..53b7dcf 100644 --- a/src/minisql/config/model.ml +++ b/src/minisql/config/model.ml @@ -6,6 +6,8 @@ package minisql.config.model // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0; see LICENSE for details. +import minisql.common.format_version as format_version + /// Groups the paths config state and preserves the field relationships documented below. struct PathsConfig /// Stores the data root associated with this value. @@ -243,7 +245,7 @@ end function /// Any side effects are limited to the explicitly invoked dependencies. /// @param pageSize pageSize value consumed by this operation. function defaultDatabaseSettings(pageSize) - return DatabaseDefaults(pageSize, "crc32c", 16777216, "utf-8", "binary", 1, 1, 1, 1, 1) + return DatabaseDefaults(pageSize, "crc32c", 16777216, "utf-8", "binary", format_version.DATABASE, format_version.TABLE, format_version.INDEX, format_version.WAL, format_version.ROW) end function /// Implements default config for this module. diff --git a/src/minisql/config/validation.ml b/src/minisql/config/validation.ml index 5c7cc61..b31640b 100644 --- a/src/minisql/config/validation.ml +++ b/src/minisql/config/validation.ml @@ -7,6 +7,7 @@ package minisql.config.validation // Licensed under the Apache License, Version 2.0; see LICENSE for details. import minisql.common.limits as limits +import minisql.common.format_version as format_version import minisql.config.model as model /// Defines the invalid configuration constant used by the minisql config validation module. @@ -80,8 +81,8 @@ function validate(config) if config.databaseDefaults.defaultCollation != "binary" then return fail("only binary collation is supported in M8") end if positive(config.databaseDefaults.walSegmentBytes, "databaseDefaults.walSegmentBytes") if config.databaseDefaults.walSegmentBytes < 4096 then return fail("databaseDefaults.walSegmentBytes must be at least 4096") end if - if config.databaseDefaults.databaseFormatVersion != 1 or config.databaseDefaults.tableFileFormatVersion != 1 or config.databaseDefaults.indexFileFormatVersion != 1 or config.databaseDefaults.walFormatVersion != 1 or config.databaseDefaults.rowFormatVersion != 1 then - return fail("all persisted format versions must be 1") + if config.databaseDefaults.databaseFormatVersion != format_version.DATABASE or config.databaseDefaults.tableFileFormatVersion != format_version.TABLE or config.databaseDefaults.indexFileFormatVersion != format_version.INDEX or config.databaseDefaults.walFormatVersion != format_version.WAL or config.databaseDefaults.rowFormatVersion != format_version.ROW then + return fail("database/table/index/row format versions must be 2 and WAL framing version must be 1") end if if config.runtime.logLevel != "debug" and config.runtime.logLevel != "info" and config.runtime.logLevel != "warning" and config.runtime.logLevel != "warn" and config.runtime.logLevel != "error" then return fail("runtime.logLevel must be debug, info, warning or error") end if if typeof(config.logging.stdoutEnabled) != "bool" or typeof(config.logging.fileEnabled) != "bool" then return fail("logging destination flags must be boolean") end if diff --git a/src/minisql/executor/dml.ml b/src/minisql/executor/dml.ml index 683f4bb..8e3b2e7 100644 --- a/src/minisql/executor/dml.ml +++ b/src/minisql/executor/dml.ml @@ -11,6 +11,7 @@ import minisql.catalog.catalog as catalog import minisql.catalog.metadata as metadata import minisql.catalog.schema_history as schema_history import minisql.common.endian as endian +import minisql.common.float_codec as float_codec import minisql.platform.file as file_api import minisql.executor.scan as scan import minisql.server.database_manager as database_manager @@ -25,6 +26,7 @@ import minisql.storage.heap_file as heap_file import minisql.storage.overflow as overflow import minisql.storage.page as page import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.row_codec as row_codec import minisql.storage.slotted_page as slotted_page import minisql.transaction.checkpoint as checkpoint @@ -284,7 +286,7 @@ function stageInsertWithCursor(pageTransaction, file, table, encodedRow, cursor) if cursor is not InsertCursor then return fail(INVALID_ARGUMENT, "stageInsertWithCursor", "cursor must be InsertCursor") end if if typeof(encodedRow) != "bytes" or len(encodedRow) == 0 then return fail(INVALID_ARGUMENT, "stageInsertWithCursor", "encoded row must be non-empty bytes") end if startPage = cursor.pageNumber - if startPage < 0 then startPage = 0 end if + if startPage < table_header.FIRST_DATA_PAGE then startPage = table_header.FIRST_DATA_PAGE end if // The cursor normally names the current heap page, so try it before loading // or extending the persistent directory. Overflow writes may have grown the // physical file since the prior row while this page still has free space. @@ -789,7 +791,7 @@ function insertBatchWithoutConflict(database, sessionId, bound, pageTransaction, returnedRows = [] if len(bound.returning) > 0 then returnedRows = array(len(preparedRows)) end if rowSchema = scan.schemaForTable(bound.table) - cursorStart = 0 + cursorStart = table_header.FIRST_DATA_PAGE allocationBatch = 1 // Reserve heap pages in one durable allocation once a statement is large // enough to amortize the metadata barrier. A 32-row floor also benefits wide @@ -797,7 +799,7 @@ function insertBatchWithoutConflict(database, sessionId, bound, pageTransaction, if len(preparedRows) >= 32 then allocationBatch = 256 cursorStart = file.pageCount - 1 - if cursorStart < 0 then cursorStart = 0 end if + if cursorStart < table_header.FIRST_DATA_PAGE then cursorStart = table_header.FIRST_DATA_PAGE end if end if insertCursor = InsertCursor(cursorStart, allocationBatch, len(preparedRows)) if len(preparedRows) > 0 then @@ -1058,7 +1060,7 @@ function insert(database, sessionId, bound, pageTransaction) if not binder.isBoundInsert(bound) then return fail(INVALID_ARGUMENT, "insert", "bound must be BoundInsert") end if transaction.requireActive(pageTransaction, "executor.dml.insert") if pageTransaction.readOnly then return fail(READ_ONLY_VIOLATION, "insert", "transaction is read-only") end if - file = paged_file.open(catalog.tableFilePath(database.path, bound.table.tableId)) + file = table_header.open(catalog.tableFilePath(database.path, bound.table.tableId)) result = try(insertInner(database, sessionId, bound, pageTransaction, file)) closeResult = try(paged_file.close(file)) if typeof(result) == "error" then return result end if @@ -1123,7 +1125,7 @@ function update(database, sessionId, bound, pageTransaction) if not binder.isBoundUpdate(bound) then return fail(INVALID_ARGUMENT, "update", "bound must be BoundUpdate") end if transaction.requireActive(pageTransaction, "executor.dml.update") if pageTransaction.readOnly then return fail(READ_ONLY_VIOLATION, "update", "transaction is read-only") end if - file = paged_file.open(catalog.tableFilePath(database.path, bound.table.tableId)) + file = table_header.open(catalog.tableFilePath(database.path, bound.table.tableId)) result = try(updateInner(database, sessionId, bound, pageTransaction, file)) closeResult = try(paged_file.close(file)) if typeof(result) == "error" then return result end if @@ -1169,7 +1171,7 @@ function delete(database, sessionId, bound, pageTransaction) if not binder.isBoundDelete(bound) then return fail(INVALID_ARGUMENT, "delete", "bound must be BoundDelete") end if transaction.requireActive(pageTransaction, "executor.dml.delete") if pageTransaction.readOnly then return fail(READ_ONLY_VIOLATION, "delete", "transaction is read-only") end if - file = paged_file.open(catalog.tableFilePath(database.path, bound.table.tableId)) + file = table_header.open(catalog.tableFilePath(database.path, bound.table.tableId)) result = try(deleteInner(database, sessionId, bound, pageTransaction, file)) closeResult = try(paged_file.close(file)) if typeof(result) == "error" then return result end if @@ -1189,7 +1191,7 @@ function truncate(database, sessionId, bound, pageTransaction) if not binder.isBoundTruncate(bound) then return fail(INVALID_ARGUMENT, "truncate", "bound must be BoundTruncate") end if transaction.requireActive(pageTransaction, "executor.dml.truncate") if pageTransaction.readOnly then return fail(READ_ONLY_VIOLATION, "truncate", "transaction is read-only") end if - file = paged_file.open(catalog.tableFilePath(database.path, bound.table.tableId)) + file = table_header.open(catalog.tableFilePath(database.path, bound.table.tableId)) rows = try(scan.scanUsingControlled(database, sessionId, bound.table, pageTransaction, file)) if typeof(rows) == "error" then paged_file.close(file); return rows end if checked = true @@ -1221,7 +1223,7 @@ end function /// @param fileId Identifier of file. function fileForChange(database, fileId) for each table in database.catalogHandle.catalog.tables - if table.tableId == fileId then return paged_file.open(catalog.tableFilePath(database.path, table.tableId)) end if + if table.tableId == fileId then return table_header.open(catalog.tableFilePath(database.path, table.tableId)) end if end for return fail(OBJECT_NOT_FOUND, "fileForChange", "committed page refers to unknown table") end function @@ -1358,12 +1360,11 @@ function escapedKeyBytes(source) return output + bytes([0, 0]) end function -/// Implements index key part for this module. -/// Returns the computed value or operation status. -/// Any side effects are limited to the explicitly invoked dependencies. -/// @param value Value consumed or transformed by the operation. -function indexKeyPart(value) - if not values.isSqlValue(value) then return fail(INVALID_ARGUMENT, "indexKeyPart", "value must be SqlValue") end if +/// Encodes one typed index component with plain little-endian numeric payloads. +/// INCLUDE values preserve binary64 signed zero exactly like stored rows. +/// @param value SQL value consumed by the operation. +function indexValuePart(value) + if not values.isSqlValue(value) then return fail(INVALID_ARGUMENT, "indexValuePart", "value must be SqlValue") end if if value.isNull then return bytes([1]) end if if value.typeKind == types.SqlTypeKind.Boolean then byteValue = 0 @@ -1374,16 +1375,24 @@ function indexKeyPart(value) words = values.asInt64(value) output = bytes(9, 0) output[0] = 3 - endian.writeU32BE(output, 1, words.high ^ 2147483648) - endian.writeU32BE(output, 5, words.low) + endian.writeI64LE(output, 1, words) return output end if if value.typeKind == types.SqlTypeKind.Real or value.typeKind == types.SqlTypeKind.Double then - return bytes([4]) + escapedKeyBytes(bytes("" + value.value)) + return bytes([4]) + float_codec.encodeFloat64LE(value.value) end if if types.isTextKind(value.typeKind) then return bytes([5]) + escapedKeyBytes(bytes(value.value)) end if if types.isBinaryKind(value.typeKind) then return bytes([6]) + escapedKeyBytes(value.value) end if - return fail(TYPE_MISMATCH, "indexKeyPart", "unsupported index key type") + return fail(TYPE_MISMATCH, "indexValuePart", "unsupported index value type") +end function + +/// Preserves the stored value's binary64 representation for index-only reads. +/// The B+ tree comparator equates zero signs; only ephemeral constraint hash +/// keys canonicalize zero, because byte hashing has no numeric comparator. +/// @param value SQL key component. +function indexKeyPart(value) + if not values.isSqlValue(value) then return fail(INVALID_ARGUMENT, "indexKeyPart", "value must be SqlValue") end if + return indexValuePart(value) end function /// Encodes index key using the supplied inputs. @@ -1393,7 +1402,7 @@ end function /// @param keyValues keyValues value consumed by this operation. function encodeIndexKey(keyValues) if typeof(keyValues) != "array" or len(keyValues) == 0 then return fail(INVALID_ARGUMENT, "encodeIndexKey", "keyValues must be non-empty") end if - output = bytes([127]) + output = btree.sqlKeyPrefix() for each value in keyValues output = appendKeyBytes(output, indexKeyPart(value)) if len(output) > btree.MAX_KEY_BYTES then return fail(INVALID_ARGUMENT, "encodeIndexKey", "encoded key exceeds B+ tree limit") end if @@ -1407,7 +1416,7 @@ end function /// @param keyValues keyValues value consumed by this operation. function encodeConstraintHashKey(keyValues) if typeof(keyValues) != "array" or len(keyValues) == 0 then return fail(INVALID_ARGUMENT, "encodeConstraintHashKey", "keyValues must be non-empty") end if - output = bytes([127]) + output = btree.sqlKeyPrefix() for each value in keyValues normalized = value if (value.typeKind == types.SqlTypeKind.Real or value.typeKind == types.SqlTypeKind.Double) and value.value == 0 then normalized = values.of(value.typeKind, 0.0) end if @@ -1439,8 +1448,7 @@ end function /// @param tableId Identifier of table. /// @param encoded encoded value consumed by this operation. function decodeRowReference(tableId, encoded) - // The stable 12-byte reference is the prefix of both legacy leaf values and - // v1 covering values, so older indexes remain readable without migration. + // Both ordinary and covering values start with the physical row reference. if typeof(tableId) != "int" or typeof(encoded) != "bytes" or len(encoded) < 12 then return fail(CORRUPT_DATA, "decodeRowReference", "invalid index row reference") end if if endian.readU32LE(encoded, 8) != tableId then return fail(CORRUPT_DATA, "decodeRowReference", "index row reference belongs to another table") end if return scan.RowReference(endian.readU32LE(encoded, 0), endian.readU16LE(encoded, 4), endian.readU16LE(encoded, 6)) @@ -1448,16 +1456,16 @@ end function /// Validates the leaf-value shape before a heap-backed scan consumes only its /// row-reference prefix. Full payload decoding remains exclusive to index-only -/// scans, while ordinary legacy values still require an exact 12-byte length. +/// scans, while values without INCLUDE require an exact 12-byte length. /// @param constraint constraint value consumed by this operation. /// @param encoded encoded value consumed by this operation. function validateIndexEntryValueShape(constraint, encoded) if typeof(encoded) != "bytes" then return fail(CORRUPT_DATA, "validateIndexEntryValueShape", "index leaf value must be bytes") end if if len(constraint.referenceColumns) == 0 then - if len(encoded) != 12 then return fail(CORRUPT_DATA, "validateIndexEntryValueShape", "legacy index leaf value has trailing bytes") end if + if len(encoded) != 12 then return fail(CORRUPT_DATA, "validateIndexEntryValueShape", "ordinary index leaf value has trailing bytes") end if return true end if - if len(encoded) < 16 or encoded[12] != 77 or encoded[13] != 83 or encoded[14] != 73 or encoded[15] != 1 then return fail(CORRUPT_DATA, "validateIndexEntryValueShape", "invalid INCLUDE payload header") end if + if len(encoded) < 16 or encoded[12] != 77 or encoded[13] != 83 or encoded[14] != 73 or encoded[15] != btree.FORMAT_VERSION then return fail(CORRUPT_DATA, "validateIndexEntryValueShape", "invalid INCLUDE payload header") end if return true end function @@ -1485,9 +1493,8 @@ function decodeEscapedKeyBytes(encoded, startOffset) return fail(CORRUPT_DATA, "decodeEscapedKeyBytes", "missing component terminator") end function -/// Decodes one self-delimiting typed value shared by ordered keys and INCLUDE -/// payloads. Floating-point key text is not reversible and deliberately returns -/// void, which makes execution fall back to a heap-backed index scan. +/// Decodes one self-delimiting v2 value shared by SQL keys and INCLUDE payloads. +/// Binary64 values are decoded directly without a text conversion or fallback. /// @param column column value consumed by this operation. /// @param encoded encoded value consumed by this operation. /// @param cursor cursor value consumed by this operation. @@ -1500,42 +1507,50 @@ function decodeIndexPart(column, encoded, cursor, operation) if tag == 1 then decodedValue = values.nullValue(column.typeCode) else if tag == 2 then + if column.typeCode != types.SqlTypeKind.Boolean then return fail(CORRUPT_DATA, operation, "Boolean index tag disagrees with catalog") end if if cursor >= len(encoded) or (encoded[cursor] != 0 and encoded[cursor] != 1) then return fail(CORRUPT_DATA, operation, "invalid Boolean index value") end if decodedValue = values.of(column.typeCode, encoded[cursor] == 1) cursor = cursor + 1 else if tag == 3 then + if not types.isIntegralKind(column.typeCode) and column.typeCode != types.SqlTypeKind.Decimal and column.typeCode != types.SqlTypeKind.Date and column.typeCode != types.SqlTypeKind.Time and column.typeCode != types.SqlTypeKind.Timestamp then return fail(CORRUPT_DATA, operation, "integral index tag disagrees with catalog") end if if cursor > len(encoded) - 8 then return fail(CORRUPT_DATA, operation, "truncated integral index value") end if - words = endian.makeInt64(endian.readU32BE(encoded, cursor) ^ 2147483648, endian.readU32BE(encoded, cursor + 4)) + words = endian.readI64LE(encoded, cursor) cursor = cursor + 8 if column.typeCode == types.SqlTypeKind.SmallInt or column.typeCode == types.SqlTypeKind.Integer or column.typeCode == types.SqlTypeKind.Date then decodedValue = values.of(column.typeCode, endian.int64ToInt(words)) else decodedValue = values.of(column.typeCode, words) end if + else if tag == 4 then + if column.typeCode != types.SqlTypeKind.Real and column.typeCode != types.SqlTypeKind.Double then return fail(CORRUPT_DATA, operation, "floating index tag disagrees with catalog") end if + if cursor > len(encoded) - 8 then return fail(CORRUPT_DATA, operation, "truncated floating index value") end if + decodedValue = values.of(column.typeCode, float_codec.decodeFloat64LE(encoded, cursor)) + cursor = cursor + 8 else if tag == 5 or tag == 6 then + if (tag == 5 and not types.isTextKind(column.typeCode)) or (tag == 6 and not types.isBinaryKind(column.typeCode)) then return fail(CORRUPT_DATA, operation, "byte index tag disagrees with catalog") end if escaped = decodeEscapedKeyBytes(encoded, cursor) cursor = escaped[1] if tag == 5 then decodedValue = values.of(column.typeCode, decode(escaped[0])) else decodedValue = values.of(column.typeCode, escaped[0]) end if else - return void + return fail(CORRUPT_DATA, operation, "unknown typed index value tag") end if return [decodedValue, cursor] end function /// Reconstructs table-typed SQL values from an index key. Non-key positions are /// typed NULL placeholders and are safe because the optimizer proves they are -/// not referenced before selecting an index-only plan. Floating encodings retain -/// their textual ordering representation and therefore conservatively fall back. +/// not referenced before selecting an index-only plan. /// @param table table value consumed by this operation. /// @param constraint constraint value consumed by this operation. /// @param encoded encoded value consumed by this operation. function decodeCoveredIndexKey(table, constraint, encoded) - if typeof(encoded) != "bytes" or len(encoded) == 0 or encoded[0] != 127 then return fail(CORRUPT_DATA, "decodeCoveredIndexKey", "invalid index key prefix") end if + if typeof(encoded) != "bytes" or not btree.isSqlKey(encoded) then return fail(CORRUPT_DATA, "decodeCoveredIndexKey", "invalid index key prefix") end if + btree.validateKey(encoded) output = [] for each column in table.columns output = output + [values.nullValue(column.typeCode)] end for - cursor = 1 + cursor = 4 for each columnName in constraint.columns columnIndex = binder.findColumnIndex(table, columnName) if columnIndex < 0 or cursor >= len(encoded) then return fail(CORRUPT_DATA, "decodeCoveredIndexKey", "index key shape does not match catalog") end if @@ -1550,7 +1565,7 @@ function decodeCoveredIndexKey(table, constraint, encoded) end function /// Encodes a leaf value as a stable row-reference prefix followed, when needed, -/// by the MSI v1 marker and self-delimiting typed INCLUDE values. +/// by the MSI v2 marker and self-delimiting typed INCLUDE values. /// @param table table value consumed by this operation. /// @param constraint constraint value consumed by this operation. /// @param rowValues rowValues value consumed by this operation. @@ -1558,26 +1573,24 @@ end function function encodeIndexEntryValue(table, constraint, rowValues, reference) output = encodeRowReference(table.tableId, reference) if len(constraint.referenceColumns) == 0 then return output end if - output = output + bytes([77, 83, 73, 1]) + output = output + bytes([77, 83, 73, btree.FORMAT_VERSION]) for each columnName in constraint.referenceColumns columnIndex = binder.findColumnIndex(table, columnName) if columnIndex < 0 then return fail(CORRUPT_DATA, "encodeIndexEntryValue", "index INCLUDE references missing column") end if - output = output + indexKeyPart(rowValues[columnIndex]) + output = output + indexValuePart(rowValues[columnIndex]) if len(output) > btree.MAX_VALUE_BYTES then return fail(INVALID_ARGUMENT, "encodeIndexEntryValue", "encoded INCLUDE payload exceeds one B+ tree leaf entry") end if end for return output end function -/// Merges a validated MSI v1 payload into the table-width row reconstructed -/// from the key. Missing legacy payloads return void and trigger a safe fallback. +/// Merges a validated MSI v2 payload into the table-width reconstructed row. /// @param table table value consumed by this operation. /// @param constraint constraint value consumed by this operation. /// @param encoded encoded value consumed by this operation. /// @param output Output collection or buffer populated by the operation. function decodeIncludedIndexValues(table, constraint, encoded, output) if len(constraint.referenceColumns) == 0 then return output end if - if len(encoded) == 12 then return void end if - if len(encoded) < 16 or encoded[12] != 77 or encoded[13] != 83 or encoded[14] != 73 or encoded[15] != 1 then return fail(CORRUPT_DATA, "decodeIncludedIndexValues", "invalid INCLUDE payload header") end if + if len(encoded) < 16 or encoded[12] != 77 or encoded[13] != 83 or encoded[14] != 73 or encoded[15] != btree.FORMAT_VERSION then return fail(CORRUPT_DATA, "decodeIncludedIndexValues", "invalid INCLUDE payload header") end if cursor = 16 for each columnName in constraint.referenceColumns columnIndex = binder.findColumnIndex(table, columnName) @@ -2096,7 +2109,6 @@ function namedRangeIndexRows(database, table, columnIndex, literalValue, operato if constraint is void then return void end if converted = values.convert(literalValue, types.fromColumn(table.columns[columnIndex])) if converted.isNull then return [] end if - if converted.typeKind == types.SqlTypeKind.Real or converted.typeKind == types.SqlTypeKind.Double then return void end if key = encodeIndexKey([converted]) lower = void upper = void @@ -2294,7 +2306,6 @@ function namedExpressionIndexRows(database, table, expression, pageTransaction, if operatorValue != "=" and operatorValue != "<" and operatorValue != "<=" and operatorValue != ">" and operatorValue != ">=" then return void end if converted = values.convert(found[2], keyExpression.typeInfo) if converted.isNull then return [] end if - if converted.typeKind == types.SqlTypeKind.Real or converted.typeKind == types.SqlTypeKind.Double then return void end if encodedKey = encodeIndexKey([converted]) indexLease = openReadOnlyIndex(database, constraint, "expressionIndexRows") tree = readOnlyIndexTree(indexLease) @@ -2360,14 +2371,12 @@ function plannedCoveredIndexEntries(database, table, expression, constraint) encodedKey = encodeIndexKey(keyValues) indexLease = openReadOnlyIndex(database, constraint, "plannedCoveredIndexEntries") tree = readOnlyIndexTree(indexLease) - foundValues = try(btree.findWithContext(tree, encodedKey, readOnlyIndexContext(indexLease))) + // Equality must retain the stored keys. A search literal may compare equal + // without having identical bits, notably +0.0 versus a persisted -0.0. + entries = try(btree.rangeWithContext(tree, encodedKey, true, encodedKey, true, 0, readOnlyIndexContext(indexLease))) closeResult = try(closeReadOnlyIndex(indexLease)) - if typeof(foundValues) == "error" then return foundValues end if + if typeof(entries) == "error" then return entries end if if typeof(closeResult) == "error" then return closeResult end if - entries = [] - for each rowValue in foundValues - entries = entries + [btree.entry(encodedKey, rowValue)] - end for return entries end if @@ -2378,21 +2387,12 @@ function plannedCoveredIndexEntries(database, table, expression, constraint) if operatorValue != "=" and operatorValue != "<" and operatorValue != "<=" and operatorValue != ">" and operatorValue != ">=" then return void end if converted = values.convert(found[2], types.fromColumn(table.columns[columnIndex])) if converted.isNull then return [] end if - if converted.typeKind == types.SqlTypeKind.Real or converted.typeKind == types.SqlTypeKind.Double then return void end if encodedKey = encodeIndexKey([converted]) indexLease = openReadOnlyIndex(database, constraint, "plannedCoveredIndexEntries") tree = readOnlyIndexTree(indexLease) entries = void if operatorValue == "=" then - foundValues = try(btree.findWithContext(tree, encodedKey, readOnlyIndexContext(indexLease))) - if typeof(foundValues) != "error" then - entries = [] - for each rowValue in foundValues - entries = entries + [btree.entry(encodedKey, rowValue)] - end for - else - entries = foundValues - end if + entries = try(btree.rangeWithContext(tree, encodedKey, true, encodedKey, true, 0, readOnlyIndexContext(indexLease))) else lower = void upper = void diff --git a/src/minisql/executor/executor.ml b/src/minisql/executor/executor.ml index 40bb1e8..027545c 100644 --- a/src/minisql/executor/executor.ml +++ b/src/minisql/executor/executor.ml @@ -33,6 +33,7 @@ import minisql.sql.parser as parser import minisql.sql.types as types import minisql.sql.values as values import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.buffer_pool as buffer_pool import minisql.transaction.transaction as transaction import std.ds.list as list @@ -3811,7 +3812,7 @@ end function function analyzeTable(engine, state, table) populationRows = scan.countTableRowsCached(engine.database.path, table, void, engine.database.readCache) rows = scan.sampleTableRowsCached(engine.database.path, table, populationRows, ANALYZE_SAMPLE_ROWS, engine.database.readCache) - tableFile = paged_file.open(catalog.tableFilePath(engine.database.path, table.tableId)) + tableFile = table_header.open(catalog.tableFilePath(engine.database.path, table.tableId)) pageCount = tableFile.pageCount paged_file.close(tableFile) return statistics.replaceTable(state, statistics.analyzeSampleWithGroups(table, populationRows, rows, pageCount, analyzeColumnGroups(engine, table))) diff --git a/src/minisql/executor/scan.ml b/src/minisql/executor/scan.ml index b9a9cc3..c51e352 100644 --- a/src/minisql/executor/scan.ml +++ b/src/minisql/executor/scan.ml @@ -19,6 +19,7 @@ import minisql.storage.buffer_pool as buffer_pool import minisql.storage.heap_file as heap_file import minisql.storage.page as page import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.row_codec as row_codec import minisql.storage.slotted_page as slotted_page import minisql.transaction.transaction as transaction @@ -217,7 +218,7 @@ function openCached(databasePath, table, pageTransaction, readCache) if not metadata.isTableMetadata(table) then return fail(INVALID_ARGUMENT, "open", "table must be TableMetadata") end if if pageTransaction is not void then transaction.validateTransaction(pageTransaction, "executor.scan.open") end if tablePath = catalog.tableFilePath(databasePath, table.tableId) - file = try(paged_file.openReadOnly(tablePath)) + file = try(table_header.openReadOnly(tablePath)) if typeof(file) == "error" then return fail(file.code, "open", "cannot open table file " + tablePath + ": " + file.message) end if state = try(schema_history.loadOrCreate(databasePath, file.databaseId)) if typeof(state) == "error" then @@ -243,7 +244,7 @@ function openCachedWithSchema(databasePath, table, pageTransaction, readCache, s if not schema_history.isSchemaState(state) then return fail(INVALID_ARGUMENT, "openWithSchema", "state must be SchemaState") end if if pageTransaction is not void then transaction.validateTransaction(pageTransaction, "executor.scan.openWithSchema") end if tablePath = catalog.tableFilePath(databasePath, table.tableId) - file = try(paged_file.openReadOnly(tablePath)) + file = try(table_header.openReadOnly(tablePath)) if typeof(file) == "error" then return fail(file.code, "openWithSchema", "cannot open table file " + tablePath + ": " + file.message) end if tableSchemaValue = schema_history.findTableSchema(state, table.tableId) generatedColumns = schema_history.generatedForTable(state, table.tableId) @@ -329,7 +330,7 @@ end function /// @param pageNumber pageNumber value consumed by this operation. function visiblePage(reader, pageNumber) validateOpen(reader, "visiblePage") - if typeof(pageNumber) != "int" or pageNumber < 0 or pageNumber >= reader.file.pageCount then return fail(INVALID_ARGUMENT, "visiblePage", "page number is outside table") end if + if typeof(pageNumber) != "int" or pageNumber < table_header.FIRST_DATA_PAGE or pageNumber >= reader.file.pageCount then return fail(INVALID_ARGUMENT, "visiblePage", "page number is outside table data pages") end if if reader.pageTransaction is not void then privatePage = transaction.readPrivatePage(reader.pageTransaction, reader.table.tableId, pageNumber) if privatePage is not void then return privatePage end if @@ -685,7 +686,7 @@ function allRangeColumns(reader, offset, limit, requiredColumns) if typeof(limit) != "int" or limit < -1 then return fail(INVALID_ARGUMENT, "allRange", "limit must be -1 or non-negative") end if if requiredColumns is not void and (typeof(requiredColumns) != "array" or len(requiredColumns) != len(reader.table.columns)) then return fail(INVALID_ARGUMENT, "allRange", "required column mask must match the table") end if if limit == 0 then return [] end if - if reader.file.pageCount == 0 then return [] end if + if reader.file.pageCount == table_header.FIRST_DATA_PAGE then return [] end if // A growable buffer keeps appends amortized O(1) while allowing each page to // be read and checksum-verified only once. The former exact pre-count pass // doubled I/O and CRC work for every sequential SELECT. @@ -743,7 +744,7 @@ end function function readReference(reader, reference) validateOpen(reader, "readReference") if reference is not RowReference then return fail(INVALID_ARGUMENT, "readReference", "reference must be RowReference") end if - if reference.pageNumber < 0 or reference.pageNumber >= reader.file.pageCount then return void end if + if reference.pageNumber < table_header.FIRST_DATA_PAGE or reference.pageNumber >= reader.file.pageCount then return void end if pageBytes = visiblePage(reader, reference.pageNumber) header = page.verify(pageBytes) if header.pageType != page.TYPE_HEAP then return fail(CORRUPT_DATA, "readReference", "table page has wrong type") end if diff --git a/src/minisql/planner/optimizer.ml b/src/minisql/planner/optimizer.ml index 851c151..3489408 100644 --- a/src/minisql/planner/optimizer.ml +++ b/src/minisql/planner/optimizer.ml @@ -406,7 +406,7 @@ function indexCoversBound(bound, source, index, predicate) for each columnIndex in index.columnIndexes + index.includedColumnIndexes if columnIndex < 0 or columnIndex >= len(source.table.columns) then return false end if typeCode = source.table.columns[columnIndex].typeCode - decodable = typeCode == types.SqlTypeKind.Boolean or types.isIntegralKind(typeCode) or typeCode == types.SqlTypeKind.Decimal or typeCode == types.SqlTypeKind.Date or typeCode == types.SqlTypeKind.Time or typeCode == types.SqlTypeKind.Timestamp or types.isTextKind(typeCode) or types.isBinaryKind(typeCode) + decodable = typeCode == types.SqlTypeKind.Boolean or types.isIntegralKind(typeCode) or typeCode == types.SqlTypeKind.Real or typeCode == types.SqlTypeKind.Double or typeCode == types.SqlTypeKind.Decimal or typeCode == types.SqlTypeKind.Date or typeCode == types.SqlTypeKind.Time or typeCode == types.SqlTypeKind.Timestamp or types.isTextKind(typeCode) or types.isBinaryKind(typeCode) if not decodable then return false end if end for if not expressionCoveredByIndex(predicate, source, index) or not expressionCoveredByIndex(bound.havingExpression, source, index) then return false end if diff --git a/src/minisql/server/database_manager.ml b/src/minisql/server/database_manager.ml index 7a02fd9..f0764a2 100644 --- a/src/minisql/server/database_manager.ml +++ b/src/minisql/server/database_manager.ml @@ -20,6 +20,7 @@ import minisql.platform.file as file_api import minisql.platform.clock as clock import minisql.platform.lock as file_lock import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.btree as btree import minisql.storage.buffer_pool as buffer_pool import minisql.transaction.checkpoint as checkpoint @@ -611,7 +612,7 @@ function acquireTableReadHandle(database, path) if not cache.guard.acquire() then return fail(CLOSED_HANDLE, "acquireTableReadHandle", "registry guard is unavailable") end if entry = cache.tables.get(path) if entry is void then - tableFile = try(paged_file.openReadOnlyManaged(path)) + tableFile = try(table_header.openReadOnlyManaged(path)) if typeof(tableFile) == "error" then cache.guard.release(); return tableFile end if entry = CachedReadHandle(path, tableFile, false) cache.tables.set(path, entry) @@ -996,7 +997,7 @@ function openInternal(path, allowStandby, checkpointWalBytes, bufferPoolBytes, q recoveryTargets = [] recoveryTargetIds = hashmap.HashMap.new() for each table in catalogHandle.catalog.tables - tableFile = try(paged_file.open(catalog.tableFilePath(path, table.tableId))) + tableFile = try(table_header.open(catalog.tableFilePath(path, table.tableId))) if typeof(tableFile) == "error" then closeRecoveryFiles(recoveryFiles) checkpoint.close(checkpointFile) diff --git a/src/minisql/sql/values.ml b/src/minisql/sql/values.ml index d33f51f..5d86c0c 100644 --- a/src/minisql/sql/values.ml +++ b/src/minisql/sql/values.ml @@ -7,6 +7,7 @@ package minisql.sql.values // Licensed under the Apache License, Version 2.0; see LICENSE for details. import minisql.common.endian as endian +import minisql.common.float_codec as float_codec import minisql.sql.ast as ast import minisql.sql.types as types import minisql.storage.row_codec as row_codec @@ -233,7 +234,7 @@ function floatingNumberFromText(textValue) end if direct = toNumber(textValue) - if typeof(direct) == "float" or typeof(direct) == "int" then return direct end if + if typeof(direct) == "float" or typeof(direct) == "int" then return floatingSignedZero(textValue, direct) end if raw = bytes(textValue) startOffset = 0 @@ -268,7 +269,7 @@ function floatingNumberFromText(textValue) if typeof(mantissa) != "float" and typeof(mantissa) != "int" then return fail(BINDING_ERROR, "floatingNumberFromText", "invalid floating mantissa") end if - if exponentOffset < 0 then return mantissa end if + if exponentOffset < 0 then return floatingSignedZero(textValue, mantissa) end if exponentIndex = exponentOffset + 1 exponentNegative = false @@ -289,7 +290,8 @@ function floatingNumberFromText(textValue) exponentIndex = exponentIndex + 1 end while - result = mantissa + 0.0 + result = mantissa + if typeof(result) != "float" then result = result + 0.0 end if scaleIndex = 0 while scaleIndex < exponentMagnitude if exponentNegative then @@ -304,7 +306,22 @@ function floatingNumberFromText(textValue) // comparison is unequal to itself, which gives us a portable finite check. finiteProbe = result - result if finiteProbe != finiteProbe then return fail(BINDING_ERROR, "floatingNumberFromText", "floating literal exceeds the finite DOUBLE range") end if - return result + return floatingSignedZero(textValue, result) +end function + +/// Restores the explicit sign of parsed zero: the runtime's decimal parser +/// canonicalizes zero before SQL receives it. This also covers underflow. +/// @param textValue Validated source spelling of the numeric value. +/// @param number Parsed finite numeric value. +function floatingSignedZero(textValue, number) + if number != 0 then return number end if + raw = bytes(textValue) + cursor = 0 + while cursor < len(raw) and raw[cursor] <= 32 + cursor = cursor + 1 + end while + if cursor < len(raw) and raw[cursor] == 45 then return float_codec.nativeCopySign(0.0, -1.0) end if + return number end function /// Implements literal float for this module. @@ -698,6 +715,9 @@ function convert(value, target) end if if target.kind == types.SqlTypeKind.Real or target.kind == types.SqlTypeKind.Double then number = asNumber(value) + // Adding +0.0 to an existing -0.0 changes its IEEE-754 sign. Preserve + // floating inputs exactly; only integral inputs need numeric promotion. + if typeof(number) == "float" then return of(target.kind, number) end if return of(target.kind, number + 0.0) end if if types.isTextKind(target.kind) then @@ -755,7 +775,7 @@ function cast(value, target) if target.kind == types.SqlTypeKind.Decimal then return of(target.kind, decimalWordsFromText(value.value, target.precision, target.scale)) end if if target.kind == types.SqlTypeKind.Real or target.kind == types.SqlTypeKind.Double then parsed = floatingNumberFromText(value.value) - return convert(of(types.SqlTypeKind.Double, parsed + 0.0), target) + return convert(of(types.SqlTypeKind.Double, parsed), target) end if parsedInteger = literalInteger(value.value) return convert(parsedInteger, target) diff --git a/src/minisql/storage/btree.ml b/src/minisql/storage/btree.ml index 9e83980..e823918 100644 --- a/src/minisql/storage/btree.ml +++ b/src/minisql/storage/btree.ml @@ -7,12 +7,14 @@ package minisql.storage.btree import minisql.common.byte_ops as byte_ops import minisql.common.endian as endian +import minisql.common.format_version as format_version import minisql.storage.page as page import minisql.storage.paged_file as paged_file import minisql.storage.superblock as superblock import std.ds.list as list -/// Persistent B+ tree v1. +/// Persistent B+ tree v2. SQL keys use typed little-endian components; raw +/// keys retain byte ordering and leaf values always retain byte ordering. const INVALID_ARGUMENT = 9001 /// Defines the unsupported format constant used by the minisql storage btree module. @@ -27,7 +29,7 @@ const OBJECT_EXISTS = 9013 const OBJECT_NOT_FOUND = 9014 /// Defines the format version constant used by the minisql storage btree module. -const FORMAT_VERSION = 1 +const FORMAT_VERSION = format_version.INDEX /// Defines the meta page a constant used by the minisql storage btree module. const META_PAGE_A = 0 /// Defines the meta page b constant used by the minisql storage btree module. @@ -183,13 +185,169 @@ function bytesEqual(left, right) return true end function -/// Compares the keys. -/// Inputs: `left`, `right`. Returns the produced value or propagates a structured error from validation or delegated operations. -/// @param left left value consumed by this operation. -/// @param right right value consumed by this operation. +/// Returns the reserved SQL-key family marker and its byte-sized version. +/// Raw B+ tree clients may use any key outside the reserved ASCII MSK prefix. +function sqlKeyPrefix() + return bytes([77, 83, 75, FORMAT_VERSION]) +end function + +/// Identifies typed keys without interpreting arbitrary raw B+ tree bytes. +/// An unsupported version inside the reserved family is never read as raw. +/// @param encoded Encoded key bytes. +function isSqlKey(encoded) + if typeof(encoded) != "bytes" then return fail(INVALID_ARGUMENT, "isSqlKey", "key must be bytes") end if + if len(encoded) < 3 then return false end if + if encoded[0] != 77 or encoded[1] != 83 or encoded[2] != 75 then return false end if + if len(encoded) < 4 or encoded[3] != FORMAT_VERSION then return fail(UNSUPPORTED_FORMAT, "isSqlKey", "unsupported SQL key version") end if + return true +end function + +/// Validates one self-delimiting component and returns the next byte offset. +/// No slices or temporary SQL values are allocated on the comparator path. +/// @param encoded Encoded SQL key. +/// @param cursor Offset of the component tag. +function sqlPartEnd(encoded, cursor) + if cursor >= len(encoded) then return fail(CORRUPT_DATA, "sqlPartEnd", "missing SQL key component") end if + tag = encoded[cursor] + cursor = cursor + 1 + if tag == 1 then return cursor end if + if tag == 2 then + if cursor >= len(encoded) or encoded[cursor] > 1 then return fail(CORRUPT_DATA, "sqlPartEnd", "invalid Boolean SQL key component") end if + return cursor + 1 + end if + if tag == 3 or tag == 4 then + if cursor > len(encoded) - 8 then return fail(CORRUPT_DATA, "sqlPartEnd", "truncated numeric SQL key component") end if + if tag == 4 and (endian.readU32LE(encoded, cursor + 4) & 2146435072) == 2146435072 then return fail(CORRUPT_DATA, "sqlPartEnd", "non-finite floating SQL key component") end if + return cursor + 8 + end if + if tag != 5 and tag != 6 then return fail(CORRUPT_DATA, "sqlPartEnd", "unknown SQL key component tag") end if + while cursor < len(encoded) + if encoded[cursor] == 0 then + if cursor + 1 >= len(encoded) then return fail(CORRUPT_DATA, "sqlPartEnd", "truncated SQL key escape") end if + escaped = encoded[cursor + 1] + if escaped == 0 then return cursor + 2 end if + if escaped != 255 then return fail(CORRUPT_DATA, "sqlPartEnd", "invalid SQL key escape") end if + cursor = cursor + 2 + else + cursor = cursor + 1 + end if + end while + return fail(CORRUPT_DATA, "sqlPartEnd", "unterminated SQL key component") +end function + +/// Validates the complete typed representation at storage and lookup boundaries. +/// @param encoded Raw or SQL key bytes. +function validateKey(encoded) + if typeof(encoded) != "bytes" then return fail(INVALID_ARGUMENT, "validateKey", "key must be bytes") end if + if not isSqlKey(encoded) then return true end if + if len(encoded) == 4 then return fail(CORRUPT_DATA, "validateKey", "SQL key has no components") end if + cursor = 4 + while cursor < len(encoded) + cursor = sqlPartEnd(encoded, cursor) + end while + return true +end function + +/// Compares two same-tag numeric components directly from their LE words. +/// Signed integers compare signed high words then unsigned low words. Finite +/// binary64 values compare magnitude words, reversed for negatives; both zero +/// signs compare equal. This avoids a lossy scalar conversion for INT64 limits. +/// @param left Left key. +/// @param leftOffset Left numeric payload offset. +/// @param right Right key. +/// @param rightOffset Right numeric payload offset. +/// @param floating Whether the payload is finite IEEE-754 binary64. +function compareNumericPart(left, leftOffset, right, rightOffset, floating) + leftLow = endian.readU32LE(left, leftOffset) + rightLow = endian.readU32LE(right, rightOffset) + leftHigh = endian.readU32LE(left, leftOffset + 4) + rightHigh = endian.readU32LE(right, rightOffset + 4) + if not floating then + if leftHigh >= 2147483648 then leftHigh = leftHigh - 4294967296 end if + if rightHigh >= 2147483648 then rightHigh = rightHigh - 4294967296 end if + if leftHigh < rightHigh then return -1 end if + if leftHigh > rightHigh then return 1 end if + if leftLow < rightLow then return -1 end if + if leftLow > rightLow then return 1 end if + return 0 + end if + leftNegative = leftHigh >= 2147483648 + rightNegative = rightHigh >= 2147483648 + leftMagnitude = leftHigh & 2147483647 + rightMagnitude = rightHigh & 2147483647 + if leftMagnitude == 0 and leftLow == 0 and rightMagnitude == 0 and rightLow == 0 then return 0 end if + if leftNegative != rightNegative then + if leftNegative then return -1 end if + return 1 + end if + direction = 1 + if leftNegative then direction = -1 end if + if leftMagnitude < rightMagnitude then return 0 - direction end if + if leftMagnitude > rightMagnitude then return direction end if + if leftLow < rightLow then return 0 - direction end if + if leftLow > rightLow then return direction end if + return 0 +end function + +/// Compares already-validated escaped byte components without allocating slices. +/// The 00 FF escape and 00 00 terminator preserve bytewise text/binary ordering. +/// @param left Left key. +/// @param leftStart Left component payload offset. +/// @param leftEnd Offset after the left component. +/// @param right Right key. +/// @param rightStart Right component payload offset. +/// @param rightEnd Offset after the right component. +function compareByteParts(left, leftStart, leftEnd, right, rightStart, rightEnd) + while leftStart < leftEnd and rightStart < rightEnd + if left[leftStart] < right[rightStart] then return -1 end if + if left[leftStart] > right[rightStart] then return 1 end if + leftStart = leftStart + 1 + rightStart = rightStart + 1 + end while + if leftStart < leftEnd then return 1 end if + if rightStart < rightEnd then return -1 end if + return 0 +end function + +/// Compares SQL components semantically while preserving the raw-key API. +/// A component prefix sorts before its extensions. Raw keys precede typed keys +/// in mixed trees so the ordering remains transitive across the two domains. +/// @param left Left raw or typed key. +/// @param right Right raw or typed key. function compareKeys(left, right) if typeof(left) != "bytes" or typeof(right) != "bytes" then return fail(INVALID_ARGUMENT, "compareKeys", "keys must be bytes") end if - return byte_ops.compareLexicographic(left, right) + leftSql = isSqlKey(left) + rightSql = isSqlKey(right) + if not leftSql and not rightSql then return byte_ops.compareLexicographic(left, right) end if + if leftSql != rightSql then + if leftSql then return 1 end if + return -1 + end if + if len(left) == 4 or len(right) == 4 then return fail(CORRUPT_DATA, "compareKeys", "SQL key has no components") end if + leftCursor = 4 + rightCursor = 4 + while leftCursor < len(left) and rightCursor < len(right) + leftEnd = sqlPartEnd(left, leftCursor) + rightEnd = sqlPartEnd(right, rightCursor) + leftTag = left[leftCursor] + rightTag = right[rightCursor] + if leftTag < rightTag then return -1 end if + if leftTag > rightTag then return 1 end if + comparison = 0 + if leftTag == 2 then + comparison = left[leftCursor + 1] - right[rightCursor + 1] + else if leftTag == 3 or leftTag == 4 then + comparison = compareNumericPart(left, leftCursor + 1, right, rightCursor + 1, leftTag == 4) + else if leftTag == 5 or leftTag == 6 then + comparison = compareByteParts(left, leftCursor + 1, leftEnd, right, rightCursor + 1, rightEnd) + end if + if comparison != 0 then return comparison end if + leftCursor = leftEnd + rightCursor = rightEnd + end while + if leftCursor < len(left) then return 1 end if + if rightCursor < len(right) then return -1 end if + return 0 end function /// Compares the entries. @@ -200,7 +358,8 @@ function compareEntries(left, right) if left is not BTreeEntry or right is not BTreeEntry then return fail(INVALID_ARGUMENT, "compareEntries", "values must be BTreeEntry") end if keyResult = compareKeys(left.key, right.key) if keyResult != 0 then return keyResult end if - return compareKeys(left.value, right.value) + // Values are opaque row references / INCLUDE payloads, never typed keys. + return byte_ops.compareLexicographic(left.value, right.value) end function /// Performs the entry operation for this module. @@ -210,6 +369,7 @@ end function function entry(key, value) if typeof(key) != "bytes" or len(key) == 0 or len(key) > MAX_KEY_BYTES then return fail(INVALID_ARGUMENT, "entry", "key must contain 1..256 bytes") end if if typeof(value) != "bytes" or len(value) == 0 or len(value) > MAX_VALUE_BYTES then return fail(INVALID_ARGUMENT, "entry", "value must contain 1..3584 bytes") end if + validateKey(key) return BTreeEntry(bytes(key), bytes(value)) end function @@ -650,6 +810,7 @@ function decodeInternalWithContext(tree, pageNumber, readContext) if child < 2 or child >= tree.pagedFile.pageCount then return fail(CORRUPT_DATA, "decodeInternal", "child is outside file") end if if cursor > len(encoded) - 12 - keyLength then return fail(CORRUPT_DATA, "decodeInternal", "internal key is truncated") end if key = slice(encoded, cursor + 12, keyLength) + validateKey(key) if previous is not void then separatorOrder = compareKeys(previous, key) if separatorOrder > 0 or (separatorOrder == 0 and tree.meta.unique) then return fail(CORRUPT_DATA, "decodeInternal", "separator keys violate index ordering") end if @@ -984,6 +1145,7 @@ function findWithContext(tree, key, readContext) if typeof(readContext) == "error" then return readContext end if validateOpen(tree, "find") if typeof(key) != "bytes" or len(key) == 0 or len(key) > MAX_KEY_BYTES then return fail(INVALID_ARGUMENT, "find", "key must contain 1..256 bytes") end if + validateKey(key) if tree.meta.entryCount == 0 then return [] end if result = [] leaf = locateLeafWithContext(tree, key, readContext) @@ -1040,6 +1202,8 @@ function rangeWithContext(tree, lower, lowerInclusive, upper, upperInclusive, ma validateOpen(tree, "range") if lower is not void and typeof(lower) != "bytes" then return fail(INVALID_ARGUMENT, "range", "lower must be bytes or void") end if if upper is not void and typeof(upper) != "bytes" then return fail(INVALID_ARGUMENT, "range", "upper must be bytes or void") end if + if lower is not void then validateKey(lower) end if + if upper is not void then validateKey(upper) end if if typeof(lowerInclusive) != "bool" or typeof(upperInclusive) != "bool" then return fail(INVALID_ARGUMENT, "range", "inclusive flags must be bool") end if if typeof(maximum) != "int" or maximum < 0 then return fail(INVALID_ARGUMENT, "range", "maximum must be non-negative") end if if tree.meta.entryCount == 0 then return [] end if diff --git a/src/minisql/storage/heap_file.ml b/src/minisql/storage/heap_file.ml index 85d7c9f..8d4b764 100644 --- a/src/minisql/storage/heap_file.ml +++ b/src/minisql/storage/heap_file.ml @@ -12,6 +12,7 @@ import minisql.storage.page as page import minisql.storage.paged_file as paged_file import minisql.storage.slotted_page as slotted import minisql.storage.superblock as superblock +import minisql.storage.table_header as table_header import std.ds.list as list /// Heap-file storage built on stable slotted pages. External RowId values contain @@ -230,7 +231,8 @@ function decodePageDirectory(file, encoded) heapPageCount = decodeDirectoryNative(endian.readU64LE(payload, 48), "decodePageDirectory", "heapPageCount") if heapPageCount != (len(payload) - PAGE_DIRECTORY_HEADER_BYTES) >> 3 then return fail(CORRUPT_DATA, "decodePageDirectory", "heap page count does not match payload") end if pages = array(heapPageCount) - previous = -1 + if indexedPageCount < table_header.FIRST_DATA_PAGE then return fail(CORRUPT_DATA, "decodePageDirectory", "table header page is not included in the source frontier") end if + previous = table_header.FIRST_DATA_PAGE - 1 if heapPageCount > 0 then for index = 0 to heapPageCount - 1 pageNumber = decodeDirectoryNative(endian.readU64LE(payload, PAGE_DIRECTORY_HEADER_BYTES + index * 8), "decodePageDirectory", "pageNumber") @@ -263,8 +265,10 @@ end function function classifyHeapPages(file, startPage, prefix) output = list.List.new() for each pageNumber in prefix + if pageNumber < table_header.FIRST_DATA_PAGE then return fail(CORRUPT_DATA, "classifyHeapPages", "table header page cannot contain heap rows") end if output.add(pageNumber) end for + if startPage < table_header.FIRST_DATA_PAGE then startPage = table_header.FIRST_DATA_PAGE end if if startPage < file.pageCount then for pageNumber = startPage to file.pageCount - 1 pageBytes = paged_file.readPage(file, pageNumber) @@ -285,7 +289,7 @@ end function /// @param file file value consumed by this operation. function synchronized rebuildHeapPageNumbers(file) directory = loadPageDirectory(file) - startPage = 0 + startPage = table_header.FIRST_DATA_PAGE prefix = [] exact = false if directory is HeapPageDirectory then @@ -341,7 +345,7 @@ end function /// @param slotId Identifier of slot. /// @param generation generation value consumed by this operation. function rowId(pageNumber, slotId, generation) - if typeof(pageNumber) != "int" or pageNumber < 0 or pageNumber > endian.MAX_MINILANG_INT then return fail(INVALID_ARGUMENT, "rowId", "pageNumber must be non-negative") end if + if typeof(pageNumber) != "int" or pageNumber < table_header.FIRST_DATA_PAGE or pageNumber > endian.MAX_MINILANG_INT then return fail(INVALID_ARGUMENT, "rowId", "pageNumber must identify a table data page") end if if typeof(slotId) != "int" or slotId < 0 or slotId > 65535 then return fail(INVALID_ARGUMENT, "rowId", "slotId must fit U16") end if if typeof(generation) != "int" or generation <= 0 or generation > 65535 then return fail(INVALID_ARGUMENT, "rowId", "generation must be a positive U16") end if return RowId(pageNumber, slotId, generation) @@ -403,7 +407,7 @@ end function /// @param fileId Identifier of file. /// @param databaseId Identifier of database. function create(path, pageSize, fileId, databaseId) - file = paged_file.create(path, pageSize, superblock.FILE_TYPE_TABLE, fileId, databaseId) + file = table_header.create(path, pageSize, fileId, databaseId) return HeapFile(file, -1, false) end function @@ -412,7 +416,7 @@ end function /// durable slot reuse without repeating it for every row in a batch. /// @param file file value consumed by this operation. function initialInsertionPage(file) - if file.pageCount == 0 then return -1 end if + if file.pageCount == table_header.FIRST_DATA_PAGE then return -1 end if lastHeapPage = -1 heapPages = heapPageNumbers(file) for each pageNumber in heapPages @@ -433,8 +437,7 @@ end function /// Inputs: `path`. Returns the produced value or propagates a structured error from validation or delegated operations. /// @param path Path of the file or directory used by the operation. function open(path) - file = paged_file.open(path) - if file.fileType != superblock.FILE_TYPE_TABLE then paged_file.close(file); return fail(CORRUPT_DATA, "open", "file is not a table") end if + file = table_header.open(path) hint = try(initialInsertionPage(file)) if typeof(hint) == "error" then paged_file.close(file); return hint end if return HeapFile(file, hint, false) @@ -517,7 +520,7 @@ function insertWithFlags(heap, recordBytes, slotFlags) if slotFlags != slotted.SLOT_FLAG_LIVE and slotFlags != slotted.SLOT_FLAG_MOVED then return fail(INVALID_ARGUMENT, "insertWithFlags", "heap insertion requires live or moved state") end if attemptedHint = -1 - if heap.insertionPageHint >= 0 and heap.insertionPageHint < heap.pagedFile.pageCount then + if heap.insertionPageHint >= table_header.FIRST_DATA_PAGE and heap.insertionPageHint < heap.pagedFile.pageCount then attemptedHint = heap.insertionPageHint pageBytes = try(paged_file.readPage(heap.pagedFile, attemptedHint)) header = try(page.verify(pageBytes)) @@ -541,7 +544,7 @@ function insertWithFlags(heap, recordBytes, slotFlags) // A reopened heap may point at an old reusable slot that is too small for // this row. Try the append frontier once before allocating another page. lastPage = heap.pagedFile.pageCount - 1 - if lastPage >= 0 and lastPage != attemptedHint then + if lastPage >= table_header.FIRST_DATA_PAGE and lastPage != attemptedHint then pageBytes = try(paged_file.readPage(heap.pagedFile, lastPage)) header = try(page.verify(pageBytes)) if header.pageType == page.TYPE_HEAP then @@ -668,7 +671,7 @@ end function function scan(heap) validateOpen(heap, "scan") rows = [] - if heap.pagedFile.pageCount == 0 then return rows end if + if heap.pagedFile.pageCount == table_header.FIRST_DATA_PAGE then return rows end if heapPages = heapPageNumbers(heap.pagedFile) for each pageNumber in heapPages pageBytes = paged_file.readPage(heap.pagedFile, pageNumber) diff --git a/src/minisql/storage/overflow.ml b/src/minisql/storage/overflow.ml index 74f0656..8c863b6 100644 --- a/src/minisql/storage/overflow.ml +++ b/src/minisql/storage/overflow.ml @@ -7,11 +7,12 @@ package minisql.storage.overflow import minisql.common.crc32c as crc32c import minisql.common.endian as endian +import minisql.common.format_version as format_version import minisql.storage.page as page import minisql.storage.paged_file as paged_file import minisql.storage.row_codec as row_codec -/// Overflow-chain format v1 for large TEXT/BLOB values. Every chain page is a +/// Overflow-chain format v2 uses U32 lengths and independently checksummed pointers. const INVALID_ARGUMENT = 9001 /// Defines the unsupported format constant used by the minisql storage overflow module. @@ -20,9 +21,11 @@ const UNSUPPORTED_FORMAT = 9003 const CORRUPT_DATA = 9004 /// Defines the format version constant used by the minisql storage overflow module. -const FORMAT_VERSION = 1 +const FORMAT_VERSION = format_version.OVERFLOW /// Defines the pointer size constant used by the minisql storage overflow module. const POINTER_SIZE = 48 +/// Stores the pointer checksum after the whole-value checksum; zero during CRC calculation. +const POINTER_CHECKSUM_OFFSET = 44 /// Defines the chain header offset constant used by the minisql storage overflow module. const CHAIN_HEADER_OFFSET = 64 /// Defines the chain header size constant used by the minisql storage overflow module. @@ -144,10 +147,12 @@ function encodePointer(pointer) else endian.writeU64LE(output, 16, endian.uint64FromInt(checked.firstPage)) end if - endian.writeU64LE(output, 24, endian.uint64FromInt(checked.totalLength)) + endian.writeU32LE(output, 24, checked.totalLength) + endian.writeU32LE(output, 28, 0) endian.writeU64LE(output, 32, endian.uint64FromInt(checked.ownerId)) endian.writeU32LE(output, 40, checked.valueChecksum) - endian.writeU32LE(output, 44, 0) + endian.writeU32LE(output, POINTER_CHECKSUM_OFFSET, 0) + endian.writeU32LE(output, POINTER_CHECKSUM_OFFSET, crc32c.compute(output)) return output end function @@ -167,14 +172,19 @@ end function function decodePointer(encoded) if typeof(encoded) != "bytes" or len(encoded) != POINTER_SIZE then return fail(CORRUPT_DATA, "decodePointer", "pointer must be 48 bytes") end if if not bytesEqual(slice(encoded, 0, 4), pointerMagic()) then return fail(UNSUPPORTED_FORMAT, "decodePointer", "pointer magic mismatch") end if - if endian.readU16LE(encoded, 4) != FORMAT_VERSION or endian.readU16LE(encoded, 6) != 0 or endian.readU32LE(encoded, 44) != 0 then return fail(UNSUPPORTED_FORMAT, "decodePointer", "unsupported pointer fields") end if + if endian.readU16LE(encoded, 4) != FORMAT_VERSION then return fail(UNSUPPORTED_FORMAT, "decodePointer", "storage format v2 required; legacy overflow pointers are unsupported") end if + pointerBytes = bytes(encoded) + expectedChecksum = endian.readU32LE(pointerBytes, POINTER_CHECKSUM_OFFSET) + endian.writeU32LE(pointerBytes, POINTER_CHECKSUM_OFFSET, 0) + if crc32c.compute(pointerBytes) != expectedChecksum then return fail(CORRUPT_DATA, "decodePointer", "pointer checksum mismatch") end if + if endian.readU16LE(encoded, 6) != 0 or endian.readU32LE(encoded, 28) != 0 then return fail(UNSUPPORTED_FORMAT, "decodePointer", "reserved pointer fields are non-zero") end if firstWords = endian.readU64LE(encoded, 16) firstPage = -1 if firstWords.high != endian.MAX_U32 or firstWords.low != endian.MAX_U32 then firstPage = decodeNative(firstWords, "decodePointer", "firstPage") end if return createPointer( decodeNative(endian.readU64LE(encoded, 8), "decodePointer", "fileId"), firstPage, - decodeNative(endian.readU64LE(encoded, 24), "decodePointer", "totalLength"), + endian.readU32LE(encoded, 24), decodeNative(endian.readU64LE(encoded, 32), "decodePointer", "ownerId"), endian.readU32LE(encoded, 40) ) diff --git a/src/minisql/storage/page.ml b/src/minisql/storage/page.ml index 9c87bcb..d174777 100644 --- a/src/minisql/storage/page.ml +++ b/src/minisql/storage/page.ml @@ -40,6 +40,8 @@ const TYPE_BTREE_INTERNAL = 3 const TYPE_BTREE_LEAF = 4 /// Defines the type catalog constant used by the minisql storage page module. const TYPE_CATALOG = 5 +/// Identifies the immutable page-zero identity header of a version-two user table. +const TYPE_TABLE_META = 6 /// Defines the type generic constant used by the minisql storage page module. const TYPE_GENERIC = 255 diff --git a/src/minisql/storage/row_codec.ml b/src/minisql/storage/row_codec.ml index a6b3cbc..9837615 100644 --- a/src/minisql/storage/row_codec.ml +++ b/src/minisql/storage/row_codec.ml @@ -6,8 +6,10 @@ package minisql.storage.row_codec // Licensed under the Apache License, Version 2.0; see the LICENSE file. import minisql.common.endian as endian +import minisql.common.float_codec as float_codec +import minisql.common.format_version as format_version -/// Row format v1. SQL NULL is represented by SqlNull rather than MiniLang void, +/// Row format v2 uses aligned fields and finite IEEE-754 binary64 values. const INVALID_ARGUMENT = 9001 /// Defines the unsupported format constant used by the minisql storage row codec module. @@ -18,11 +20,13 @@ const CORRUPT_DATA = 9004 const TYPE_MISMATCH = 9017 /// Defines the format version constant used by the minisql storage row codec module. -const FORMAT_VERSION = 1 +const FORMAT_VERSION = format_version.ROW /// Defines the header size constant used by the minisql storage row codec module. const HEADER_SIZE = 16 /// Defines the directory entry size constant used by the minisql storage row codec module. const DIRECTORY_ENTRY_SIZE = 8 +/// Rows and the column directory begin on eight-byte boundaries. +const ROW_ALIGNMENT = 8 /// Defines the type boolean constant used by the minisql storage row codec module. const TYPE_BOOLEAN = 1 @@ -139,6 +143,43 @@ function bytesEqual(left, right) return true end function +/// Rounds an offset upward to its natural power-of-two alignment. +/// @param offset Non-negative byte offset. +/// @param alignment Required alignment in bytes. +function alignOffset(offset, alignment) + remainder = offset % alignment + if remainder == 0 then return offset end if + return offset + alignment - remainder +end function + +/// Returns the physical alignment for a stored column, including external pointers. +/// NULL owns no storage and therefore adds no alignment padding. +/// @param typeCode Physical column type. +/// @param flags Column directory flags. +function valueAlignment(typeCode, flags) + if flags == FLAG_NULL then return 1 end if + if flags == FLAG_EXTERNAL then return 8 end if + if typeCode == TYPE_SMALLINT then return 2 end if + if typeCode == TYPE_INTEGER or typeCode == TYPE_DATE then return 4 end if + if typeCode == TYPE_BIGINT or typeCode == TYPE_REAL or typeCode == TYPE_DOUBLE or typeCode == TYPE_DECIMAL or typeCode == TYPE_TIME or typeCode == TYPE_TIMESTAMP then return 8 end if + return 1 +end function + +/// Rejects nonzero bytes in a bounded, half-open alignment-padding range. +/// @param encoded Encoded row bytes. +/// @param first First padding byte. +/// @param ending Offset immediately after the padding. +/// @param operation Decoder operation used in diagnostics. +function validatePadding(encoded, first, ending, operation) + if first < 0 or ending < first or ending > len(encoded) then return fail(CORRUPT_DATA, operation, "padding exceeds row") end if + if ending > first then + for offset = first to ending - 1 + if encoded[offset] != 0 then return fail(CORRUPT_DATA, operation, "non-zero alignment padding") end if + end for + end if + return true +end function + /// Performs the null value operation for this module. /// Takes no caller-supplied inputs. Returns the produced value or propagates a structured error from validation or delegated operations. function nullValue() @@ -269,9 +310,7 @@ function encodeScalar(spec, value) end if if spec.typeCode == TYPE_REAL or spec.typeCode == TYPE_DOUBLE then if typeof(value) != "float" and typeof(value) != "int" then return fail(TYPE_MISMATCH, "encodeScalar", "floating type requires number") end if - // MiniLang currently has no stable float-bit cast. Format v1 therefore uses - // a canonical UTF-8 numeric rendering and validates it on decode. - return bytes("" + value) + return float_codec.encodeFloat64LE(value) end if if isTextType(spec.typeCode) then return encodeText(spec, value) end if if isBinaryType(spec.typeCode) then return encodeBinary(spec, value) end if @@ -322,11 +361,8 @@ function decodeScalar(spec, encoded) return endian.readI64LE(encoded, 0) end if if spec.typeCode == TYPE_REAL or spec.typeCode == TYPE_DOUBLE then - text = decode(encoded) - if typeof(text) != "string" then return fail(CORRUPT_DATA, "decodeScalar", "floating rendering is not UTF-8") end if - value = toNumber(text) - if typeof(value) != "float" and typeof(value) != "int" then return fail(CORRUPT_DATA, "decodeScalar", "invalid floating rendering") end if - return value + if len(encoded) != 8 then return fail(CORRUPT_DATA, "decodeScalar", "invalid binary64 length") end if + return float_codec.decodeFloat64LE(encoded, 0) end if if isTextType(spec.typeCode) then return decodeText(spec, encoded) end if if isBinaryType(spec.typeCode) then return decodeBinary(spec, encoded) end if @@ -342,10 +378,11 @@ function encode(rowSchema, values) if typeof(values) != "array" or len(values) != len(rowSchema.columns) then return fail(INVALID_ARGUMENT, "encode", "value count does not match schema") end if count = len(values) nullBytes = (count + 7) >> 3 - directoryOffset = HEADER_SIZE + nullBytes + directoryOffset = alignOffset(HEADER_SIZE + nullBytes, ROW_ALIGNMENT) dataOffset = directoryOffset + count * DIRECTORY_ENTRY_SIZE encodedValues = [] flags = [] + valueOffsets = [] total = dataOffset for index = 0 to count - 1 @@ -355,21 +392,27 @@ function encode(rowSchema, values) if not spec.nullable then return fail(TYPE_MISMATCH, "encode", "NULL in NOT NULL column " + index) end if encodedValues = encodedValues + [bytes()] flags = flags + [FLAG_NULL] + valueOffsets = valueOffsets + [total] else if value is ExternalValue then if not isExternalType(spec.typeCode) then return fail(TYPE_MISMATCH, "encode", "external value only allowed for TEXT/BLOB") end if if typeof(value.encodedPointer) != "bytes" or len(value.encodedPointer) == 0 then return fail(TYPE_MISMATCH, "encode", "external pointer must be non-empty bytes") end if encodedValues = encodedValues + [bytes(value.encodedPointer)] flags = flags + [FLAG_EXTERNAL] + total = alignOffset(total, valueAlignment(spec.typeCode, FLAG_EXTERNAL)) + valueOffsets = valueOffsets + [total] total = total + len(value.encodedPointer) else if value is void then return fail(TYPE_MISMATCH, "encode", "MiniLang void is not SQL NULL; use nullValue()") end if encoded = encodeScalar(spec, value) encodedValues = encodedValues + [encoded] flags = flags + [0] + total = alignOffset(total, valueAlignment(spec.typeCode, 0)) + valueOffsets = valueOffsets + [total] total = total + len(encoded) end if end for - if total > 65535 then return fail(INVALID_ARGUMENT, "encode", "encoded row exceeds 65535 bytes") end if + total = alignOffset(total, ROW_ALIGNMENT) + if total > 65535 then return fail(INVALID_ARGUMENT, "encode", "aligned row exceeds 65535 bytes") end if output = bytes(total, 0) copyBytes(output, 0, magicBytes(), 0, 4) @@ -379,19 +422,17 @@ function encode(rowSchema, values) endian.writeU16LE(output, 10, nullBytes) endian.writeU16LE(output, 12, directoryOffset) endian.writeU16LE(output, 14, 0) - cursor = dataOffset for index = 0 to count - 1 entryOffset = directoryOffset + index * DIRECTORY_ENTRY_SIZE endian.writeU16LE(output, entryOffset, rowSchema.columns[index].typeCode) endian.writeU16LE(output, entryOffset + 2, flags[index]) - endian.writeU16LE(output, entryOffset + 4, cursor) + endian.writeU16LE(output, entryOffset + 4, valueOffsets[index]) endian.writeU16LE(output, entryOffset + 6, len(encodedValues[index])) if (flags[index] & FLAG_NULL) != 0 then bitmapByte = HEADER_SIZE + (index >> 3) output[bitmapByte] = output[bitmapByte] | (1 << (index % 8)) else - if len(encodedValues[index]) > 0 then copyBytes(output, cursor, encodedValues[index], 0, len(encodedValues[index])) end if - cursor = cursor + len(encodedValues[index]) + if len(encodedValues[index]) > 0 then copyBytes(output, valueOffsets[index], encodedValues[index], 0, len(encodedValues[index])) end if end if end for return output @@ -410,60 +451,7 @@ end function /// @param rowSchema rowSchema value consumed by this operation. /// @param encoded encoded value consumed by this operation. function decodeRow(rowSchema, encoded) - if rowSchema is not RowSchema then return fail(INVALID_ARGUMENT, "decodeRow", "rowSchema must be RowSchema") end if - if typeof(encoded) != "bytes" or len(encoded) < HEADER_SIZE then return fail(CORRUPT_DATA, "decodeRow", "row is shorter than header") end if - if not bytesEqual(slice(encoded, 0, 4), magicBytes()) then return fail(UNSUPPORTED_FORMAT, "decodeRow", "row magic mismatch") end if - if endian.readU16LE(encoded, 4) != FORMAT_VERSION then return fail(UNSUPPORTED_FORMAT, "decodeRow", "row format mismatch") end if - schemaVersion = endian.readU16LE(encoded, 6) - count = endian.readU16LE(encoded, 8) - nullBytes = endian.readU16LE(encoded, 10) - directoryOffset = endian.readU16LE(encoded, 12) - if endian.readU16LE(encoded, 14) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeRow", "reserved row field is non-zero") end if - if schemaVersion != rowSchema.version then return fail(UNSUPPORTED_FORMAT, "decodeRow", "schema version does not match decoder") end if - if count != len(rowSchema.columns) or nullBytes != ((count + 7) >> 3) or directoryOffset != HEADER_SIZE + nullBytes then return fail(CORRUPT_DATA, "decodeRow", "row shape does not match schema") end if - dataStart = directoryOffset + count * DIRECTORY_ENTRY_SIZE - if dataStart > len(encoded) then return fail(CORRUPT_DATA, "decodeRow", "directory exceeds row") end if - - // Bits beyond the final column are reserved and must stay zero. - if count % 8 != 0 then - lastMask = 0 - for bit = count % 8 to 7 - lastMask = lastMask | (1 << bit) - end for - if (encoded[HEADER_SIZE + nullBytes - 1] & lastMask) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeRow", "reserved NULL-bitmap bits are non-zero") end if - end if - - values = [] - cursor = dataStart - for index = 0 to count - 1 - spec = rowSchema.columns[index] - entryOffset = directoryOffset + index * DIRECTORY_ENTRY_SIZE - typeCode = endian.readU16LE(encoded, entryOffset) - entryFlags = endian.readU16LE(encoded, entryOffset + 2) - valueOffset = endian.readU16LE(encoded, entryOffset + 4) - valueLength = endian.readU16LE(encoded, entryOffset + 6) - if typeCode != spec.typeCode or (entryFlags != 0 and entryFlags != FLAG_NULL and entryFlags != FLAG_EXTERNAL) then return fail(CORRUPT_DATA, "decodeRow", "invalid directory entry") end if - bitmapNull = (encoded[HEADER_SIZE + (index >> 3)] & (1 << (index % 8))) != 0 - if ((entryFlags & FLAG_NULL) != 0) != bitmapNull then return fail(CORRUPT_DATA, "decodeRow", "NULL bitmap disagrees with directory") end if - if valueOffset != cursor then return fail(CORRUPT_DATA, "decodeRow", "non-canonical value offset") end if - - if bitmapNull then - if valueLength != 0 or not spec.nullable then return fail(CORRUPT_DATA, "decodeRow", "invalid NULL value") end if - values = values + [nullValue()] - else - if valueOffset < dataStart or valueOffset > len(encoded) or valueLength > len(encoded) - valueOffset then return fail(CORRUPT_DATA, "decodeRow", "value range exceeds row") end if - valueBytes = slice(encoded, valueOffset, valueLength) - if (entryFlags & FLAG_EXTERNAL) != 0 then - if not isExternalType(spec.typeCode) or valueLength == 0 then return fail(CORRUPT_DATA, "decodeRow", "invalid external LOB pointer") end if - values = values + [ExternalValue(valueBytes)] - else - values = values + [decodeScalar(spec, valueBytes)] - end if - cursor = cursor + valueLength - end if - end for - if cursor != len(encoded) then return fail(CORRUPT_DATA, "decodeRow", "trailing or unreachable row bytes") end if - return RowData(schemaVersion, values) + return decodeAligned(rowSchema, encoded, false) end function /// Decodes the compatible. @@ -471,25 +459,39 @@ end function /// @param rowSchema rowSchema value consumed by this operation. /// @param encoded encoded value consumed by this operation. function decodeCompatible(rowSchema, encoded) - if rowSchema is not RowSchema then return fail(INVALID_ARGUMENT, "decodeCompatible", "rowSchema must be RowSchema") end if - if typeof(encoded) != "bytes" or len(encoded) < HEADER_SIZE then return fail(CORRUPT_DATA, "decodeCompatible", "row is shorter than header") end if - if not bytesEqual(slice(encoded, 0, 4), magicBytes()) then return fail(UNSUPPORTED_FORMAT, "decodeCompatible", "row magic mismatch") end if - if endian.readU16LE(encoded, 4) != FORMAT_VERSION then return fail(UNSUPPORTED_FORMAT, "decodeCompatible", "row format mismatch") end if + return decodeAligned(rowSchema, encoded, true) +end function + +/// Shared v2 decoder: checks canonical alignment, all padding, and schema shape. +/// @param rowSchema Schema used to decode physical column values. +/// @param encoded Complete row bytes, including zero tail padding. +/// @param compatible Whether an older schema with a matching column prefix is accepted. +function decodeAligned(rowSchema, encoded, compatible) + operation = "decodeRow" + if compatible then operation = "decodeCompatible" end if + if rowSchema is not RowSchema then return fail(INVALID_ARGUMENT, operation, "rowSchema must be RowSchema") end if + if typeof(encoded) != "bytes" or len(encoded) < HEADER_SIZE then return fail(CORRUPT_DATA, operation, "row is shorter than header") end if + if not bytesEqual(slice(encoded, 0, 4), magicBytes()) then return fail(UNSUPPORTED_FORMAT, operation, "row magic mismatch") end if + if endian.readU16LE(encoded, 4) != FORMAT_VERSION then return fail(UNSUPPORTED_FORMAT, operation, "row format mismatch") end if + if len(encoded) > 65535 or len(encoded) % ROW_ALIGNMENT != 0 then return fail(CORRUPT_DATA, operation, "row length is not aligned or exceeds U16") end if schemaVersion = endian.readU16LE(encoded, 6) count = endian.readU16LE(encoded, 8) nullBytes = endian.readU16LE(encoded, 10) directoryOffset = endian.readU16LE(encoded, 12) - if endian.readU16LE(encoded, 14) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeCompatible", "reserved row field is non-zero") end if - if schemaVersion <= 0 or schemaVersion > rowSchema.version then return fail(UNSUPPORTED_FORMAT, "decodeCompatible", "stored schema version is newer than decoder") end if - if count <= 0 or count > len(rowSchema.columns) or nullBytes != ((count + 7) >> 3) or directoryOffset != HEADER_SIZE + nullBytes then return fail(CORRUPT_DATA, "decodeCompatible", "row shape is incompatible with schema") end if + if endian.readU16LE(encoded, 14) != 0 then return fail(UNSUPPORTED_FORMAT, operation, "reserved row field is non-zero") end if + if schemaVersion <= 0 or schemaVersion > rowSchema.version then return fail(UNSUPPORTED_FORMAT, operation, "stored schema version is newer than decoder") end if + if not compatible and schemaVersion != rowSchema.version then return fail(UNSUPPORTED_FORMAT, operation, "schema version does not match decoder") end if + if count <= 0 or count > len(rowSchema.columns) or nullBytes != ((count + 7) >> 3) or directoryOffset != alignOffset(HEADER_SIZE + nullBytes, ROW_ALIGNMENT) then return fail(CORRUPT_DATA, operation, "row shape is incompatible with schema") end if + if not compatible and count != len(rowSchema.columns) then return fail(CORRUPT_DATA, operation, "row column count does not match schema") end if dataStart = directoryOffset + count * DIRECTORY_ENTRY_SIZE - if dataStart > len(encoded) then return fail(CORRUPT_DATA, "decodeCompatible", "directory exceeds row") end if + if dataStart > len(encoded) then return fail(CORRUPT_DATA, operation, "directory exceeds row") end if + validatePadding(encoded, HEADER_SIZE + nullBytes, directoryOffset, operation) if count % 8 != 0 then lastMask = 0 for bit = count % 8 to 7 lastMask = lastMask | (1 << bit) end for - if (encoded[HEADER_SIZE + nullBytes - 1] & lastMask) != 0 then return fail(UNSUPPORTED_FORMAT, "decodeCompatible", "reserved NULL-bitmap bits are non-zero") end if + if (encoded[HEADER_SIZE + nullBytes - 1] & lastMask) != 0 then return fail(UNSUPPORTED_FORMAT, operation, "reserved NULL-bitmap bits are non-zero") end if end if output = [] cursor = dataStart @@ -500,18 +502,21 @@ function decodeCompatible(rowSchema, encoded) entryFlags = endian.readU16LE(encoded, entryOffset + 2) valueOffset = endian.readU16LE(encoded, entryOffset + 4) valueLength = endian.readU16LE(encoded, entryOffset + 6) - if typeCode != spec.typeCode or (entryFlags != 0 and entryFlags != FLAG_NULL and entryFlags != FLAG_EXTERNAL) then return fail(CORRUPT_DATA, "decodeCompatible", "invalid directory entry") end if + if typeCode != spec.typeCode or (entryFlags != 0 and entryFlags != FLAG_NULL and entryFlags != FLAG_EXTERNAL) then return fail(CORRUPT_DATA, operation, "invalid directory entry") end if bitmapNull = (encoded[HEADER_SIZE + (index >> 3)] & (1 << (index % 8))) != 0 - if ((entryFlags & FLAG_NULL) != 0) != bitmapNull then return fail(CORRUPT_DATA, "decodeCompatible", "NULL bitmap disagrees with directory") end if - if valueOffset != cursor then return fail(CORRUPT_DATA, "decodeCompatible", "non-canonical value offset") end if + if ((entryFlags & FLAG_NULL) != 0) != bitmapNull then return fail(CORRUPT_DATA, operation, "NULL bitmap disagrees with directory") end if + alignedCursor = alignOffset(cursor, valueAlignment(typeCode, entryFlags)) + if valueOffset != alignedCursor then return fail(CORRUPT_DATA, operation, "non-canonical aligned value offset") end if + validatePadding(encoded, cursor, alignedCursor, operation) + cursor = alignedCursor if bitmapNull then - if valueLength != 0 or not spec.nullable then return fail(CORRUPT_DATA, "decodeCompatible", "invalid NULL value") end if + if valueLength != 0 or not spec.nullable then return fail(CORRUPT_DATA, operation, "invalid NULL value") end if output = output + [nullValue()] else - if valueOffset < dataStart or valueOffset > len(encoded) or valueLength > len(encoded) - valueOffset then return fail(CORRUPT_DATA, "decodeCompatible", "value range exceeds row") end if + if valueOffset < dataStart or valueOffset > len(encoded) or valueLength > len(encoded) - valueOffset then return fail(CORRUPT_DATA, operation, "value range exceeds row") end if valueBytes = slice(encoded, valueOffset, valueLength) if (entryFlags & FLAG_EXTERNAL) != 0 then - if not isExternalType(spec.typeCode) or valueLength == 0 then return fail(CORRUPT_DATA, "decodeCompatible", "invalid external LOB pointer") end if + if not isExternalType(spec.typeCode) or valueLength == 0 then return fail(CORRUPT_DATA, operation, "invalid external LOB pointer") end if output = output + [ExternalValue(valueBytes)] else output = output + [decodeScalar(spec, valueBytes)] @@ -519,7 +524,8 @@ function decodeCompatible(rowSchema, encoded) cursor = cursor + valueLength end if end for - if cursor != len(encoded) then return fail(CORRUPT_DATA, "decodeCompatible", "trailing or unreachable row bytes") end if + if alignOffset(cursor, ROW_ALIGNMENT) != len(encoded) then return fail(CORRUPT_DATA, operation, "non-canonical row tail length") end if + validatePadding(encoded, cursor, len(encoded), operation) return RowData(schemaVersion, output) end function diff --git a/src/minisql/storage/slotted_page.ml b/src/minisql/storage/slotted_page.ml index ba0c5db..3edc920 100644 --- a/src/minisql/storage/slotted_page.ml +++ b/src/minisql/storage/slotted_page.ml @@ -8,7 +8,7 @@ package minisql.storage.slotted_page import minisql.common.endian as endian import minisql.storage.page as page -/// Slotted-page format v1. The slot directory grows from the beginning of the +/// Slotted-page format v2 places record allocations on eight-byte boundaries. const INVALID_ARGUMENT = 9001 /// Defines the corrupt data constant used by the minisql storage slotted page module. @@ -22,6 +22,8 @@ const STALE_REFERENCE = 9018 /// Defines the slot size constant used by the minisql storage slotted page module. const SLOT_SIZE = 8 +/// Every body owns its rounded-up allocation; bytes after its logical end are zero. +const RECORD_ALIGNMENT = 8 /// Defines the slot flag live constant used by the minisql storage slotted page module. const SLOT_FLAG_LIVE = 0 /// Defines the slot flag deleted constant used by the minisql storage slotted page module. @@ -70,6 +72,12 @@ function slotOffset(slotId) return page.HEADER_SIZE + slotId * SLOT_SIZE end function +/// Returns physical storage charged for a body, excluding its directory entry. +/// @param recordLength Logical body length in bytes. +function allocationSize(recordLength) + return ((recordLength + RECORD_ALIGNMENT - 1) >> 3) << 3 +end function + /// Performs the valid flags operation for this module. /// Inputs: `flags`. Returns the produced value or propagates a structured error from validation or delegated operations. /// @param flags Bit flags controlling the operation. @@ -142,6 +150,7 @@ function validate(pageBytes, operation) expectedFreeStart = page.HEADER_SIZE + header.itemCount * SLOT_SIZE if header.freeStart != expectedFreeStart then return fail(CORRUPT_DATA, operation, "slot directory length mismatch") end if if header.freeStart > header.freeEnd then return fail(CORRUPT_DATA, operation, "slot directory overlaps record data") end if + if header.freeEnd % RECORD_ALIGNMENT != 0 then return fail(CORRUPT_DATA, operation, "record area is not aligned") end if occupied = bytes(len(pageBytes), 0) usedBytes = 0 @@ -154,12 +163,15 @@ function validate(pageBytes, operation) if entry.dataOffset != 0 or entry.dataLength != 0 then return fail(CORRUPT_DATA, operation, "deleted slot still references data") end if else if entry.dataLength == 0 then return fail(CORRUPT_DATA, operation, "live slot has zero length") end if - if entry.dataOffset < header.freeEnd or entry.dataOffset > len(pageBytes) or entry.dataLength > len(pageBytes) - entry.dataOffset then + allocated = allocationSize(entry.dataLength) + if entry.dataOffset % RECORD_ALIGNMENT != 0 then return fail(CORRUPT_DATA, operation, "record offset is not aligned") end if + if entry.dataOffset < header.freeEnd or entry.dataOffset > len(pageBytes) or allocated > len(pageBytes) - entry.dataOffset then return fail(CORRUPT_DATA, operation, "slot data range is invalid") end if - usedBytes = usedBytes + entry.dataLength - for byteIndex = entry.dataOffset to entry.dataOffset + entry.dataLength - 1 + usedBytes = usedBytes + allocated + for byteIndex = entry.dataOffset to entry.dataOffset + allocated - 1 if occupied[byteIndex] != 0 then return fail(CORRUPT_DATA, operation, "slot data ranges overlap") end if + if byteIndex >= entry.dataOffset + entry.dataLength and pageBytes[byteIndex] != 0 then return fail(CORRUPT_DATA, operation, "non-zero record alignment padding") end if occupied[byteIndex] = 1 end for end if @@ -320,7 +332,7 @@ function rebuild(pageBytes, replacementSlot, replacement, replacementFlags, dele if deleted then writeEntry(output, slotId, SlotEntry(0, 0, SLOT_FLAG_DELETED, generation)) else - cursor = cursor - len(data) + cursor = cursor - allocationSize(len(data)) if cursor < outputHeader.freeStart then return fail(PAGE_FULL, "rebuild", "records do not fit in page") end if copyBytes(output, cursor, data, 0, len(data)) writeEntry(output, slotId, SlotEntry(cursor, len(data), flags, generation)) @@ -357,7 +369,7 @@ function insertWithFlags(pageBytes, recordBytes, slotFlags) reusable = findDeleted(working, header) directoryBytes = SLOT_SIZE if reusable >= 0 then directoryBytes = 0 end if - if len(recordBytes) + directoryBytes > header.freeEnd - header.freeStart then return fail(PAGE_FULL, "insertWithFlags", "record does not fit") end if + if allocationSize(len(recordBytes)) + directoryBytes > header.freeEnd - header.freeStart then return fail(PAGE_FULL, "insertWithFlags", "aligned record does not fit") end if slotId = reusable generation = 1 @@ -368,7 +380,7 @@ function insertWithFlags(pageBytes, recordBytes, slotFlags) else generation = rawEntry(working, slotId).generation end if - dataOffset = header.freeEnd - len(recordBytes) + dataOffset = header.freeEnd - allocationSize(len(recordBytes)) copyBytes(working, dataOffset, recordBytes, 0, len(recordBytes)) writeEntry(working, slotId, SlotEntry(dataOffset, len(recordBytes), slotFlags, generation)) header.freeEnd = dataOffset diff --git a/src/minisql/storage/table_header.ml b/src/minisql/storage/table_header.ml new file mode 100644 index 0000000..254dedd --- /dev/null +++ b/src/minisql/storage/table_header.ml @@ -0,0 +1,164 @@ +//! Validates the immutable page-zero identity of format-v2 heap tables. + +package minisql.storage.table_header +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +import minisql.common.endian as endian +import minisql.common.format_version as format_version +import minisql.storage.checksum as checksum +import minisql.storage.page as page +import minisql.storage.paged_file as paged_file +import minisql.storage.superblock as superblock + +/// Invalid caller input. +const INVALID_ARGUMENT = 9001 +/// A legacy or unknown physical table format cannot be opened. +const UNSUPPORTED_FORMAT = 9003 +/// Persisted identity or checksum does not match the table file. +const CORRUPT_DATA = 9004 +/// Bytes occupied by the general page header and table-specific metadata. +const HEADER_BYTES = 128 +/// First physical page that can hold heap records or overflow data. +const FIRST_DATA_PAGE = 1 + +/// Creates a structured table-header error. +/// @param code Stable MiniSQL error code. +/// @param operation Name of the failed operation. +/// @param message Details of the violated invariant. +function fail(code, operation, message) + return error(code, "storage.table_header." + operation + ": " + message) +end function + +/// Returns the four-byte table-header magic. +function magicBytes() + return bytes("MSTB") +end function + +/// Creates the immutable page-zero image for a newly created empty table. +/// Creation generation is recorded once; subsequent data-page allocations do +/// not rewrite page zero or publish potentially stale allocation hints. +/// @param file Open newly created user-table paged file. +function encode(file) + paged_file.validateOpen(file, "table_header.encode") + if file.fileType != superblock.FILE_TYPE_TABLE or file.pageCount != 0 then return fail(INVALID_ARGUMENT, "encode", "table header requires a newly created empty table file") end if + if file.generation.high == 0 and file.generation.low == 0 then return fail(INVALID_ARGUMENT, "encode", "creation generation must be non-zero") end if + output = page.create(file.pageSize, page.TYPE_TABLE_META, file.fileId, 0) + header = page.decodePageHeader(output) + copyBytes(output, 64, magicBytes(), 0, 4) + endian.writeU16LE(output, 68, format_version.TABLE) + endian.writeU16LE(output, 70, HEADER_BYTES) + copyBytes(output, 72, file.databaseId, 0, 16) + endian.writeU64LE(output, 88, endian.uint64FromInt(file.fileId)) + endian.writeU32LE(output, 96, file.pageSize) + endian.writeU16LE(output, 100, checksum.ALGORITHM_CRC32C) + endian.writeU16LE(output, 102, format_version.ROW) + endian.writeU64LE(output, 104, file.generation) + endian.writeU64LE(output, 112, endian.uint64FromInt(FIRST_DATA_PAGE)) + endian.writeU64LE(output, 120, endian.makeUInt64(0, 0)) + header.generation = file.generation + header.freeStart = HEADER_BYTES + page.seal(output, header) + return output +end function + +/// Checks table identity, versions and reserved bytes after both page CRCs have +/// been verified. The redundant identity must agree with the file superblock. +/// @param file Open user-table paged file. +/// @param encoded Complete logical page-zero image. +function validatePage(file, encoded) + paged_file.validateOpen(file, "table_header.validatePage") + if file.fileType != superblock.FILE_TYPE_TABLE then return fail(CORRUPT_DATA, "validatePage", "file is not a user table") end if + if typeof(encoded) != "bytes" or len(encoded) != file.pageSize then return fail(CORRUPT_DATA, "validatePage", "table header has the wrong page size") end if + header = page.verify(encoded) + if header.pageType != page.TYPE_TABLE_META or slice(encoded, 64, 4) != magicBytes() then return fail(UNSUPPORTED_FORMAT, "validatePage", "format-v2 table header is missing") end if + if endian.readU16LE(encoded, 68) != format_version.TABLE or endian.readU16LE(encoded, 70) != HEADER_BYTES or endian.readU16LE(encoded, 102) != format_version.ROW then return fail(UNSUPPORTED_FORMAT, "validatePage", "unsupported table or row format") end if + if header.pageId.fileId != file.fileId or header.pageId.pageNumber != 0 then return fail(CORRUPT_DATA, "validatePage", "table header page identity mismatch") end if + storedId = endian.readU64LE(encoded, 88) + if storedId.high > endian.MAX_SCALAR_HIGH or endian.uint64ToInt(storedId) != file.fileId or slice(encoded, 72, 16) != file.databaseId then return fail(CORRUPT_DATA, "validatePage", "table header belongs to another table or database") end if + if endian.readU32LE(encoded, 96) != file.pageSize then return fail(CORRUPT_DATA, "validatePage", "table header page size disagrees with the superblock") end if + if endian.readU16LE(encoded, 100) != checksum.ALGORITHM_CRC32C then return fail(UNSUPPORTED_FORMAT, "validatePage", "unsupported table checksum algorithm") end if + creationGeneration = endian.readU64LE(encoded, 104) + if creationGeneration.high == 0 and creationGeneration.low == 0 then return fail(CORRUPT_DATA, "validatePage", "creation generation is zero") end if + if superblock.compareGeneration(creationGeneration, header.generation) != 0 or superblock.compareGeneration(creationGeneration, file.generation) > 0 then return fail(CORRUPT_DATA, "validatePage", "table creation generation is inconsistent") end if + firstDataPage = endian.readU64LE(encoded, 112) + if firstDataPage.high != 0 or firstDataPage.low != FIRST_DATA_PAGE then return fail(UNSUPPORTED_FORMAT, "validatePage", "unsupported table data-page boundary") end if + if header.flags != 0 or header.itemCount != 0 or header.freeStart != HEADER_BYTES or header.freeEnd != file.pageSize or header.pageLsn.high != 0 or header.pageLsn.low != 0 then return fail(CORRUPT_DATA, "validatePage", "table header page fields are invalid") end if + for offset = 120 to len(encoded) - 1 + if encoded[offset] != 0 then return fail(UNSUPPORTED_FORMAT, "validatePage", "reserved table header bytes are non-zero") end if + end for + return true +end function + +/// Validates an open table, including read-only handles. Empty legacy table +/// files and legacy tables with heap data on page zero are rejected. +/// @param file Open user-table paged file. +function validate(file) + paged_file.validateOpen(file, "table_header.validate") + if file.fileType != superblock.FILE_TYPE_TABLE then return fail(CORRUPT_DATA, "validate", "file is not a table") end if + if file.pageCount < FIRST_DATA_PAGE then return fail(UNSUPPORTED_FORMAT, "validate", "format-v2 table header is missing") end if + return validatePage(file, paged_file.readPage(file, 0)) +end function + +/// Durably reserves page zero before any heap or overflow allocation. +/// @param file Newly created empty user-table paged file. +function initialize(file) + encoded = encode(file) + paged_file.appendPage(file, encoded) + return true +end function + +/// Creates a physical user table with its required immutable header page. +/// Catalog and security paged files intentionally use their own page formats. +/// @param path Destination table path. +/// @param pageSize Database page size. +/// @param fileId Table object identifier. +/// @param databaseId Sixteen-byte database identifier. +function create(path, pageSize, fileId, databaseId) + file = paged_file.create(path, pageSize, superblock.FILE_TYPE_TABLE, fileId, databaseId) + initialized = try(initialize(file)) + if typeof(initialized) == "error" then ignoredClose = try(paged_file.close(file)); return initialized end if + return file +end function + +/// Validates an acquired table handle and releases it on every failure path. +/// @param file Open paged file returned by the selected access mode. +function checkedOpen(file) + checked = try(validate(file)) + if typeof(checked) == "error" then ignoredClose = try(paged_file.close(file)); return checked end if + return file +end function + +/// Opens and validates a writable user table. +/// @param path Existing table path. +function open(path) + return checkedOpen(paged_file.open(path)) +end function + +/// Opens and validates a shared read-only user table. +/// @param path Existing table path. +function openReadOnly(path) + return checkedOpen(paged_file.openReadOnly(path)) +end function + +/// Opens and validates a database-managed read-only user table. +/// @param path Existing table path protected by the database manager. +function openReadOnlyManaged(path) + return checkedOpen(paged_file.openReadOnlyManaged(path)) +end function + +/// Returns the component identifier used by documentation tooling. +function componentName() + return "storage.table_header" +end function + +/// Returns the storage-format milestone owned by this component. +function targetMilestone() + return "StorageV2" +end function + +/// Reports that the table-header codec is implemented. +function isImplemented() + return true +end function diff --git a/src/minisql/tools/backup.ml b/src/minisql/tools/backup.ml index 54e80ea..ce0a4dc 100644 --- a/src/minisql/tools/backup.ml +++ b/src/minisql/tools/backup.ml @@ -22,6 +22,7 @@ import minisql.server.database_manager as database_manager import minisql.storage.btree as btree import minisql.storage.checksum as checksum import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.transaction.wal as wal import minisql.transaction.checkpoint as checkpoint import std.crypto.aes_gcm as aes_gcm @@ -400,7 +401,7 @@ function captureDatabase(database) for each table in database.catalogHandle.catalog.tables relativePath = "tables\\" + catalog.tableFileName(table.tableId) - tableFile = try(paged_file.open(catalog.tableFilePath(database.path, table.tableId))) + tableFile = try(table_header.open(catalog.tableFilePath(database.path, table.tableId))) if typeof(tableFile) == "error" then return tableFile end if image = try(paged_file.snapshotDurableBytes(tableFile, MAX_FILE_BYTES)) closeResult = try(paged_file.close(tableFile)) diff --git a/src/tests/m10_overflow.ml b/src/tests/m10_overflow.ml index e070197..8bc0a64 100644 --- a/src/tests/m10_overflow.ml +++ b/src/tests/m10_overflow.ml @@ -7,6 +7,7 @@ import minisql.platform.file as file_api import minisql.storage.overflow as overflow import minisql.storage.page as page import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.storage.row_codec as rows import minisql.storage.superblock as superblock import tests.support.testkit as testkit @@ -54,7 +55,9 @@ function main(args) cleanup(path) state = testkit.create() testkit.errorCode(state, try(overflow.createPointer(1, 0, 4294967296, 1, 0)), overflow.INVALID_ARGUMENT, "pointer length must fit U32") - file = paged_file.create(path, 4096, superblock.FILE_TYPE_TABLE, 123, databaseId()) + file = table_header.create(path, 4096, 123, databaseId()) + tableHeader = paged_file.readPage(file, 0) + testkit.equal(state, page.verify(tableHeader).pageType, page.TYPE_TABLE_META, "page zero is the table identity header") capacity = overflow.chunkCapacity(file) lengths = [0, 1, capacity - 1, capacity, capacity + 1, capacity * 3 + 17, 262144] pointers = [] @@ -65,6 +68,7 @@ function main(args) pointers = pointers + [pointer] expected = expected + [value] testkit.equal(state, hex(overflow.read(file, pointer)), hex(value), "overflow roundtrip " + lengths[index]) + if lengths[index] > 0 then testkit.record(state, pointer.firstPage >= table_header.FIRST_DATA_PAGE, "overflow starts after the table header") end if end for testkit.record(state, file.pageCount > 60, "large value spans many pages") @@ -114,7 +118,7 @@ function main(args) durablePointer = pointers[6] paged_file.close(file) - reopened = paged_file.open(path) + reopened = table_header.open(path) testkit.equal(state, hex(overflow.read(reopened, durablePointer)), hex(expected[6]), "large value survives reopen") freed = overflow.free(reopened, durablePointer) testkit.record(state, freed > 60, "large chain freed") @@ -123,7 +127,11 @@ function main(args) reusedPointer = overflow.write(reopened, 1200, makeValue(capacity * 2, 111)) testkit.equal(state, reopened.pageCount, pageCountBeforeReuse, "free overflow pages are reused before file growth") testkit.equal(state, hex(overflow.read(reopened, reusedPointer)), hex(makeValue(capacity * 2, 111)), "reused overflow pages remain correct") + testkit.equal(state, hex(paged_file.readPage(reopened, 0)), hex(tableHeader), "allocation freeing and reuse preserve table header bytes") paged_file.close(reopened) + headerChecked = table_header.open(path) + testkit.equal(state, hex(paged_file.readPage(headerChecked, 0)), hex(tableHeader), "table identity survives final reopen") + paged_file.close(headerChecked) cleanup(path) return testkit.finish(state, "MiniSQL M10 overflow tests: SUCCESS", "MiniSQL M10 overflow tests: FAIL") end function diff --git a/src/tests/m50_release_contract.ml b/src/tests/m50_release_contract.ml index 19f6211..f0b9e92 100644 --- a/src/tests/m50_release_contract.ml +++ b/src/tests/m50_release_contract.ml @@ -34,7 +34,7 @@ function main(args) testkit.equal(state, version.productVersion(), "1.1.1", "release semantic version") testkit.equal(state, version.milestone(), "M50", "release milestone freeze") testkit.equal(state, version.WIRE_PROTOCOL_VERSION, 1, "wire protocol remains v1") - testkit.equal(state, version.DATABASE_FORMAT_VERSION, 1, "database format remains v1") + testkit.equal(state, version.DATABASE_FORMAT_VERSION, 2, "database format v2") for each pageSize in [4096, 8192, 16384, 32768] settings = config_model.defaultDatabaseSettings(pageSize) diff --git a/src/tests/m8_catalog.ml b/src/tests/m8_catalog.ml index 0d75fc2..d19dceb 100644 --- a/src/tests/m8_catalog.ml +++ b/src/tests/m8_catalog.ml @@ -3,6 +3,8 @@ // Licensed under the Apache License, Version 2.0; see the LICENSE file for details. import minisql.catalog.catalog as catalog +import minisql.storage.paged_file as paged_file +import minisql.storage.table_header as table_header import minisql.common.uuid as uuid import minisql.config.loader as loader import minisql.platform.file as file_api @@ -61,6 +63,10 @@ function main(args) testkit.record(state, table.columns[0].columnId != table.columns[1].columnId, "column ids unique") tablePath = catalog.tableFilePath(first.path, table.tableId) testkit.record(state, file_api.fileExists(tablePath), "one physical file created per table") + physicalTable = table_header.openReadOnly(tablePath) + testkit.equal(state, physicalTable.pageCount, 1, "new catalog table reserves immutable header page zero") + testkit.record(state, table_header.validate(physicalTable), "catalog table identity header validates") + paged_file.close(physicalTable) tx1 = catalog.allocateTransactionId(first) tx2 = catalog.allocateTransactionId(first) testkit.equal(state, tx1, 1, "first transaction id") diff --git a/src/tests/m8_config.ml b/src/tests/m8_config.ml index be4f115..5518f43 100644 --- a/src/tests/m8_config.ml +++ b/src/tests/m8_config.ml @@ -34,6 +34,11 @@ function main(args) testkit.equal(state, config.databaseDefaults.pageSize, 4096, "page default") testkit.equal(state, config.databaseDefaults.checksumAlgorithm, "crc32c", "checksum default") testkit.equal(state, config.databaseDefaults.textEncoding, "utf-8", "encoding default") + testkit.equal(state, config.databaseDefaults.databaseFormatVersion, 2, "database format v2") + testkit.equal(state, config.databaseDefaults.tableFileFormatVersion, 2, "table format v2") + testkit.equal(state, config.databaseDefaults.indexFileFormatVersion, 2, "index format v2") + testkit.equal(state, config.databaseDefaults.rowFormatVersion, 2, "row format v2") + testkit.equal(state, config.databaseDefaults.walFormatVersion, 1, "unchanged WAL framing") testkit.equal(state, config.runtime.logLevel, "info", "logger threshold") testkit.equal(state, config.server.maxResultBytes, 268435456, "aggregate result byte limit") testkit.equal(state, config.runtime.processMemoryBytes, 2147483648, "managed heap ceiling") @@ -50,6 +55,19 @@ function main(args) testkit.record(state, model.isMiniSqlConfig(config), "config exact type predicate") testkit.record(state, model.isDatabaseDefaults(config.databaseDefaults), "database defaults exact type predicate") testkit.record(state, validation.validate(config), "valid config") + config.databaseDefaults.databaseFormatVersion = 1 + testkit.errorCode(state, try(validation.validate(config)), validation.INVALID_CONFIGURATION, "legacy database defaults rejected") + config.databaseDefaults.databaseFormatVersion = 2 + config.databaseDefaults.tableFileFormatVersion = 1 + testkit.errorCode(state, try(validation.validate(config)), validation.INVALID_CONFIGURATION, "legacy table defaults rejected") + config.databaseDefaults.tableFileFormatVersion = 2 + config.databaseDefaults.indexFileFormatVersion = 1 + testkit.errorCode(state, try(validation.validate(config)), validation.INVALID_CONFIGURATION, "legacy index defaults rejected") + config.databaseDefaults.indexFileFormatVersion = 2 + config.databaseDefaults.rowFormatVersion = 1 + testkit.errorCode(state, try(validation.validate(config)), validation.INVALID_CONFIGURATION, "legacy row defaults rejected") + config.databaseDefaults.rowFormatVersion = 2 + testkit.record(state, validation.validate(config), "v2 defaults restored") testkit.errorCode(state, try(validation.validate([])), validation.INVALID_CONFIGURATION, "wrong config struct rejected") writeText(invalidPath, "{\"configVersion\":1,\"paths\":") diff --git a/src/tests/m9_heap_file.ml b/src/tests/m9_heap_file.ml index f979700..8171866 100644 --- a/src/tests/m9_heap_file.ml +++ b/src/tests/m9_heap_file.ml @@ -100,24 +100,25 @@ function main(args) for index = 0 to 255 appendId = heap_file.insert(appendHeap, makeRecord(index, 3000)) end for - testkit.equal(state, appendHeap.pagedFile.pageCount, 256, "append-heavy rows allocate one page each") - testkit.equal(state, appendId.pageNumber, 255, "append frontier advances linearly") - testkit.equal(state, appendHeap.insertionPageHint, 255, "heap retains the latest insertion page") + testkit.equal(state, appendHeap.pagedFile.pageCount, 257, "append-heavy rows allocate one page each after table header") + testkit.equal(state, appendId.pageNumber, 256, "append frontier advances linearly") + testkit.equal(state, appendHeap.insertionPageHint, 256, "heap retains the latest insertion page") heap_file.close(appendHeap) reopenedAppend = heap_file.open(appendPath) - testkit.equal(state, reopenedAppend.insertionPageHint, 255, "reopened append-only heap resumes at its frontier") + testkit.equal(state, reopenedAppend.insertionPageHint, 256, "reopened append-only heap resumes at its frontier") directoryPath = heap_file.pageDirectoryPath(appendPath) testkit.record(state, file_api.fileExists(directoryPath), "reopen persists heap-page directory") indexedPages = heap_file.heapPageNumbers(reopenedAppend.pagedFile) testkit.equal(state, len(indexedPages), 256, "directory classifies every initial heap page") - testkit.equal(state, indexedPages[255], 255, "directory preserves physical heap order") + testkit.equal(state, indexedPages[0], 1, "directory excludes reserved header page") + testkit.equal(state, indexedPages[255], 256, "directory preserves physical heap order") // Appending mixed page types extends only the newly committed suffix and // never includes overflow pages in the physical heap scan plan. overflowPage = paged_file.allocatePage(reopenedAppend.pagedFile, page.TYPE_OVERFLOW) tailHeapPage = paged_file.allocatePage(reopenedAppend.pagedFile, page.TYPE_HEAP) - testkit.equal(state, overflowPage, 256, "mixed tail overflow page") - testkit.equal(state, tailHeapPage, 257, "mixed tail heap page") + testkit.equal(state, overflowPage, 257, "mixed tail overflow page") + testkit.equal(state, tailHeapPage, 258, "mixed tail heap page") extendedPages = heap_file.heapPageNumbers(reopenedAppend.pagedFile) testkit.equal(state, len(extendedPages), 257, "directory tail extension adds only heap page") testkit.equal(state, extendedPages[256], tailHeapPage, "directory tail records new heap page") diff --git a/src/tests/storage_v2_indexes.ml b/src/tests/storage_v2_indexes.ml new file mode 100644 index 0000000..fb437de --- /dev/null +++ b/src/tests/storage_v2_indexes.ml @@ -0,0 +1,267 @@ +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +import minisql.catalog.metadata as metadata +import minisql.client.console as console +import minisql.common.endian as endian +import minisql.common.float_codec as float_codec +import minisql.config.model as config_model +import minisql.executor.dml as dml +import minisql.executor.executor as executor +import minisql.platform.file as file_api +import minisql.server.database_manager as database_manager +import minisql.sql.types as types +import minisql.sql.values as values +import minisql.storage.btree as btree +import minisql.storage.page as page +import minisql.storage.paged_file as paged_file +import tests.support.testkit as testkit + +// Creates one integral SQL key through the production encoder. +function integerKey(value) + return dml.encodeIndexKey([values.integer(value)]) +end function + +// Creates one binary64 SQL key through the production encoder. +function floatKey(value) + return dml.encodeIndexKey([values.of(types.SqlTypeKind.Double, value)]) +end function + +// Wraps independent IEEE-754 goldens without invoking the floating encoder. +function binaryFloatKey(encodedHex) + return btree.sqlKeyPrefix() + bytes([4]) + fromHex(encodedHex) +end function + +// Verifies persisted bytes and rejects malformed or unsupported key formats. +function checkGoldenCodec(state) + testkit.equal(state, hex(integerKey(1)), "4d534b02030100000000000000", "INT key uses plain I64LE") + testkit.equal(state, hex(integerKey(-1)), "4d534b0203ffffffffffffffff", "negative INT key has unmodified two's complement") + testkit.equal(state, hex(integerKey(255)), "4d534b0203ff00000000000000", "255 key golden") + testkit.equal(state, hex(integerKey(256)), "4d534b02030001000000000000", "256 key golden") + minimum = dml.encodeIndexKey([values.of(types.SqlTypeKind.BigInt, endian.minInt64())]) + maximum = dml.encodeIndexKey([values.of(types.SqlTypeKind.BigInt, endian.maxInt64())]) + testkit.equal(state, hex(minimum), "4d534b02030000000000000080", "INT64 minimum golden") + testkit.equal(state, hex(maximum), "4d534b0203ffffffffffffff7f", "INT64 maximum golden") + testkit.record(state, btree.compareKeys(minimum, integerKey(-1)) < 0, "full INT64 negative range ordering") + testkit.record(state, btree.compareKeys(maximum, integerKey(256)) > 0, "full INT64 positive range ordering") + testkit.record(state, btree.compareKeys(integerKey(255), integerKey(256)) < 0, "numeric ordering differs from LE byte ordering") + testkit.equal(state, hex(floatKey(0.1)), "4d534b02049a9999999999b93f", "DOUBLE key binary64LE golden") + testkit.equal(state, hex(dml.encodeIndexKey([values.of(types.SqlTypeKind.Real, 0.1)])), "4d534b02049a9999999999b93f", "REAL key also uses binary64LE") + negativeZero = float_codec.decodeFloat64LE(fromHex("0000000000000080"), 0) + testkit.equal(state, hex(float_codec.encodeFloat64LE(values.floatingNumberFromText("-0.0e5"))), "0000000000000080", "scientific floating parse preserves negative zero") + testkit.equal(state, hex(floatKey(negativeZero)), "4d534b02040000000000000080", "persisted key preserves negative zero") + testkit.equal(state, hex(dml.encodeConstraintHashKey([values.of(types.SqlTypeKind.Double, negativeZero)])), hex(dml.encodeConstraintHashKey([values.of(types.SqlTypeKind.Double, 0.0)])), "ephemeral unique hash keys equate zero signs") + zeroPart = dml.indexValuePart(values.of(types.SqlTypeKind.Double, negativeZero)) + testkit.equal(state, hex(zeroPart), "040000000000000080", "INCLUDE binary64 preserves negative zero") + doubleColumn = metadata.createColumn(1, "double_value", types.SqlTypeKind.Double, true, 0, 0, 0) + restored = dml.decodeIndexPart(doubleColumn, zeroPart, 0, "test") + testkit.equal(state, hex(float_codec.encodeFloat64LE(restored[0].value)), "0000000000000080", "INCLUDE decoding preserves binary64 bits") + testkit.equal(state, restored[1], 9, "floating index component has fixed width") + textKey = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "Nils")]) + testkit.equal(state, hex(textKey), "4d534b02054e696c730000", "text key version and terminator") + binaryKey = dml.encodeIndexKey([values.of(types.SqlTypeKind.Blob, bytes([65, 0, 255]))]) + testkit.equal(state, hex(binaryKey), "4d534b02064100ffff0000", "binary zero escaping remains self delimiting") + testkit.equal(state, hex(dml.encodeIndexKey([values.nullValue(types.SqlTypeKind.Integer)])), "4d534b0201", "NULL key component") + testkit.equal(state, hex(dml.encodeIndexKey([values.boolean(true)])), "4d534b020201", "Boolean key component") + testkit.errorCode(state, try(btree.entry(fromHex("4d534b01030100000000000000"), bytes([1]))), btree.UNSUPPORTED_FORMAT, "v1 typed key rejected") + testkit.errorCode(state, try(btree.entry(fromHex("4d534b020301"), bytes([1]))), btree.CORRUPT_DATA, "truncated numeric key rejected") + testkit.errorCode(state, try(btree.entry(fromHex("4d534b0205410001"), bytes([1]))), btree.CORRUPT_DATA, "invalid text escape rejected") + testkit.errorCode(state, try(btree.entry(binaryFloatKey("000000000000f07f"), bytes([1]))), btree.CORRUPT_DATA, "infinity key rejected") + testkit.errorCode(state, try(btree.entry(binaryFloatKey("010000000000f87f"), bytes([1]))), btree.CORRUPT_DATA, "NaN key rejected") + testkit.errorCode(state, try(btree.entry(btree.sqlKeyPrefix(), bytes([1]))), btree.CORRUPT_DATA, "empty typed key rejected") +end function + +// Verifies semantic ordering independently of the encoder and heap execution. +function checkComparator(state) + // Independent IEEE-754 vectors cover both signs, subnormals and extreme + // finite values. Comparing encoded words must never stringify a number. + vectors = ["ffffffffffffefff", "00000000000024c0", "00000000000004c0", "0100000000000080", "0000000000000000", "0100000000000000", "000000000000e03f", "0000000000000040", "0000000000002440", "ffffffffffffef7f"] + for left = 0 to len(vectors) - 1 + for right = 0 to len(vectors) - 1 + comparison = btree.compareKeys(binaryFloatKey(vectors[left]), binaryFloatKey(vectors[right])) + if left < right then testkit.record(state, comparison < 0, "finite float vector increasing") end if + if left > right then testkit.record(state, comparison > 0, "finite float vector decreasing") end if + if left == right then testkit.equal(state, comparison, 0, "finite float vector equal") end if + end for + end for + testkit.equal(state, btree.compareKeys(binaryFloatKey("0000000000000000"), binaryFloatKey("0000000000000080")), 0, "comparator equates raw signed zero keys") + prefix = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a")]) + first = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a"), values.integer(255)]) + second = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a"), values.integer(256)]) + nextPrefix = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "b")]) + testkit.record(state, btree.compareKeys(prefix, first) < 0, "short component prefix precedes extension") + testkit.record(state, btree.compareKeys(first, second) < 0, "composite secondary component compares numerically") + testkit.record(state, btree.compareKeys(second, nextPrefix) < 0, "composite prefix boundary") + escaped = dml.encodeIndexKey([values.of(types.SqlTypeKind.Blob, bytes([65, 0]))]) + unescaped = dml.encodeIndexKey([values.of(types.SqlTypeKind.Blob, bytes([65, 1]))]) + shorter = dml.encodeIndexKey([values.of(types.SqlTypeKind.Blob, bytes([65]))]) + testkit.record(state, btree.compareKeys(shorter, escaped) < 0 and btree.compareKeys(escaped, unescaped) < 0, "binary escaped byte ordering") + testkit.record(state, btree.compareKeys(bytes([255]), integerKey(-1)) < 0, "raw and SQL domains have a stable total order") + testkit.record(state, btree.compareKeys(bytes([255]), bytes([0, 1])) > 0, "raw keys keep lexicographic ordering") + // A value can coincidentally begin MSK. It is still opaque, not a SQL key. + leftEntry = btree.entry(integerKey(7), integerKey(255)) + rightEntry = btree.entry(integerKey(7), integerKey(256)) + testkit.record(state, btree.compareEntries(leftEntry, rightEntry) > 0, "leaf values keep raw byte tie ordering") +end function + +// Exercises durable typed trees, ranges, unique keys, reopen and version checks. +function checkTrees(state, root) + databaseId = fromHex("0123456789abcdeffedcba9876543210") + path = file_api.joinPath(root, "typed-index.msi") + tree = btree.create(path, 4096, 9101, databaseId, true) + entries = [] + for number = 270 to 240 + entries = entries + [btree.entry(integerKey(number), bytes("row-" + number))] + end for + entries = entries + [btree.entry(integerKey(-256), bytes("negative")), btree.entry(integerKey(0), bytes("zero"))] + testkit.equal(state, btree.bulkLoad(tree, entries), 33, "typed multi-leaf tree built") + testkit.record(state, btree.height(tree) >= 2 and btree.verify(tree), "typed leaf and separator ordering verifies") + selected = btree.range(tree, integerKey(255), true, integerKey(257), false, 0) + testkit.equal(state, len(selected), 2, "typed half-open range across endian boundary") + testkit.equal(state, decode(selected[0].value), "row-255", "range first value") + testkit.equal(state, decode(selected[1].value), "row-256", "range second value") + testkit.errorCode(state, try(btree.insert(tree, integerKey(256), bytes("duplicate"))), btree.OBJECT_EXISTS, "typed unique duplicate rejected") + metaPage = paged_file.readPage(tree.pagedFile, tree.activeMetaPage) + testkit.equal(state, endian.readU16LE(metaPage, 68), 2, "on-disk B+ tree metadata version is 2") + btree.close(tree) + reopened = btree.open(path) + testkit.record(state, btree.verify(reopened), "typed tree verifies after reopen") + testkit.equal(state, decode(btree.find(reopened, integerKey(256))[0]), "row-256", "typed point read after reopen") + btree.close(reopened) + + floatPath = file_api.joinPath(root, "floating-index.msi") + floatTree = btree.create(floatPath, 4096, 9102, databaseId, true) + btree.bulkLoad(floatTree, [btree.entry(floatKey(10.0), bytes("ten")), btree.entry(floatKey(2.0), bytes("two")), btree.entry(floatKey(-2.5), bytes("negative")), btree.entry(floatKey(0.0), bytes("zero")), btree.entry(floatKey(0.1), bytes("fraction"))]) + selectedFloats = btree.range(floatTree, floatKey(0.1), true, floatKey(10.0), true, 0) + testkit.equal(state, len(selectedFloats), 3, "floating numeric range length") + testkit.equal(state, decode(selectedFloats[1].value), "two", "floating range is numeric not textual") + testkit.errorCode(state, try(btree.insert(floatTree, binaryFloatKey("0000000000000080"), bytes("negative-zero"))), btree.OBJECT_EXISTS, "signed zero cannot bypass unique tree") + btree.close(floatTree) + reopenedFloat = btree.open(floatPath) + testkit.equal(state, decode(btree.find(reopenedFloat, floatKey(2.0))[0]), "two", "floating lookup after reopen") + btree.close(reopenedFloat) + + compositeTree = btree.create(file_api.joinPath(root, "composite-index.msi"), 4096, 9103, databaseId, false) + prefix = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a")]) + endPrefix = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "b")]) + a255 = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a"), values.integer(255)]) + a256 = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "a"), values.integer(256)]) + b0 = dml.encodeIndexKey([values.of(types.SqlTypeKind.Text, "b"), values.integer(0)]) + btree.bulkLoad(compositeTree, [btree.entry(b0, bytes("b")), btree.entry(a256, bytes("a256")), btree.entry(a255, bytes("a255"))]) + compositeRange = btree.range(compositeTree, prefix, true, endPrefix, false, 0) + testkit.equal(state, len(compositeRange), 2, "component-prefix range retains only matching domain") + testkit.equal(state, decode(compositeRange[1].value), "a256", "component-prefix range preserves numeric order") + btree.close(compositeTree) + + // Old metadata must be rejected, even with a fresh valid page checksum. + oldTree = btree.create(file_api.joinPath(root, "old-index.msi"), 4096, 9104, databaseId, true) + oldMeta = paged_file.readPage(oldTree.pagedFile, 0) + endian.writeU16LE(oldMeta, 68, 1) + page.reseal(oldMeta) + paged_file.writePage(oldTree.pagedFile, 0, oldMeta) + testkit.errorCode(state, try(btree.decodeMetaPage(oldTree.pagedFile, 0)), btree.UNSUPPORTED_FORMAT, "version-1 B+ tree metadata rejected") + btree.close(oldTree) +end function + +// Executes SQL and returns the first statement result without hiding failures. +function executeOne(engine, sqlText) + return executor.executeSql(engine, sqlText)[0] +end function + +// Compares complete ordered results, including exact finite binary64 payloads. +function equalRows(state, left, right, label) + testkit.equal(state, len(left.rows), len(right.rows), label + " row count") + if len(left.rows) != len(right.rows) then return false end if + for rowIndex = 0 to len(left.rows) - 1 + testkit.equal(state, len(left.rows[rowIndex]), len(right.rows[rowIndex]), label + " column count") + for columnIndex = 0 to len(left.rows[rowIndex]) - 1 + leftValue = left.rows[rowIndex][columnIndex] + rightValue = right.rows[rowIndex][columnIndex] + testkit.equal(state, values.compareNonNull(leftValue, rightValue), 0, label + " value equality") + if leftValue.typeKind == types.SqlTypeKind.Real or leftValue.typeKind == types.SqlTypeKind.Double then + testkit.equal(state, hex(float_codec.encodeFloat64LE(leftValue.value)), hex(float_codec.encodeFloat64LE(rightValue.value)), label + " exact floating bits") + end if + end for + end for + return true +end function + +// Searches rendered EXPLAIN rows for a trimmed operator prefix. +function planContains(result, text) + for each row in result.rows + if console.startsWithText(console.trimAscii(row[0].value), text) then return true end if + end for + return false +end function + +// Compares indexed SQL execution with heap results and repeats after reopening. +function checkSql(state, root) + managed = database_manager.create(root, "index_v2", config_model.defaultDatabaseSettings(4096)) + databasePath = managed.path + engine = executor.attach(managed) + executeOne(engine, "CREATE TABLE samples (id INTEGER PRIMARY KEY, n BIGINT UNIQUE, f DOUBLE, r REAL, payload DOUBLE, category VARCHAR(20))") + executeOne(engine, "INSERT INTO samples VALUES (1,-257,-10.0,0.1,0.1,'a'),(2,-256,2.0,0.2,0.2,'a'),(3,-1,10.0,0.3,0.3,'a'),(4,0,-2.5,0.4,0.4,'a'),(5,1,CAST('-0.0' AS DOUBLE),CAST('-0.0' AS REAL),CAST('-0.0' AS DOUBLE),'a'),(6,2,0.25,0.6,0.6,'a'),(7,254,2.25,0.7,0.7,'b'),(8,255,255.0,0.8,0.8,'b'),(9,256,256.0,0.9,0.9,'b'),(10,257,1000.0,1.1,1.1,'b'),(11,511,-0.5,1.2,1.2,'b'),(12,512,1.25,1.3,1.3,'b')") + query = "SELECT f,n,payload,r FROM samples WHERE f >= -2.5 ORDER BY f,n" + heapBaseline = executeOne(engine, query) + zeroQuery = "SELECT f,r,payload FROM samples WHERE f = 0.0" + zeroBaseline = executeOne(engine, zeroQuery) + testkit.equal(state, len(zeroBaseline.rows), 1, "signed-zero heap fixture has one row") + for columnIndex = 0 to 2 + testkit.equal(state, hex(float_codec.encodeFloat64LE(zeroBaseline.rows[0][columnIndex].value)), "0000000000000080", "heap fixture contains actual negative-zero bits") + end for + executeOne(engine, "CREATE INDEX ix_samples_f ON samples(f) INCLUDE(n,payload,r)") + indexed = executeOne(engine, query) + equalRows(state, heapBaseline, indexed, "heap vs binary64 covering index") + equalRows(state, zeroBaseline, executeOne(engine, zeroQuery), "positive-zero seek preserves stored negative-zero key") + testkit.record(state, planContains(executeOne(engine, "EXPLAIN SELECT f,r,payload FROM samples WHERE f = 0.0"), "Index Only Scan"), "signed-zero equality uses covering DOUBLE key") + executeOne(engine, "CREATE INDEX ix_samples_r ON samples(r) INCLUDE(f,payload)") + realZeroQuery = "SELECT f,r,payload FROM samples WHERE r = 0.0" + equalRows(state, zeroBaseline, executeOne(engine, realZeroQuery), "positive-zero seek preserves stored REAL key") + executeOne(engine, "CREATE INDEX ix_samples_category_f ON samples(category,f) INCLUDE(r,payload)") + compositeZeroQuery = "SELECT f,r,payload FROM samples WHERE category = 'a' AND f = 0.0" + equalRows(state, zeroBaseline, executeOne(engine, compositeZeroQuery), "composite equality preserves stored negative-zero component") + testkit.record(state, planContains(executeOne(engine, "EXPLAIN SELECT f,n,payload,r FROM samples WHERE f >= -2.5 ORDER BY f,n"), "Index Only Scan"), "floating key/INCLUDE fields enable index-only plan") + integral = executeOne(engine, "SELECT n FROM samples WHERE n >= 255 AND n < 511 ORDER BY n") + testkit.equal(state, len(integral.rows), 3, "SQL signed little-endian index range") + testkit.equal(state, endian.int64ToInt(integral.rows[0][0].value), 255, "SQL index lower endian boundary") + testkit.equal(state, endian.int64ToInt(integral.rows[2][0].value), 257, "SQL index upper endian boundary") + executeOne(engine, "CREATE INDEX ix_samples_composite ON samples(category,n) INCLUDE(f)") + composite = executeOne(engine, "SELECT f FROM samples WHERE category = 'b' AND n = 256") + testkit.equal(state, composite.rows[0][0].value, 256.0, "composite typed key decodes floating INCLUDE") + executeOne(engine, "CREATE TABLE floating_unique (f DOUBLE UNIQUE)") + executeOne(engine, "INSERT INTO floating_unique VALUES (0.0)") + testkit.errorCode(state, try(executeOne(engine, "INSERT INTO floating_unique VALUES (CAST('-0.0' AS DOUBLE))")), 9022, "SQL unique index equates actual zero signs") + executeOne(engine, "INSERT INTO floating_unique VALUES (2.0),(10.0),(-2.5),(NULL),(NULL)") + ordered = executeOne(engine, "SELECT f FROM floating_unique WHERE f > 0.0 ORDER BY f") + testkit.equal(state, len(ordered.rows), 2, "SQL floating range excludes NULL") + testkit.equal(state, ordered.rows[0][0].value, 2.0, "SQL floating range numeric order") + testkit.equal(state, ordered.rows[1][0].value, 10.0, "SQL floating range final value") + testkit.record(state, dml.verifyAllIndexes(managed) >= 5, "all binary index representations match heaps") + executor.close(engine) + database_manager.close(managed) + reopened = executor.open(databasePath) + equalRows(state, heapBaseline, executeOne(reopened, query), "covering index after database reopen") + equalRows(state, zeroBaseline, executeOne(reopened, zeroQuery), "signed-zero DOUBLE equality after reopen") + equalRows(state, zeroBaseline, executeOne(reopened, realZeroQuery), "signed-zero REAL equality after reopen") + equalRows(state, zeroBaseline, executeOne(reopened, compositeZeroQuery), "signed-zero composite equality after reopen") + executeOne(reopened, "UPDATE samples SET f = 3.5, payload = 0.123456789012345 WHERE id = 8") + updated = executeOne(reopened, "SELECT f,payload FROM samples WHERE f = 3.5") + testkit.equal(state, len(updated.rows), 1, "binary float index update adds new key") + testkit.equal(state, updated.rows[0][0].value, 3.5, "updated floating key decodes") + testkit.equal(state, len(executeOne(reopened, "SELECT f FROM samples WHERE f = 255.0").rows), 0, "binary float index update removes old key") + testkit.record(state, dml.verifyAllIndexes(reopened.database) >= 5, "reopened updated float indexes match heaps") + executor.close(reopened) +end function + +// Runs the regression against one caller-owned fresh data directory. +function main(args) + if len(args) != 1 then print "MiniSQL storage v2 index tests: FAIL (missing fresh data root)"; return 1 end if + file_api.createDirectory(args[0]) + state = testkit.create() + checkGoldenCodec(state) + checkComparator(state) + checkTrees(state, args[0]) + checkSql(state, args[0]) + return testkit.finish(state, "MiniSQL storage v2 index tests: SUCCESS", "MiniSQL storage v2 index tests: FAIL") +end function diff --git a/src/tests/storage_v2_metadata.ml b/src/tests/storage_v2_metadata.ml new file mode 100644 index 0000000..7c68054 --- /dev/null +++ b/src/tests/storage_v2_metadata.ml @@ -0,0 +1,47 @@ +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +import minisql.catalog.metadata as metadata +import minisql.common.endian as endian +import minisql.config.model as config_model +import minisql.storage.checksum as checksum +import tests.support.testkit as testkit + +// Checks persisted version identities independently of configuration defaults. +function main(args) + state = testkit.create() + defaults = config_model.defaultDatabaseSettings(4096) + testkit.equal(state, defaults.databaseFormatVersion, 2, "new database defaults use v2") + value = metadata.createDatabase("v2", bytes(16, 7), 4096, 67108864, 2, 2, 2, 1, 2) + encoded = metadata.encodeDatabase(value) + testkit.equal(state, hex(slice(encoded, 0, 12)), "4d5344424d30303102000100", "db.meta magic, envelope version and kind golden") + envelope = checksum.decodeEnvelope(encoded, metadata.databaseMagic(), 2, metadata.DATABASE_KIND) + testkit.equal(state, hex(slice(envelope.payload, 8, 10)), "02000200020001000200", "persisted version tuple golden") + restored = metadata.decodeDatabase(encoded) + testkit.equal(state, restored.name, "v2", "metadata name roundtrip") + testkit.equal(state, restored.databaseFormatVersion, 2, "metadata format roundtrip") + testkit.equal(state, restored.pageSize, 4096, "persisted page size roundtrip") + + legacy = checksum.encodeEnvelope(metadata.databaseMagic(), 1, metadata.DATABASE_KIND, 0, envelope.payload) + testkit.errorCode(state, try(metadata.decodeDatabase(legacy)), metadata.UNSUPPORTED_FORMAT, "legacy envelope rejected") + for each fieldOffset in [8, 10, 12, 16] + payload = bytes(envelope.payload) + endian.writeU16LE(payload, fieldOffset, 1) + mixed = checksum.encodeEnvelope(metadata.databaseMagic(), 2, metadata.DATABASE_KIND, 0, payload) + testkit.errorCode(state, try(metadata.decodeDatabase(mixed)), metadata.UNSUPPORTED_FORMAT, "mixed v1 payload rejected") + end for + payload = bytes(envelope.payload) + endian.writeU16LE(payload, 14, 2) + futureWal = checksum.encodeEnvelope(metadata.databaseMagic(), 2, metadata.DATABASE_KIND, 0, payload) + testkit.errorCode(state, try(metadata.decodeDatabase(futureWal)), metadata.UNSUPPORTED_FORMAT, "unsupported WAL framing rejected") + flagged = checksum.encodeEnvelope(metadata.databaseMagic(), 2, metadata.DATABASE_KIND, 1, envelope.payload) + testkit.errorCode(state, try(metadata.decodeDatabase(flagged)), metadata.UNSUPPORTED_FORMAT, "unknown envelope flags rejected") + for each reservedOffset in [64, 68, 72, 76] + payload = bytes(envelope.payload) + endian.writeU32LE(payload, reservedOffset, 1) + reserved = checksum.encodeEnvelope(metadata.databaseMagic(), 2, metadata.DATABASE_KIND, 0, payload) + testkit.errorCode(state, try(metadata.decodeDatabase(reserved)), metadata.UNSUPPORTED_FORMAT, "reserved payload bytes rejected") + end for + return testkit.finish(state, "MiniSQL storage v2 metadata tests: SUCCESS", "MiniSQL storage v2 metadata tests: FAIL") +end function diff --git a/src/tests/storage_v2_overflow.ml b/src/tests/storage_v2_overflow.ml new file mode 100644 index 0000000..afb6ce9 --- /dev/null +++ b/src/tests/storage_v2_overflow.ml @@ -0,0 +1,59 @@ +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file for details. + +import minisql.common.crc32c as crc32c +import minisql.common.endian as endian +import minisql.common.format_version as format_version +import minisql.storage.overflow as overflow +import tests.support.testkit as testkit + +/// Repairs the checksum after a deliberate structural mutation in a decoder test. +/// @param pointer Encoded pointer to reseal in place. +function resealPointer(pointer) + endian.writeU32LE(pointer, overflow.POINTER_CHECKSUM_OFFSET, 0) + endian.writeU32LE(pointer, overflow.POINTER_CHECKSUM_OFFSET, crc32c.compute(pointer)) + return pointer +end function + +/// Verifies the external-pointer byte contract without allocating large LOB values. +/// @param args Unused command-line arguments. +function main(args) + state = testkit.create() + pointer = overflow.createPointer(123, 3, 0x01020304, 0x05060708, 0xA1B2C3D4) + encoded = overflow.encodePointer(pointer) + expected = "4d534f50020000007b00000000000000030000000000000004030201000000000807060500000000d4c3b2a1274af41d" + testkit.equal(state, hex(encoded), expected, "independent U32 length and CRC golden vector") + testkit.equal(state, len(encoded), 48, "pointer remains eight-byte aligned") + testkit.equal(state, endian.readU16LE(encoded, 4), format_version.OVERFLOW, "explicit overflow version two") + testkit.equal(state, endian.readU32LE(encoded, 24), 0x01020304, "length is one U32") + testkit.equal(state, endian.readU32LE(encoded, 28), 0, "length is followed by reserved alignment bytes") + decoded = overflow.decodePointer(encoded) + testkit.equal(state, decoded.totalLength, pointer.totalLength, "pointer length decodes") + testkit.equal(state, decoded.ownerId, pointer.ownerId, "owner remains aligned at offset32") + testkit.equal(state, decoded.valueChecksum, pointer.valueChecksum, "value CRC independent from pointer CRC") + + largest = overflow.encodePointer(overflow.createPointer(123, 1, 4294967295, 1, 0)) + testkit.equal(state, overflow.decodePointer(largest).totalLength, 4294967295, "maximum U32 length roundtrip without allocation") + testkit.errorCode(state, try(overflow.createPointer(123, 1, 4294967296, 1, 0)), overflow.INVALID_ARGUMENT, "U32 overflow rejected") + empty = overflow.encodePointer(overflow.createPointer(123, -1, 0, 1, 0)) + testkit.equal(state, hex(slice(empty, 16, 8)), "ffffffffffffffff", "empty value has no-next-page sentinel") + testkit.equal(state, overflow.decodePointer(empty).totalLength, 0, "empty value roundtrip") + + damaged = bytes(encoded) + damaged[24] = damaged[24] ^ 1 + testkit.errorCode(state, try(overflow.decodePointer(damaged)), overflow.CORRUPT_DATA, "length corruption detected by pointer CRC") + damaged = bytes(encoded) + damaged[40] = damaged[40] ^ 1 + testkit.errorCode(state, try(overflow.decodePointer(damaged)), overflow.CORRUPT_DATA, "value CRC itself is protected") + damaged = bytes(encoded) + endian.writeU32LE(damaged, 28, 1) + resealPointer(damaged) + testkit.errorCode(state, try(overflow.decodePointer(damaged)), overflow.UNSUPPORTED_FORMAT, "nonzero reserved field is not a U64 length extension") + legacy = bytes(encoded) + endian.writeU16LE(legacy, 4, 1) + resealPointer(legacy) + testkit.errorCode(state, try(overflow.decodePointer(legacy)), overflow.UNSUPPORTED_FORMAT, "legacy pointer rejected explicitly") + testkit.errorCode(state, try(overflow.decodePointer(slice(encoded, 0, 44))), overflow.CORRUPT_DATA, "truncated pointer rejected") + return testkit.finish(state, "MiniSQL storage v2 overflow tests: SUCCESS", "MiniSQL storage v2 overflow tests: FAIL") +end function diff --git a/src/tests/storage_v2_rows.ml b/src/tests/storage_v2_rows.ml new file mode 100644 index 0000000..12c27f7 --- /dev/null +++ b/src/tests/storage_v2_rows.ml @@ -0,0 +1,195 @@ +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see the LICENSE file. + +import minisql.common.endian as endian +import minisql.common.float_codec as floats +import minisql.storage.page as page +import minisql.storage.row_codec as rows +import minisql.storage.slotted_page as slotted +import tests.support.testkit as testkit + +#if TARGET_OS == "windows" +/// Produces a native NaN for the finite-input rejection test. +extern function testSqrt(value as double) from "msvcrt.dll" symbol "sqrt" returns double +#else +/// Produces a native NaN for the finite-input rejection test. +extern function testSqrt(value as double) from "libm.so.6" symbol "sqrt" returns double +#endif + +/// Checks exact binary64 bits through decode, encode, and a physical SQL row. +function checkFloatBits(state, spelling, label) + encoded = fromHex(spelling) + value = floats.decodeFloat64LE(encoded, 0) + testkit.equal(state, typeof(value), "float", label + " remains float") + testkit.equal(state, hex(floats.encodeFloat64LE(value)), spelling, label + " exact bits") + schema = rows.schema(1, [rows.column(rows.TYPE_DOUBLE, false, 0, 0, 0)]) + row = rows.encode(schema, [value]) + decoded = rows.decodeRow(schema, row) + testkit.equal(state, hex(floats.encodeFloat64LE(decoded.values[0])), spelling, label + " row roundtrip") +end function + +/// Checks source-level numeric input against independent IEEE-754 golden bytes. +function checkFloatValue(state, value, spelling, label) + testkit.equal(state, hex(floats.encodeFloat64LE(value)), spelling, label) +end function + +/// Builds the user-facing three-column row example. +function exampleSchema(version) + return rows.schema(version, [ + rows.column(rows.TYPE_BIGINT, false, 0, 0, 0), + rows.column(rows.TYPE_TEXT, true, 0, 0, 0), + rows.column(rows.TYPE_BOOLEAN, false, 0, 0, 0) + ]) +end function + +/// Runs binary64, row alignment, corruption, and slotted-allocation regressions. +function main(args) + state = testkit.create() + checkFloatValue(state, 0.0, "0000000000000000", "positive zero") + checkFloatValue(state, 1.0, "000000000000f03f", "one") + checkFloatValue(state, -2.5, "00000000000004c0", "negative finite") + checkFloatValue(state, 0.1, "9a9999999999b93f", "decimal literal full precision") + checkFloatValue(state, 1.0000000000000002, "010000000000f03f", "next representable one") + checkFloatValue(state, 9007199254740991, "ffffffffffff3f43", "largest exact 53-bit integer") + patterns = [ + "0000000000000000", "0000000000000080", + "0100000000000000", "0100000000000080", + "ffffffffffff0f00", "ffffffffffff0f80", + "0000000000001000", "0000000000001080", + "010000000000f03f", "ffffffffffffef7f", "ffffffffffffefff", + "9a9999999999b93f", "182d4454fb210940", "785634120000f03f" + ] + for index = 0 to len(patterns) - 1 + checkFloatBits(state, patterns[index], "binary64 vector " + index) + end for + // Exercise finite bit patterns across signs, exponents and significands, + // independently of decimal parsing and source literal rounding. + lowWord = 0x9e3779b9 + highWord = 0x12345678 + for index = 0 to 127 + lowWord = (lowWord * 1664525 + 1013904223) & 0xFFFFFFFF + highWord = (highWord * 22695477 + 1) & 0xFFFFFFFF + finiteHigh = highWord + if ((finiteHigh >> 20) & 2047) == 2047 then finiteHigh = finiteHigh ^ 0x00100000 end if + vector = bytes(8, 0) + endian.writeU32LE(vector, 0, lowWord) + endian.writeU32LE(vector, 4, finiteHigh) + checkFloatBits(state, hex(vector), "finite bit pattern " + index) + end for + testkit.errorCode(state, try(floats.decodeFloat64LE(fromHex("000000000000f07f"), 0)), floats.CORRUPT_DATA, "infinity bytes rejected") + testkit.errorCode(state, try(floats.decodeFloat64LE(fromHex("000000000000f8ff"), 0)), floats.CORRUPT_DATA, "NaN bytes rejected") + testkit.errorCode(state, try(floats.encodeFloat64LE(floats.nativeLdexp(1.0, 1024))), floats.TYPE_MISMATCH, "infinity value rejected") + testkit.errorCode(state, try(floats.encodeFloat64LE(testSqrt(-1.0))), floats.TYPE_MISMATCH, "NaN value rejected") + testkit.errorCode(state, try(floats.decodeFloat64LE(bytes(7), 0)), floats.INVALID_ARGUMENT, "truncated float rejected") + + schema = exampleSchema(1) + encoded = rows.encode(schema, [endian.int64FromInt(1), "Nils", true]) + expected = "4d535257020001000300010018000000000000000000000004000000300008000a00000038000400010000003c00010001000000000000004e696c7301000000" + testkit.equal(state, hex(encoded), expected, "exact aligned row vector") + testkit.equal(state, len(encoded), 64, "example row length") + testkit.equal(state, endian.readU16LE(encoded, 12), 24, "directory starts on eight-byte boundary") + testkit.equal(state, endian.readU16LE(encoded, 28), 48, "BIGINT offset") + testkit.equal(state, endian.readU16LE(encoded, 36), 56, "TEXT offset") + testkit.equal(state, endian.readU16LE(encoded, 44), 60, "BOOLEAN offset") + + // Reserved header, bitmap-directory padding, field offsets and tail padding + // remain invalid even when their enclosing page checksum would be recomputed. + corrupt = bytes(encoded) + corrupt[4] = 1 + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.UNSUPPORTED_FORMAT, "v1 row rejected") + corrupt = bytes(encoded) + corrupt[17] = 1 + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.CORRUPT_DATA, "directory padding rejected") + corrupt = bytes(encoded) + corrupt[63] = 1 + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.CORRUPT_DATA, "row tail padding rejected") + corrupt = bytes(encoded) + endian.writeU16LE(corrupt, 28, 49) + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.CORRUPT_DATA, "misaligned scalar offset rejected") + corrupt = bytes(encoded) + endian.writeU16LE(corrupt, 30, 65535) + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.CORRUPT_DATA, "value length outside row rejected") + corrupt = bytes(encoded) + endian.writeU16LE(corrupt, 12, 65528) + testkit.errorCode(state, try(rows.decodeRow(schema, corrupt)), rows.CORRUPT_DATA, "directory outside row rejected") + testkit.errorCode(state, try(rows.decodeRow(schema, encoded + bytes(8, 0))), rows.CORRUPT_DATA, "redundant aligned tail rejected") + testkit.errorCode(state, try(rows.decodeRow(schema, slice(encoded, 0, 63))), rows.CORRUPT_DATA, "unaligned length rejected") + + // Inter-value padding exercises every scalar alignment, NULL, empty values, + // and an external pointer following an unaligned one-byte string. + mixed = rows.schema(1, [ + rows.column(rows.TYPE_BOOLEAN, false, 0, 0, 0), + rows.column(rows.TYPE_SMALLINT, false, 0, 0, 0), + rows.column(rows.TYPE_BOOLEAN, false, 0, 0, 0), + rows.column(rows.TYPE_INTEGER, false, 0, 0, 0), + rows.column(rows.TYPE_BOOLEAN, false, 0, 0, 0), + rows.column(rows.TYPE_REAL, false, 0, 0, 0), + rows.column(rows.TYPE_TEXT, false, 0, 0, 0), + rows.column(rows.TYPE_BLOB, false, 0, 0, 0), + rows.column(rows.TYPE_INTEGER, true, 0, 0, 0), + rows.column(rows.TYPE_VARCHAR, false, 8, 0, 0) + ]) + mixedRow = rows.encode(mixed, [true, -123, false, 123456, true, 0.1, "x", rows.external(bytes(48, 0x11)), rows.nullValue(), ""]) + offsets = [104, 106, 108, 112, 116, 120, 128, 136, 184, 184] + for index = 0 to len(offsets) - 1 + testkit.equal(state, endian.readU16LE(mixedRow, 24 + index * 8 + 4), offsets[index], "natural alignment " + index) + end for + testkit.equal(state, len(mixedRow), 184, "mixed row aligned length") + mixedDecoded = rows.decodeRow(mixed, mixedRow) + testkit.record(state, rows.isNull(mixedDecoded.values[8]), "NULL remains NULL") + testkit.equal(state, mixedDecoded.values[9], "", "empty string remains distinct from NULL") + for each badOffset in [105, 109, 117, 129] + corrupt = bytes(mixedRow) + corrupt[badOffset] = 1 + testkit.errorCode(state, try(rows.decodeCompatible(mixed, corrupt)), rows.CORRUPT_DATA, "inter-value padding rejected " + badOffset) + end for + newer = rows.schema(2, schema.columns + [rows.column(rows.TYPE_INTEGER, true, 0, 0, 0)]) + testkit.equal(state, len(rows.decodeCompatible(newer, encoded).values), 3, "schema-prefix evolution remains valid") + + raw = slotted.create(4096, 100, 1) + firstSlot = slotted.insert(raw, bytes("abc")) + secondSlot = slotted.insert(raw, bytes(9, 0x5a)) + testkit.equal(state, slotted.entry(raw, firstSlot).dataOffset, 4088, "three-byte record allocation") + testkit.equal(state, slotted.entry(raw, secondSlot).dataOffset, 4072, "nine-byte record allocation") + testkit.equal(state, slotted.entry(raw, firstSlot).dataLength, 3, "slot length excludes padding") + testkit.equal(state, slotted.freeBytes(raw), 3992, "padding charged to page space") + corrupt = bytes(raw) + corrupt[4091] = 1 + page.reseal(corrupt) + testkit.errorCode(state, try(slotted.validate(corrupt, "test")), slotted.CORRUPT_DATA, "slot padding rejected") + corruptBefore = bytes(corrupt) + testkit.errorCode(state, try(slotted.compact(corrupt)), slotted.CORRUPT_DATA, "compaction rejects corrupt padding") + testkit.equal(state, hex(corrupt), hex(corruptBefore), "failed compaction is byte atomic") + corrupt = bytes(raw) + endian.writeU16LE(corrupt, slotted.slotOffset(firstSlot), 4089) + page.reseal(corrupt) + testkit.errorCode(state, try(slotted.validate(corrupt, "test")), slotted.CORRUPT_DATA, "unaligned slot offset rejected") + corrupt = bytes(raw) + endian.writeU16LE(corrupt, slotted.slotOffset(firstSlot) + 2, 65535) + page.reseal(corrupt) + testkit.errorCode(state, try(slotted.validate(corrupt, "test")), slotted.CORRUPT_DATA, "allocation outside page rejected") + corrupt = bytes(raw) + endian.writeU16LE(corrupt, slotted.slotOffset(secondSlot), 4088) + page.reseal(corrupt) + testkit.errorCode(state, try(slotted.validate(corrupt, "test")), slotted.CORRUPT_DATA, "overlapping allocations rejected") + slotted.update(raw, firstSlot, bytes(17, 0x33)) + slotted.compact(raw) + testkit.equal(state, slotted.entry(raw, firstSlot).dataOffset % 8, 0, "update alignment") + testkit.equal(state, slotted.entry(raw, secondSlot).dataOffset % 8, 0, "compaction alignment") + oldGeneration = slotted.entry(raw, secondSlot).generation + slotted.remove(raw, secondSlot) + replacement = slotted.insert(raw, bytes(1, 0x44)) + testkit.equal(state, replacement, secondSlot, "deleted slot reused") + testkit.equal(state, slotted.entry(raw, replacement).generation, oldGeneration + 1, "generation retained on reuse") + testkit.equal(state, len(slotted.read(raw, replacement)), 1, "padding is not returned as record data") + full = slotted.create(4096, 101, 1) + slotted.insert(full, bytes(4023, 0x55)) + testkit.equal(state, slotted.freeBytes(full), 0, "near-page record consumes rounded allocation") + snapshot = bytes(full) + testkit.errorCode(state, try(slotted.insert(full, bytes(1, 0x66))), slotted.PAGE_FULL, "aligned page capacity enforced") + testkit.equal(state, hex(full), hex(snapshot), "failed insertion is byte atomic") + testkit.errorCode(state, try(slotted.update(full, 0, bytes(4025, 0x77))), slotted.PAGE_FULL, "growing update accounts for aligned size") + testkit.equal(state, hex(full), hex(snapshot), "failed update is byte atomic") + return testkit.finish(state, "MiniSQL storage v2 row tests: SUCCESS", "MiniSQL storage v2 row tests: FAIL") +end function diff --git a/src/tests/storage_v2_table.ml b/src/tests/storage_v2_table.ml new file mode 100644 index 0000000..25ebfc5 --- /dev/null +++ b/src/tests/storage_v2_table.ml @@ -0,0 +1,131 @@ +// Copyright 2026 MiniLangProject contributors +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0; see LICENSE for details. + +import minisql.common.endian as endian +import minisql.platform.file as file_api +import minisql.storage.heap_file as heap_file +import minisql.storage.page as page +import minisql.storage.paged_file as paged_file +import minisql.storage.superblock as superblock +import minisql.storage.table_header as table_header +import tests.support.testkit as testkit + +/// Removes an isolated test file when present. +/// @param path Test artifact path. +function cleanup(path) + ignored = try(file_api.deletePath(path)) + return true +end function + +/// Returns a stable database identity for golden header fields. +function databaseId() + return fromHex("00112233445566778899aabbccddeeff") +end function + +/// Exercises page-zero allocation, all table open modes and semantic/CRC +/// corruption rejection without accepting or converting legacy table files. +/// @param args Destination path for isolated test fixtures. +function main(args) + if len(args) != 1 then print "MiniSQL storage-v2 table headers: FAIL (missing path)"; return 1 end if + path = args[0] + legacyPath = path + ".legacy" + cleanup(path) + cleanup(legacyPath) + heap_file.invalidatePageDirectory(path) + state = testkit.create() + + heap = heap_file.create(path, 4096, 77, databaseId()) + testkit.equal(state, heap.pagedFile.pageCount, 1, "empty table already owns page zero") + testkit.equal(state, file_api.size(heap.pagedFile.file), 12288, "empty table has two superblocks and one table header") + testkit.equal(state, heap_file.count(heap), 0, "header-only table scans as empty") + original = paged_file.readPage(heap.pagedFile, 0) + common = page.verify(original) + testkit.equal(state, common.pageType, page.TYPE_TABLE_META, "page zero is table metadata") + testkit.equal(state, common.freeStart, 128, "table-specific header occupies first 128 page bytes") + testkit.equal(state, hex(slice(original, 64, 8)), "4d53544202008000", "magic version and header length golden bytes") + testkit.equal(state, hex(slice(original, 72, 16)), hex(databaseId()), "database identity golden bytes") + testkit.equal(state, endian.readU32LE(original, 88), 77, "table identity is persisted") + testkit.equal(state, endian.readU32LE(original, 96), 4096, "page size is persisted") + testkit.equal(state, endian.readU16LE(original, 100), 1, "CRC32C algorithm is persisted") + testkit.equal(state, endian.readU16LE(original, 102), 2, "physical row format is v2") + testkit.equal(state, endian.readU32LE(original, 104), 1, "initial creation generation is persisted") + testkit.equal(state, endian.readU32LE(original, 112), 1, "first data page is one") + + identifier = heap_file.insert(heap, bytes("first data row")) + testkit.equal(state, identifier.pageNumber, 1, "first inserted row uses page one") + testkit.equal(state, heap.pagedFile.pageCount, 2, "heap allocation preserves reserved page") + heapPages = heap_file.heapPageNumbers(heap.pagedFile) + testkit.equal(state, len(heapPages), 1, "heap directory only includes data pages") + testkit.equal(state, heapPages[0], 1, "heap directory excludes table header") + testkit.equal(state, hex(paged_file.readPage(heap.pagedFile, 0)), hex(original), "data allocation leaves immutable header unchanged") + testkit.errorCode(state, try(heap_file.rowId(0, 0, 1)), heap_file.INVALID_ARGUMENT, "page zero cannot be a row identifier") + + corrupt = bytes(original) + corrupt[80] = corrupt[80] ^ 1 + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.CORRUPT_DATA, "damaged table header CRC rejected") + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.CORRUPT_DATA, "foreign database rejected even with valid CRC") + corrupt = bytes(original) + endian.writeU64LE(corrupt, 88, endian.uint64FromInt(78)) + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.CORRUPT_DATA, "foreign table id rejected") + corrupt = bytes(original) + endian.writeU32LE(corrupt, 96, 8192) + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.CORRUPT_DATA, "page-size identity mismatch rejected") + corrupt = bytes(original) + endian.writeU16LE(corrupt, 68, 1) + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.UNSUPPORTED_FORMAT, "legacy table-format version rejected") + corrupt = bytes(original) + endian.writeU16LE(corrupt, 100, 0) + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.UNSUPPORTED_FORMAT, "unknown checksum algorithm rejected") + corrupt = bytes(original) + endian.writeU64LE(corrupt, 104, endian.uint64FromInt(0)) + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.CORRUPT_DATA, "zero creation generation rejected") + corrupt = bytes(original) + corrupt[128] = 1 + page.reseal(corrupt) + testkit.errorCode(state, try(table_header.validatePage(heap.pagedFile, corrupt)), table_header.UNSUPPORTED_FORMAT, "nonzero reserved tail rejected") + heap_file.close(heap) + + readOnly = table_header.openReadOnly(path) + testkit.record(state, table_header.validate(readOnly), "shared read-only open validates table header") + paged_file.close(readOnly) + managed = table_header.openReadOnlyManaged(path) + testkit.record(state, table_header.validate(managed), "managed read-only open validates table header") + paged_file.close(managed) + reopened = heap_file.open(path) + testkit.equal(state, hex(heap_file.read(reopened, identifier)), hex(bytes("first data row")), "data survives header-validating reopen") + heap_file.close(reopened) + + // Resealed semantic corruption must fail every open mode and release its + // handle, so the next check can reacquire the same path without lock leaks. + raw = paged_file.open(path) + corrupt = bytes(original) + endian.writeU16LE(corrupt, 102, 1) + page.reseal(corrupt) + paged_file.writePage(raw, 0, corrupt) + paged_file.flush(raw) + paged_file.close(raw) + testkit.errorCode(state, try(table_header.open(path)), table_header.UNSUPPORTED_FORMAT, "writable open rejects legacy row version") + testkit.errorCode(state, try(table_header.openReadOnly(path)), table_header.UNSUPPORTED_FORMAT, "read-only open rejects legacy row version") + testkit.errorCode(state, try(table_header.openReadOnlyManaged(path)), table_header.UNSUPPORTED_FORMAT, "managed open rejects legacy row version") + testkit.errorCode(state, try(heap_file.open(path)), table_header.UNSUPPORTED_FORMAT, "heap open rejects legacy row version") + + raw = paged_file.create(legacyPath, 4096, superblock.FILE_TYPE_TABLE, 88, databaseId()) + paged_file.close(raw) + testkit.errorCode(state, try(table_header.open(legacyPath)), table_header.UNSUPPORTED_FORMAT, "empty legacy table without header rejected") + raw = paged_file.open(legacyPath) + paged_file.allocatePage(raw, page.TYPE_HEAP) + paged_file.close(raw) + testkit.errorCode(state, try(table_header.openReadOnly(legacyPath)), table_header.UNSUPPORTED_FORMAT, "legacy heap page zero rejected") + + heap_file.invalidatePageDirectory(path) + cleanup(path) + cleanup(legacyPath) + return testkit.finish(state, "MiniSQL storage-v2 table headers: SUCCESS", "MiniSQL storage-v2 table headers: FAIL") +end function diff --git a/test.ps1 b/test.ps1 index 35a900c..543d949 100644 --- a/test.ps1 +++ b/test.ps1 @@ -18,6 +18,8 @@ Python executable used to run the acceptance orchestrator. Selects the existing complete Windows suite or the portable Linux x64 suite. .PARAMETER StaticOnly Runs repository and source-contract checks without compiling native targets. +.PARAMETER StorageV2 +Runs the focused storage-v2 binary-layout and compatibility regression gate. .PARAMETER KeepArtifacts Preserves intermediate acceptance files for diagnosis. .PARAMETER VerboseOutput @@ -29,6 +31,7 @@ param( [ValidateSet("windows-x64", "linux-x64")] [string]$Target = "windows-x64", [switch]$StaticOnly, + [switch]$StorageV2, [switch]$KeepArtifacts, [switch]$VerboseOutput ) @@ -36,6 +39,15 @@ param( $ErrorActionPreference = "Stop" $Root = Split-Path -Parent $MyInvocation.MyCommand.Path +if ($StorageV2 -and -not $StaticOnly) { + $StorageArguments = @((Join-Path $Root "tests/run_storage_v2.py"), "--target", $Target) + if (-not [string]::IsNullOrWhiteSpace($Compiler)) { + $StorageArguments += @("--compiler", $Compiler) + } + & $Python @StorageArguments + exit $LASTEXITCODE +} + if ($Target -eq "linux-x64" -and -not $StaticOnly) { if ([string]::IsNullOrWhiteSpace($Compiler)) { $Compiler = Join-Path $Root "..\MiniLangCompilerPy\mlc_win64.py" diff --git a/tests/baseline_m0_m10.py b/tests/baseline_m0_m10.py index 6f75d8a..0d98a84 100644 --- a/tests/baseline_m0_m10.py +++ b/tests/baseline_m0_m10.py @@ -372,7 +372,7 @@ def validate_repository(manifest: dict[str, Any]) -> None: "milestone": "M10", "revision": REVISION, "version": VERSION, - "moduleCount": 84, + "moduleCount": 87, "acceptancePhaseCount": 30, "userFacingTestRunner": "test.ps1", } @@ -432,8 +432,8 @@ def validate_repository(manifest: dict[str, Any]) -> None: catalog_doc = load_json(ROOT / "docs" / "module-catalog.json") modules = catalog_doc.get("modules") if isinstance(catalog_doc, dict) else None - if not isinstance(modules, list) or len(modules) != 84: - raise AcceptanceFailure("Module catalog must contain exactly 84 source modules") + if not isinstance(modules, list) or len(modules) != 87: + raise AcceptanceFailure("Module catalog must contain exactly 87 source modules") if catalog_doc.get("version") not in (1, "1"): raise AcceptanceFailure("Unsupported module catalog version") diff --git a/tests/manifest.json b/tests/manifest.json index 0740513..e9721e6 100644 --- a/tests/manifest.json +++ b/tests/manifest.json @@ -4,7 +4,7 @@ "milestone": "M50", "revision": "M48-M50R3", "version": "1.1.1", - "moduleCount": 84, + "moduleCount": 87, "acceptancePhaseCount": 106, "userFacingTestRunner": "test.ps1", "entryPoints": [ @@ -191,7 +191,6 @@ "NOTICE.md", "README.md", "SECURITY.md", - "minidoc.toml", "build.ps1", "clean.ps1", "clients/jdbc/README.md", @@ -223,6 +222,7 @@ "docs/acceptance/FINAL_STATUS.md", "docs/acceptance/MiniSQL-1.0.0-results.json", "docs/acceptance/README.md", + "docs/acceptance/STORAGE_V2_2026-11-24.md", "docs/adr/ADR-0001-one-page-size-per-database.md", "docs/adr/ADR-0002-wal-instead-of-full-transaction-copies.md", "docs/adr/ADR-0003-conservative-initial-concurrency.md", @@ -310,33 +310,41 @@ "docs/adr/ADR-0085-single-host-leases-and-native-write-fencing.md", "docs/adr/ADR-0086-envelope-tde-and-scram-authentication.md", "docs/formats/FORMAT_COMPATIBILITY.md", - "docs/formats/ha-fencing-records-v1.md", "docs/formats/README.md", "docs/formats/audit-log-v1.md", "docs/formats/backup-manifest-v1.md", "docs/formats/btree-v1.md", + "docs/formats/btree-v2.md", "docs/formats/catalog-bootstrap-v1.md", "docs/formats/catalog-v1.md", "docs/formats/checkpoint-v1.md", - "docs/formats/encryption-envelope-v1.md", "docs/formats/database-meta-v1.md", + "docs/formats/database-meta-v2.md", "docs/formats/ddl-journal-v1.md", + "docs/formats/encryption-envelope-v1.md", + "docs/formats/ha-fencing-records-v1.md", "docs/formats/heap-forwarding-v1.md", "docs/formats/index-file-v1.md", + "docs/formats/index-file-v2.md", "docs/formats/maintenance-journal-v1.md", "docs/formats/overflow-v1.md", + "docs/formats/overflow-v2.md", "docs/formats/page-v1.md", "docs/formats/paged-file-v1.md", "docs/formats/protected-envelope-v1.md", "docs/formats/row-v1.md", + "docs/formats/row-v2.md", "docs/formats/schema-extensions-v1.md", "docs/formats/schema-history-v1.md", "docs/formats/secure-transport-v1.md", "docs/formats/security-catalog-v1.md", "docs/formats/slotted-page-v1.md", + "docs/formats/slotted-page-v2.md", "docs/formats/sort-spill-v1.md", "docs/formats/statistics-v1.md", + "docs/formats/storage-v2.md", "docs/formats/table-file-v1.md", + "docs/formats/table-file-v2.md", "docs/formats/wal-archive-v1.md", "docs/formats/wal-durable-marker-v1.md", "docs/formats/wal-v1.md", @@ -476,6 +484,7 @@ "docs/spec/65-production-fault-injection.md", "docs/spec/66-automatic-ha-fencing.md", "docs/spec/README.md", + "minidoc.toml", "release.ps1", "src/apps/minisql/main.ml", "src/apps/minisql_admin/main.ml", @@ -493,11 +502,13 @@ "src/minisql/client/client.ml", "src/minisql/client/console.ml", "src/minisql/client/formatter.ml", - "src/minisql/common/crc32c.ml", "src/minisql/common/byte_ops.ml", + "src/minisql/common/crc32c.ml", "src/minisql/common/diagnostics.ml", "src/minisql/common/endian.ml", "src/minisql/common/errors.ml", + "src/minisql/common/float_codec.ml", + "src/minisql/common/format_version.ml", "src/minisql/common/limits.ml", "src/minisql/common/logger.ml", "src/minisql/common/uuid.ml", @@ -526,8 +537,8 @@ "src/minisql/platform/file_win32.ml", "src/minisql/platform/lock.ml", "src/minisql/platform/network.ml", - "src/minisql/platform/tls_policy.ml", "src/minisql/platform/tls_openssl.ml", + "src/minisql/platform/tls_policy.ml", "src/minisql/platform/tls_schannel.ml", "src/minisql/platform/win32_gui.ml", "src/minisql/protocol/codec.ml", @@ -558,6 +569,7 @@ "src/minisql/storage/row_codec.ml", "src/minisql/storage/slotted_page.ml", "src/minisql/storage/superblock.ml", + "src/minisql/storage/table_header.ml", "src/minisql/tools/backup.ml", "src/minisql/tools/check.ml", "src/minisql/tools/encryption.ml", @@ -670,6 +682,11 @@ "src/tests/m8_config.ml", "src/tests/m9_heap_file.ml", "src/tests/m9_row_codec.ml", + "src/tests/storage_v2_indexes.ml", + "src/tests/storage_v2_metadata.ml", + "src/tests/storage_v2_overflow.ml", + "src/tests/storage_v2_rows.ml", + "src/tests/storage_v2_table.ml", "src/tests/support/testkit.ml", "test.ps1", "tests/README.md", @@ -696,17 +713,17 @@ "tests/performance/PERFORMANCE_BASELINE_2026-08-23.md", "tests/performance/README.md", "tests/performance/TDE_SECURITY_2026-09-02.md", - "tests/performance/tde_overhead.ml", "tests/performance/WINDOWS_LINUX_COMPARISON_2026-08-26.md", "tests/performance/capacity_regression.py", "tests/performance/compiler_concepts.py", "tests/performance/compiler_primitives.ml", "tests/performance/concurrent_indexed_reads.py", - "tests/performance/native_concurrent_indexed_reads.ml", - "tests/performance/profile_concurrent_reads.ps1", "tests/performance/m49_baseline.json", + "tests/performance/native_concurrent_indexed_reads.ml", "tests/performance/network_baseline.py", "tests/performance/platform_compare.py", + "tests/performance/profile_concurrent_reads.ps1", + "tests/performance/tde_overhead.ml", "tests/recovery/README.md", "tests/recovery/m49_crash_matrix.json", "tests/reference/README.md", @@ -724,9 +741,11 @@ "tests/reference/m48_m50_layout.json", "tests/reference/m4_layout.json", "tests/reference/m6_m10_layout.json", + "tests/reference/storage_v2_layout.json", "tests/run_all_tests.py", "tests/run_linux_tests.ps1", "tests/run_native_tls_tests.ps1", + "tests/run_storage_v2.py", "tests/soak/production_soak.py", "tests/unit/README.md", "tools/monitoring/minisql_exporter.py", diff --git a/tests/reference/m48_m50_layout.json b/tests/reference/m48_m50_layout.json index 277d4c8..343588a 100644 --- a/tests/reference/m48_m50_layout.json +++ b/tests/reference/m48_m50_layout.json @@ -10,7 +10,7 @@ "release": { "productVersion": "1.1.1", "milestone": "M50", - "databaseFormatVersion": 1, + "databaseFormatVersion": 2, "wireProtocolVersion": 1, "platform": "windows-x64" }, diff --git a/tests/reference/storage_v2_layout.json b/tests/reference/storage_v2_layout.json new file mode 100644 index 0000000..4f65990 --- /dev/null +++ b/tests/reference/storage_v2_layout.json @@ -0,0 +1,20 @@ +{ + "versions": {"database": 2, "table": 2, "index": 2, "row": 2, "overflow": 2, "wal": 1}, + "floating": [ + {"value": "0x0p+0", "littleEndian": "0000000000000000"}, + {"value": "-0x0p+0", "littleEndian": "0000000000000080"}, + {"value": "0x1p-1074", "littleEndian": "0100000000000000"}, + {"value": "0x1p-1022", "littleEndian": "0000000000001000"}, + {"value": "0x1.999999999999ap-4", "littleEndian": "9a9999999999b93f"}, + {"value": "0x1.fffffffffffffp+1023", "littleEndian": "ffffffffffffef7f"} + ], + "integerKeys": [ + {"value": -9223372036854775808, "hex": "4d534b02030000000000000080"}, + {"value": -1, "hex": "4d534b0203ffffffffffffffff"}, + {"value": 255, "hex": "4d534b0203ff00000000000000"}, + {"value": 256, "hex": "4d534b02030001000000000000"}, + {"value": 9223372036854775807, "hex": "4d534b0203ffffffffffffff7f"} + ], + "overflowPointer": "4d534f50020000007b00000000000000030000000000000004030201000000000807060500000000d4c3b2a1274af41d", + "row": "4d535257020001000300010018000000000000000000000004000000300008000a00000038000400010000003c00010001000000000000004e696c7301000000" +} diff --git a/tests/run_all_tests.py b/tests/run_all_tests.py index 2deb2f7..68adf3c 100644 --- a/tests/run_all_tests.py +++ b/tests/run_all_tests.py @@ -24,6 +24,7 @@ import os import re import socket +import struct import subprocess import sys import time @@ -748,7 +749,7 @@ def validate_repository(manifest: dict[str, Any]) -> None: "milestone": "M50", "revision": REVISION, "version": VERSION, - "moduleCount": 84, + "moduleCount": 87, "acceptancePhaseCount": PHASE_COUNT, "userFacingTestRunner": "test.ps1", } @@ -886,8 +887,8 @@ def is_generated_api_path(path: Path) -> bool: catalog_document = load_json(ROOT / "docs/module-catalog.json") modules = catalog_document.get("modules") - if not isinstance(modules, list) or len(modules) != 84: - raise AcceptanceFailure("Module catalog must contain exactly 84 source modules") + if not isinstance(modules, list) or len(modules) != 87: + raise AcceptanceFailure("Module catalog must contain exactly 87 source modules") catalog_paths: set[str] = set() for item in modules: relative = item.get("path") @@ -1021,7 +1022,7 @@ def validate_source_contracts() -> None: 'const MILESTONE = "M50"', 'const REVISION = "M48-M50R3"', "const WIRE_PROTOCOL_VERSION = 1", - "const DATABASE_FORMAT_VERSION = 1", + "const DATABASE_FORMAT_VERSION = format_version.DATABASE", ], "src/minisql/platform/network.ml": [ "extern function send(s as ptr, buffer as ptr, count as i32, flags as i32) from \"ws2_32.dll\" returns i32", @@ -1329,10 +1330,40 @@ def validate_platform_compare_cache_hygiene() -> None: base.clean_path(probe_root) +def validate_storage_v2_vectors() -> None: + """Checks independent storage-v2 goldens with Python's numeric codecs and CRC reference.""" + vectors = load_json(ROOT / "tests/reference/storage_v2_layout.json") + if vectors["versions"] != {"database": 2, "table": 2, "index": 2, "row": 2, "overflow": 2, "wal": 1}: + raise AcceptanceFailure("Storage-v2 version registry mismatch") + for item in vectors["floating"]: + if struct.pack(" None: """Validates independent binary, parser and security reference vectors.""" if PHASE_COUNT != 106: raise AcceptanceFailure("MiniSQL 1.1.1 phase count must remain 106") + validate_storage_v2_vectors() corpus_document = load_json(ROOT / "tests/fuzz/m49_sql_corpus.json") corpus = corpus_document.get("statements") if not isinstance(corpus, list) or len(corpus) < 32 or not all(isinstance(item, str) for item in corpus): @@ -1357,7 +1388,7 @@ def validate_reference_vectors() -> None: raise AcceptanceFailure("MiniSQL 1.1.1 acceptance reference mismatch") upgrade = load_json(ROOT / "docs/release/upgrade-matrix.json") features = load_json(ROOT / "docs/release/feature-matrix.json") - if upgrade.get("targetVersion") != VERSION or upgrade.get("databaseFormatVersion") != 1: + if upgrade.get("targetVersion") != VERSION or upgrade.get("databaseFormatVersion") != 2: raise AcceptanceFailure("M50 upgrade matrix version mismatch") if features.get("version") != VERSION or features.get("wireProtocolVersion") != 1: raise AcceptanceFailure("M50 feature matrix version mismatch") @@ -1853,6 +1884,18 @@ def package_results() -> Path: return archive +def run_row_and_storage_v2(compiler: Path, verbose: bool) -> None: + """Runs the established row scenario and the five new storage-format regressions.""" + base.run_m9_row(compiler, verbose) + result = base.run_command( + [sys.executable, str(ROOT / "tests/run_storage_v2.py"), "--compiler", str(compiler), + "--target", "windows-x64"], + log_name="storage-v2.run.log", verbose=verbose, timeout=3600.0, + ) + if result.returncode != 0 or "MiniSQL storage v2 tests: SUCCESS" not in result.stdout: + raise AcceptanceFailure("Storage-v2 binary-format regression gate failed") + + def parse_args() -> argparse.Namespace: """Parses and returns the acceptance runner command-line arguments.""" parser = argparse.ArgumentParser(description="Run the complete MiniSQL 1.1.1 M0-M50 test suite") @@ -1870,7 +1913,7 @@ def main() -> int: try: manifest = load_json(MANIFEST_PATH) static_actions = [ - ("repository manifest, one-launcher contract and 84-module catalog", lambda: validate_repository(manifest)), + ("repository manifest, one-launcher contract and 87-module catalog", lambda: validate_repository(manifest)), ("configuration, final M0-M50 evidence and complete 1.0 documentation", validate_config_and_docs), ("durable replication, hardening and release source contracts", validate_source_contracts), ("independent corpus, sidecar, compatibility and deterministic-release vectors", validate_reference_vectors), @@ -1902,7 +1945,7 @@ def main() -> int: ("M7 process termination before commit", lambda: base.run_m7_crash_uncommitted(compiler,args.verbose)), ("M8 strict configuration loader and defaults", lambda: base.run_m8_config(compiler,args.verbose)), ("M8 database directory, catalog and manager", lambda: base.run_m8_catalog(compiler,args.verbose)), - ("M9 row format and SQL NULL codec", lambda: base.run_m9_row(compiler,args.verbose)), + ("M9 row codec and storage-v2 byte-format regressions", lambda: run_row_and_storage_v2(compiler,args.verbose)), ("M9 slotted pages and heap-file workload", lambda: base.run_m9_heap(compiler,args.verbose)), ("M10 overflow chains, replacement and reclamation", lambda: base.run_m10_overflow(compiler,args.verbose)), ("M10 71-module implementation smoke", lambda: base.run_m10_modules(compiler,args.verbose)), diff --git a/tests/run_storage_v2.py b/tests/run_storage_v2.py new file mode 100644 index 0000000..48c5160 --- /dev/null +++ b/tests/run_storage_v2.py @@ -0,0 +1,143 @@ +# Copyright 2026 MiniLangProject contributors +# SPDX-License-Identifier: Apache-2.0 +# Licensed under the Apache License, Version 2.0; see the LICENSE file. + +"""Internal native storage-v2 gate, exposed through test.ps1 -StorageV2.""" + +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +CORE = { + "storage_v2_metadata": [], + "storage_v2_rows": [], + "storage_v2_table": ["{data}/table.tbl"], + "storage_v2_overflow": [], + "storage_v2_indexes": ["{data}"], +} +REGRESSIONS = { + "m8_config": ["{repo}/config/minisql.example.json", "{data}/invalid.json"], + "m8_catalog": ["{repo}/config/minisql.example.json", "{data}"], + "m9_row_codec": [], + "m9_heap_file": ["{data}/heap.tbl"], + "m10_overflow": ["{data}/overflow.tbl"], + "m11_btree": ["{data}/index.idx"], + "m6_wal": ["{data}/wal.log"], + "m6_transaction": ["{data}/wal.log"], + "m7_checkpoint": ["{data}/checkpoint.meta"], + "m7_recovery": ["{data}/data.tbl", "{data}/wal.log"], + "m15_sql_engine": ["{data}"], + "m23_index_integration": ["{data}"], + "m24_schema_evolution": ["{data}"], + "m25_maintenance": ["{data}"], + "m26_offline_migration": ["{data}"], + "m50_release_contract": ["{data}"], + "m79_security_at_rest": ["{data}"], +} + + +def execute(command: list[str], log: Path, timeout: int) -> subprocess.CompletedProcess[str]: + """Runs a bounded process and preserves its complete diagnostic output.""" + result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, + encoding="utf-8", errors="replace", timeout=timeout) + log.write_text(json.dumps(command) + "\n" + result.stdout + "\n" + result.stderr, + encoding="utf-8") + return result + + +def run_case(name: str, arguments: list[str], compiler: Path, target: str, + run_root: Path, compile_only: bool) -> dict[str, object]: + """Compiles a test and, for native gates, checks its exit status and success banner.""" + started = time.monotonic() + case_root = run_root / name + data = case_root / "data" + data.mkdir(parents=True) + source = ROOT / "src" / "tests" / (name + ".ml") + executable = case_root / (name + (".exe" if target == "windows-x64" else "")) + result: dict[str, object] = {"case": name, "status": "FAIL"} + try: + command = [sys.executable, str(compiler), str(source), str(executable), + "-I", str(ROOT / "src"), "-I", str(compiler.parent), "--target", target] + compiled = execute(command, case_root / "compile.log", 1200) + if compiled.returncode != 0 or not executable.is_file(): + raise RuntimeError("compilation failed; see compile.log") + expected_magic = b"MZ" if target == "windows-x64" else b"\x7fELF" + with executable.open("rb") as stream: + if stream.read(len(expected_magic)) != expected_magic: + raise RuntimeError("compiler produced an unexpected executable format") + if compile_only: + result["status"] = "COMPILE_PASS" + else: + executable.chmod(executable.stat().st_mode | 0o111) + command = [str(executable)] + [item.format(data=data, repo=ROOT) for item in arguments] + native = execute(command, case_root / "run.log", 600) + banners = re.findall(r'"(MiniSQL[^"\n]*: SUCCESS)"', source.read_text(encoding="utf-8")) + if native.returncode != 0 or not banners or banners[-1] not in native.stdout: + raise RuntimeError("native test failed or success banner missing; see run.log") + result["status"] = "PASS" + except (OSError, subprocess.TimeoutExpired, RuntimeError) as error: + result["error"] = str(error) + result["seconds"] = round(time.monotonic() - started, 3) + return result + + +def main() -> int: + """Runs the focused or selected regression cases and writes machine-readable evidence.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--compiler", default=os.environ.get("MINILANG_COMPILER")) + parser.add_argument("--target", choices=["windows-x64", "linux-x64"], + default="windows-x64" if os.name == "nt" else "linux-x64") + parser.add_argument("--compile-only", action="store_true") + parser.add_argument("--integration", action="store_true") + parser.add_argument("--case", action="append", choices=sorted(CORE | REGRESSIONS)) + parser.add_argument("--jobs", type=int, default=2) + args = parser.parse_args() + if args.jobs < 1 or args.jobs > 4: + parser.error("--jobs must be between 1 and 4") + native_target = "windows-x64" if os.name == "nt" else "linux-x64" + if args.target != native_target and not args.compile_only: + parser.error("cross-target execution is unsupported; use --compile-only") + compiler = Path(args.compiler) if args.compiler else ROOT.parent / "MiniLangCompilerPy" / "mlc_win64.py" + compiler = compiler.resolve() + if not compiler.is_file(): + parser.error("MiniLang compiler not found; pass --compiler") + inventory = CORE | REGRESSIONS + selected = args.case or list(inventory if args.integration else CORE) + selected = list(dict.fromkeys(selected)) + output_parent = ROOT / "build" / "storage-v2" / "gates" + output_parent.mkdir(parents=True, exist_ok=True) + run_root = Path(tempfile.mkdtemp(prefix=datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ-"), dir=output_parent)) + results = [] + print(f"Storage v2 {args.target}: {len(selected)} cases; logs: {run_root}", flush=True) + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + futures = [pool.submit(run_case, name, inventory[name], compiler, args.target, + run_root, args.compile_only) for name in selected] + for future in as_completed(futures): + result = future.result() + results.append(result) + print(f"{result['case']}: {result['status']} ({result['seconds']}s)", flush=True) + if "error" in result: + print(result["error"], flush=True) + passed = all(result["status"] in {"PASS", "COMPILE_PASS"} for result in results) + evidence = {"databaseFormatVersion": 2, "target": args.target, + "compileOnly": args.compile_only, "compiler": str(compiler), + "status": "PASS" if passed else "FAIL", "cases": sorted(results, key=lambda item: item["case"])} + (run_root / "results.json").write_text(json.dumps(evidence, indent=2) + "\n", encoding="utf-8") + mode = "compile gate" if args.compile_only else "tests" + print(f"MiniSQL storage v2 {mode}: {'SUCCESS' if passed else 'FAIL'}", flush=True) + return 0 if passed else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/release/build_release.py b/tools/release/build_release.py index 2a4c122..6ca5d8b 100644 --- a/tools/release/build_release.py +++ b/tools/release/build_release.py @@ -94,7 +94,7 @@ def manifest(files: dict[str, bytes]) -> dict[str, object]: "product": "MiniSQL", "version": VERSION, "milestone": "M50", - "databaseFormatVersion": 1, + "databaseFormatVersion": 2, "wireProtocolVersion": 1, "platform": "windows-x64", "nativeTransports": ["Windows Schannel TLS 1.3/X.509"],