diff --git a/AGENTS.md b/AGENTS.md index cff711b6..19f2494f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Embedded + networked database engine for .NET with AES-256-GCM encryption, a gRP package family spanning ADO.NET, EF Core, Dapper, linq2DB, YesSql, Sync, Analytics, VectorSearch, Graph, EventSourcing, CQRS and Projections. C#/.NET, `LangVersion=preview`. Deep documentation lives in `docs/` (start at `docs/INDEX.md`); the live performance mission is -`docs/performance/AUTONOMOUS_AGENT_BRIEF.md`. `master` is the `net11.0` / C# 15 preview line (2.2.0 — the +`docs/performance/AUTONOMOUS_AGENT_BRIEF.md`. `master` is the `net11.0` / C# 15 preview line (2.2.1 — the .NET 11 GA line; see `docs/net11/PROMOTION_TO_MAIN.md`). The net10.0 / C# 14 stable line is parked on `release/v2.0` for 2.0.x servicing and is built by `ci-net10.yml`. diff --git a/Directory.Packages.props b/Directory.Packages.props index 39538c0d..a1eb3a7c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -2,7 +2,7 @@ true true - 2.2.0 + 2.2.1 @@ -22,10 +22,12 @@ + + diff --git a/README.md b/README.md index 9cf06b3d..b7604b53 100644 --- a/README.md +++ b/README.md @@ -24,11 +24,25 @@ Use it when you need: - Fast embedded storage with **AES-256-GCM encryption** and ACID guarantees - A secure network database via **gRPC (HTTP/2 + HTTP/3)** - Built-in **vector search**, **advanced analytics**, and **GraphRAG/graph algorithms** -- A production-focused stack validated by **4,886 tests across all 17 test projects (0 failed, - 6 skipped, measured 2026-11-28)**, including the write-path regression gate and the reopen +- A production-focused stack validated by **4,968 tests across all 17 test projects (0 failed, + 1 skipped, measured 2026-11-30)**, including the write-path regression gate and the reopen round-trip matrix -> **Current release: v2.2.0 (2026-11-28) — the .NET 11 / C# 15 line, on `master`.** A minor release with +> **Current release: v2.2.1 (2026-11-30) — the .NET 11 / C# 15 line, on `master`.** The quality patch on top +> of 2.2.0: four new test suites over public surfaces that had none (`PageBasedAdapter`, +> `CorruptionDetector`, `SimdHelper`, single-file key moves), and **six defects they found, all fixed +> red→green** — storage-provider **read-your-writes** (`WriteBlockAsync` queues, `ReadBlockAsync` read the +> file anyway, saw zeros and then "self-healed" the registry to match, losing the block), +> `PageBasedAdapter` persistence on dispose, single-file **UPDATE statement atomicity** on all four paths, +> **RTRIM** and collation-aware key uniqueness (`NOCASE` keys canonicalise), `HorizontalSum` on 4–7-element +> spans, and `DeserializeBatchDouble`'s null flags. Also includes the closing owner-decision work (D1=A +> composite keys, D2=A `COLLATE`), 24 SonarCloud S3358 refactors, and the two central package-version +> entries that were missing (`Search`, `HybridSearch`). Validated by **4,968 tests / 0 failed / 1 skipped +> across all 17 test projects**, line coverage **49.00 %** (engine assembly 56.92 %) and the write-path gate +> **PASSED** (8/8 capability metrics `ok`). Full notes: +> [`docs/CHANGELOG.md`](docs/CHANGELOG.md) › `[2.2.1]`. + +> **Previous release — v2.2.0 (2026-11-28) — the .NET 11 / C# 15 line.** A minor release with > the .NET 11 dependency majors (EF Core / ASP.NET Core / Extensions **11.0.0**, Aspire.Hosting **17.0.0**, > MailKit/MimeKit **5.0.0**, Serilog **11.0.0**), **EF Core 11 compatibility** for the provider, and the > engine hardening that landed since 2.1.4 (composite keys, atomic UPDATE, CHECK/CASE, PageBased durability, @@ -37,7 +51,7 @@ Use it when you need: > `UPDATE … SET` / `INSERT … VALUES` is now evaluated as an expression, as SQLite evaluates it — a bare word > that names no column keeps the lenient literal reading, and an unquoted date in a `DATETIME` column stays a > date. Validated by **4,886 tests / 0 failed / 6 skipped across all 17 test projects**, including a -> **511-case differential matrix** for #525. Full notes: +> **511-case differential matrix** for #525. Notes: > [`docs/CHANGELOG.md`](docs/CHANGELOG.md) › `[2.2.0]`. > **Previous release — v2.1.4 (2026-11-13) — the .NET 11 / C# 15 line, on `master`.** The quoted-identifier @@ -113,17 +127,17 @@ Use it when you need: ## Requirements and the two release lines -| | **v2.2.0 — this line (`master`)** | **v2.0.0.3 — parked line (`release/v2.0`)** | +| | **v2.2.1 — this line (`master`)** | **v2.0.0.3 — parked line (`release/v2.0`)** | |---|---|---| | Target framework | `net11.0` only (every project under `src`) | `net10.0` | | Language | C# 15 (`LangVersion=preview`, always on) | C# 14 | | SDK | .NET 11 GA, pinned in `global.json` (`11.0.100`, `rollForward: latestPatch`) | .NET 10 (`10.0.x`) | | Pipeline | `.github/workflows/ci.yml` | `.github/workflows/ci-net10.yml` | -| Packages | `2.2.0` — the 28 packable projects under `src` | `2.0.0.3` | +| Packages | `2.2.1` — the 28 packable projects under `src` | `2.0.0.3` | | Status | current release, receives new work | servicing only | - **Pick one line per solution.** The package references are line-specific: a `net10.0` project uses the - `2.0.0.x` packages, a `net11.0` project the `2.2.0` ones. Do not mix them in one solution. + `2.0.0.x` packages, a `net11.0` project the `2.2.x` ones. Do not mix them in one solution. - **The .NET 11 SDK is required to build** — the `global.json` pin is deliberate and `dotnet test` is not this repository's runner (Microsoft.Testing.Platform is; run the built test executable, or see [`docs/INDEX.md`](docs/INDEX.md)). @@ -155,7 +169,23 @@ Use it when you need: --- -## What's new in v2.2.0 (current release) +## What's new in v2.2.1 (current release) + +**Tests first, then the defects they found.** The release adds four suites over surfaces that had no test at +all — `PageBasedAdapter` (the page engine's window onto a `.scdb` file), `CorruptionDetector`, `SimdHelper` +(every public SIMD primitive, both the vector path and the scalar tail) and the single-file key-move matrix +— and fixes what they exposed: (1) the storage provider's **read-your-writes** was broken (`WriteBlockAsync` +only queues; `ReadBlockAsync` read the file anyway, reported a checksum mismatch and then repaired the +registry *to the zeros*, so the block was lost) and the pending-writes flag could hide a write queued during +a flush (a durability gap on close); (2) `PageBasedAdapter.Dispose` never flushed the shared provider, so a +reopen lost every page; (3) a rejected single-file `UPDATE` left the row altered on all four paths — one +shared applier now validates the prospective key set before the first write; (4) `COLLATE RTRIM` was parsed +but compared ordinally, and key uniqueness always compared ordinal text (`NOCASE` keys accepted `'aa'` and +`'AA'`); (5) `SimdHelper.HorizontalSum` summed 8 instead of 15 on a five-element span; (6) +`DeserializeBatchDouble` ignored its null flags. Coverage moved **47.89 % → 49.00 %** (engine assembly +56.92 %). Full notes: [`docs/CHANGELOG.md`](docs/CHANGELOG.md) › `[2.2.1]`. + +## What's new in v2.2.0 **Dependency majors, EF Core 11, and SQLite expression parity for `INSERT`/`UPDATE`.** Every Microsoft.* package moves to **11.0.0** (EF Core, ASP.NET Core, Extensions), **Aspire.Hosting to 17.0.0**, @@ -377,7 +407,7 @@ Headline changes, grouped by area. Everything below is in the shipped `2.1.0` pa ### 1) Embedded mode ```bash -dotnet add package SharpCoreDB --version 2.2.0 +dotnet add package SharpCoreDB --version 2.2.1 ``` ```csharp @@ -414,8 +444,8 @@ gRPC endpoint: `https://localhost:5001` Install client/server packages: ```bash -dotnet add package SharpCoreDB.Server.Core --version 2.2.0 -dotnet add package SharpCoreDB.Client --version 2.2.0 +dotnet add package SharpCoreDB.Server.Core --version 2.2.1 +dotnet add package SharpCoreDB.Client --version 2.2.1 ``` > The server host is a standalone executable (`src/SharpCoreDB.Server`), distributed as the @@ -446,50 +476,50 @@ dotnet add package SharpCoreDB.Client --version 2.2.0 ## Available NuGet packages -### v2.2.0 — current release (`master`, net11.0 / C# 15 preview) +### v2.2.1 — current release (`master`, net11.0 / C# 15 preview) ```bash # Core -dotnet add package SharpCoreDB --version 2.2.0 +dotnet add package SharpCoreDB --version 2.2.1 # Server/client -dotnet add package SharpCoreDB.Server.Core --version 2.2.0 -dotnet add package SharpCoreDB.Server.Protocol --version 2.2.0 -dotnet add package SharpCoreDB.Client --version 2.2.0 -dotnet add package SharpCoreDB.Client.Protocol --version 2.2.0 -dotnet add package SharpCoreDB.Data.Provider --version 2.2.0 +dotnet add package SharpCoreDB.Server.Core --version 2.2.1 +dotnet add package SharpCoreDB.Server.Protocol --version 2.2.1 +dotnet add package SharpCoreDB.Client --version 2.2.1 +dotnet add package SharpCoreDB.Client.Protocol --version 2.2.1 +dotnet add package SharpCoreDB.Data.Provider --version 2.2.1 # Engines and extensions -dotnet add package SharpCoreDB.Analytics --version 2.2.0 -dotnet add package SharpCoreDB.VectorSearch --version 2.2.0 -dotnet add package SharpCoreDB.Search --version 2.2.0 -dotnet add package SharpCoreDB.HybridSearch --version 2.2.0 -dotnet add package SharpCoreDB.Graph --version 2.2.0 -dotnet add package SharpCoreDB.Graph.Advanced --version 2.2.0 -dotnet add package SharpCoreDB.Distributed --version 2.2.0 -dotnet add package SharpCoreDB.Provider.Sync --version 2.2.0 -dotnet add package SharpCoreDB.Provider.YesSql --version 2.2.0 -dotnet add package SharpCoreDB.EntityFrameworkCore --version 2.2.0 -dotnet add package SharpCoreDB.Extensions --version 2.2.0 -dotnet add package SharpCoreDB.Identity --version 2.2.0 -dotnet add package SharpCoreDB.Serilog.Sinks --version 2.2.0 +dotnet add package SharpCoreDB.Analytics --version 2.2.1 +dotnet add package SharpCoreDB.VectorSearch --version 2.2.1 +dotnet add package SharpCoreDB.Search --version 2.2.1 +dotnet add package SharpCoreDB.HybridSearch --version 2.2.1 +dotnet add package SharpCoreDB.Graph --version 2.2.1 +dotnet add package SharpCoreDB.Graph.Advanced --version 2.2.1 +dotnet add package SharpCoreDB.Distributed --version 2.2.1 +dotnet add package SharpCoreDB.Provider.Sync --version 2.2.1 +dotnet add package SharpCoreDB.Provider.YesSql --version 2.2.1 +dotnet add package SharpCoreDB.EntityFrameworkCore --version 2.2.1 +dotnet add package SharpCoreDB.Extensions --version 2.2.1 +dotnet add package SharpCoreDB.Identity --version 2.2.1 +dotnet add package SharpCoreDB.Serilog.Sinks --version 2.2.1 # Optional architecture packages -dotnet add package SharpCoreDB.EventSourcing --version 2.2.0 -dotnet add package SharpCoreDB.Projections --version 2.2.0 -dotnet add package SharpCoreDB.CQRS --version 2.2.0 +dotnet add package SharpCoreDB.EventSourcing --version 2.2.1 +dotnet add package SharpCoreDB.Projections --version 2.2.1 +dotnet add package SharpCoreDB.CQRS --version 2.2.1 # Optional functional adapters -dotnet add package SharpCoreDB.Functional --version 2.2.0 -dotnet add package SharpCoreDB.Functional.Dapper --version 2.2.0 -dotnet add package SharpCoreDB.Functional.EntityFrameworkCore --version 2.2.0 -dotnet add package SharpCoreDB.Functional.Linq2DB --version 2.2.0 +dotnet add package SharpCoreDB.Functional --version 2.2.1 +dotnet add package SharpCoreDB.Functional.Dapper --version 2.2.1 +dotnet add package SharpCoreDB.Functional.EntityFrameworkCore --version 2.2.1 +dotnet add package SharpCoreDB.Functional.Linq2DB --version 2.2.1 # Hosting and tooling -dotnet add package SharpCoreDB.Aspire.Hosting --version 2.2.0 +dotnet add package SharpCoreDB.Aspire.Hosting --version 2.2.1 ``` -> The 28 commands above are the complete packable set of this line. **`2.2.0` is a stable release**, so +> The 28 commands above are the complete packable set of this line. **`2.2.1` is a stable release**, so > NuGet selects it by default for a `net11.0` project; a `net10.0` project resolves to the `2.0.0.3` line > instead. Pin the version explicitly (as above) when you want to be certain, and tick *Include > prerelease* only if you are deliberately testing an RC build. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 23efc592..8fe3581e 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,7 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -> New entries start here, above `[2.2.0]`. +> New entries start here, above `[2.2.1]`. + +## [2.2.1] - 2026-11-30 + +> **`2.2.1`** is the quality release on the net11.0 / C# 15 line: four new test suites over previously +> untested public surfaces, six product defects found by them and fixed red→green (storage-provider +> read-your-writes and its durability flag, `PageBasedAdapter` persistence, single-file UPDATE statement +> atomicity, RTRIM/collation-aware key uniqueness, `HorizontalSum`, `DeserializeBatchDouble`), the plan-009 +> owner decisions (D1=A composite keys, D2=A `COLLATE`), prepared-batch DELETE parity, parallel AES-GCM for +> the batch crypto path, `SingleFileDatabase : IMetadataProvider`, and 24 SonarCloud S3358 sites refactored. +> Validated across all 17 test projects: **4,968 tests / 0 failed / 1 skipped**; line coverage **49.00 %** +> (engine assembly 56.92 %); the mutation baseline re-measured (26.40 % on the `SqlFunctions` slice); the +> write-path gate **PASSED** (8/8 capability metrics `ok`, tolerance 1.50×). + +### Added + +- **Four test suites for public surfaces that had no test at all, and the coverage they buy.** `PageBasedAdapter` (the page-based engine's window onto a single-file database: insert/read/update/delete/batch/metrics/transactions/reopen — 0 % covered) and `CorruptionDetector` (all four validation modes, report shape, disposal — 0 % covered) are now pinned by `PageBasedAdapterTests` and `CorruptionDetectorTests`; `SimdHelperTests` drives every public SIMD primitive on a span shorter than a vector and on one longer than it (both branches plus the scalar tail), including the four batch deserializers' wire layouts; `SingleFileKeyMoveTests` pins owner decision D1=A on every UPDATE and DELETE path. Writing them found six defects, all fixed below. Line coverage of the shipped assemblies moves **47,89 % → 49,00 %** (`SharpCoreDB` **55,32 % → 56,92 %** — 30 766 of 62 791 lines covered, measured by `tools/measure-coverage.ps1` on the four CI suites); the per-assembly numbers and the tiered targets are in `docs/quality/SONAR_AND_COVERAGE.md`. +- **`COLLATE RTRIM` is honoured end to end, and key uniqueness follows the declared collation.** The DDL parsed and persisted `RTRIM` but the evaluator compared ordinally (a trailing-blank difference counted) and the key-tuple set always compared ordinal text, so a `NOCASE` key accepted `'aa'` and `'AA'` as distinct rows while `WHERE k = 'AA'` matched both. RTRIM now trims before comparing in WHERE, BETWEEN, ORDER BY and in the key set; `NOCASE` and `UNICODE` keys canonicalise with `ToUpperInvariant` / culture-upper; every key-column canonicalisation is one helper (`CanonicalKeyPart`). Pinned by `SingleFileCollationTests` (RTRIM WHERE survives reopen, RTRIM ORDER BY treats `'a '` and `'a'` equal) and `SingleFileKeyMoveTests` (`NoCaseKey_*`, `RTrimKey_*` — both red before). +- **`SingleFileDatabase` now implements `IMetadataProvider`, so the schema probe answers the same in both storage modes.** `db is IMetadataProvider` was true for a directory database and false for a `.scdb` file, even though the single-file database already answered `GetTables()` / `GetColumns()` (they come from `IDatabase`). The interface is now declared on the class (implicit implementation, the same shape `Database` uses), so metadata discovery works consistently. Pinned by `SingleFileMetadataParityTests`, which asserts the probe and column-for-column metadata equality across the two modes (red before the declaration). Plan: `specs/008-single-file-metadata-parity/`. +- **`ExecuteBatchPrepared` now accepts the canonical DELETE template, not only UPDATE.** `DELETE FROM WHERE = @param` is classified **once** for the whole batch (through the same `TryScanCanonicalDml` the raw SQL batch classifier uses) and each parameter set binds its already-typed key into `DeleteBatchStructured` — the same primary-key / hash-index / contiguous resolvers the SQL batch DELETE path runs — instead of re-scanning and re-parsing a raw statement per row. The UPDATE template and the method signature are unchanged, so no caller or interface breaks. A DELETE template whose WHERE value is a literal (not an `@parameter`), a non-canonical statement, or a parameter set missing the WHERE key throws `ArgumentException`; a null key is rejected by `DeleteBatchStructured`. Pinned by `ExecuteBatchPreparedTests` — `Delete_RemovesEveryParameterSet` (PK shape) and `Delete_OnIndexedColumn_ResolvesThroughHashIndex` (the benchmark's indexed-column shape) both failed before the change (**2 failures**) and pass after, plus `DeleteNonParameterTemplate_Throws` for the rejection. No storage, format, encryption or durability change: the branch runs inside the same `RunInBatchTransaction` every batch path uses. + +### Changed + +- **At-rest batch UPDATE/DELETE now encrypt and decrypt their records across cores.** The contiguous fixed-width span is the engine's hot batch path, and on an encrypted table it paid one sequential AEAD open per record (row-locate) plus one sequential seal per overwritten record. Both loops are now `Parallel.For` above 64 records (below it the per-batch overhead exceeds the work), which is safe because `AesGcmEncryption` keeps one cipher per thread and derives every nonce from an `Interlocked` counter. The storage buffer's base-length cache is resolved inside its lock — it was outside, a latent race once the batch path calls it from parallel workers. Measured on the `--pk` arm, same-session A/B, at-rest tax vs the same run's plaintext arm: UPDATE **1,945× → 1,585× (−19 %)**, DELETE directionally better too; the diagnostics (`BulkContiguousParallelDecryptBatches` / `BulkContiguousParallelEncryptBatches`) prove the branch engaged, and the records are byte-identical (full-scan after reopen). No storage format, encryption-strength or durability change. Plan: `specs/006-parallel-record-encryption/`. + +### Fixed + +- **Reading a block right after writing it returned zeros — and the checksum "self-heal" then overwrote the registry entry to match.** `SingleFileStorageProvider.WriteBlockAsync` only *queues* the bytes for the write-behind worker, and `ReadBlockAsync` read the file without draining the queue: a read issued in between saw the zero fill of an unwritten region, reported a checksum mismatch and repaired the *registry* checksum to the zeros, so the block was lost even to later reads. `ReadBlockAsync` now flushes pending writes before taking the I/O gate, and the pending-writes flag is cleared only when the queue is empty (a write enqueued during a flush used to be hidden from `HasPendingChanges`, which let `FlushAsync` early-return and leave it queued — a durability gap on close). Found by the first `PageBasedAdapter` test ever written (every insert failed with `Page full`); `PageBasedAdapterTests.Insert_ThenRead_RoundTripsTheRecord` and `Reopen_SeesThePersistedTableAndItsRecords` pin both halves. +- **`PageBasedAdapter.Dispose` never flushed the provider, so a reopen of the same file lost every page written through the adapter.** The adapter deliberately does not dispose the shared provider, but nothing pushed its still-queued page blocks and table metadata to the file; `Dispose` now calls `FlushAsync` (drains the queue, flushes the registry, fsyncs). Second half of the `Reopen_…` test above. +- **A rejected single-file `UPDATE` left the row altered.** All four UPDATE paths applied the new values and only then checked whether a moved primary key landed on another row, so the statement threw with the bad value already in the row cache (`UPDATE t SET id = 2 WHERE id = 1` left two rows with id 2). The check now runs on the prospective row **before** the first write, for every matched row — including two matched rows moving onto the same key — through one shared applier (`ApplyMatchedUpdates`). `UpdateByPrimaryKey` had no uniqueness check at all and now shares the same applier; `DELETE FROM t` without a WHERE clause clears the key set (it used to leave every key claimed, so re-inserting any of them failed). Pinned by `SingleFileKeyMoveTests` — 9 cases red before the fix. +- **`SimdHelper.HorizontalSum` answered wrong for spans of 4–7 elements.** The 128-bit path widened only the low two int32s of each four-element lane and skipped the upper two, so `[1,2,3,4,5]` summed to 8 instead of 15; the upper half is now widened and accumulated, with a scalar fallback when SSE4.1 is absent. Pinned by `SimdHelperTests.HorizontalSum_ScalarAndVectorPaths_SumTheSpan` (red before). +- **`SimdHelper.DeserializeBatchDouble` ignored its null flags.** The vector path stored the four doubles as-is ("assumes no nulls for performance"), so a null slot returned whatever bytes sat behind its flag; the flag block is now honoured (a zero flag writes `0.0`). Pinned by `SimdHelperTests.DeserializeBatchDouble_ReadsTheFlagBlockThenTheValues`, which reserves `9.0` behind a null flag (red before). +- **Two single-file databases whose tables shared a name but not a shape corrupted each other's batch INSERTs.** The single-file batch path kept a **static** prepared-INSERT cache keyed by the table *name* only, so once one database's `docs (id, body)` shape filled it, a valid `INSERT INTO docs (name, age)` on another database was mapped through that foreign column list and failed with `Column 'name' cannot be NULL` (or silently misplaced values). The key now carries the table's column signature (name + ordered columns + their types), and the cache is bounded (256 shapes). Pinned by `SingleFileBatchSchemaIsolationTests`, which fails with exactly that message when the name-only key is restored. Found by the wider suite: two single-file tests using `docs` with different columns ran in parallel. +- **Two stale documentation claims told callers that single-file Zstandard compression does not work.** `BlockCompressionMode.Zstd` said "on this runtime, using this mode will throw NotSupportedException" (it has worked since the .NET 11 in-box `System.IO.Compression.ZstandardStream` landed), and `BlockFlags.Compressed` said "reserved, always 0 for .scdb" (it is set on every compressed block). Both corrected, and the missing end-to-end proof added: `SingleFileCompressionTests` writes a Zstd-compressed `.scdb`, round-trips 200 rows after reopen, updates a row, and asserts that opening the file with the wrong mode throws the actionable `BlockCompression = Zstd` message; an encrypted variant pins the compress-then-encrypt ordering. The file header already records the mode, so a mismatch fails fast instead of returning garbled rows. +- **Single-file storage now honours a column's declared `COLLATE`.** `CREATE TABLE t (name TEXT COLLATE NOCASE)` behaved as BINARY on `.scdb` storage: the DDL parser never read the clause, the column entry had nowhere to keep it, and the evaluator/ordering had no collation support. The collation is now parsed, persisted in free bits 8–11 of the column entry's flags (a file written before decodes to BINARY — its behaviour), reloaded on reopen, honoured by the WHERE evaluator (`=`, ranges, BETWEEN; the ordinal fast path is bypassed for such a column) and by ORDER BY. Directory storage already honoured it. Plan: `specs/009-owner-decisions/` D2. +- **Single-file storage enforces PRIMARY KEY uniqueness for tables it creates, and models composite keys.** A duplicate insert (or an UPDATE moving a key onto an existing row) went through on `.scdb` storage, and `PRIMARY KEY (a, b)` was rejected as unsupported. Every key column is now parsed and persisted, a free flag bit marks the file as key-modelled, and the key tuple's uniqueness is enforced on INSERT, multi-row INSERT and every UPDATE path. Files written before the marker stay unenforced — their key columns were never recorded, so enforcing there could reject legitimate rows. `PrimaryKeyIndex` (the storage key) is still the last key column. Plan: `specs/009-owner-decisions/` D1. +- **A too-large number in a batch INSERT was stored as 0, and the `UseSqliteIntegerAffinity` advice did not work on single-file storage.** The batch literal path (`PreparedInsertStatement.ParseValueFast`) silently coerced an out-of-range `INTEGER`/`BIGINT` to 0 — a value the caller never wrote — while the single-statement path threw an actionable message; the batch path now throws the same message and keeps the lenient 0 only for non-numeric text. Separately, the single-file DDL hardcoded the integer-affinity opt-in off, so the message's advice ("set `DatabaseConfig.UseSqliteIntegerAffinity = true`") had no effect there; it now reads the config. `IntegerAffinityTests` (3 cases). Plan: `specs/009-owner-decisions/` D3. ## [2.2.0] - 2026-11-28 diff --git a/docs/INDEX.md b/docs/INDEX.md index 615a0147..b76be03d 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -1,6 +1,6 @@ # SharpCoreDB Documentation Index -**Status:** Active documentation set (`2.1.0` — net11.0 / C# 15 preview on `master`; the v2.0 net10.0 stable line is parked on `release/v2.0`) +**Status:** Active documentation set (`2.2.1` — net11.0 / C# 15 preview on `master`; the v2.0 net10.0 stable line is parked on `release/v2.0`) ## 0. Manual (start here) @@ -203,7 +203,7 @@ guide explaining when SharpCoreDB is fastest. - `../.github/CODING_STANDARDS.md` - `../.github/SIMD_STANDARDS.md` - `quality/SONAR_AND_COVERAGE.md` — SonarCloud gate and coverage state -- `quality/MUTATION_TESTING.md` — Stryker.NET setup, calibrated baseline, the blocked engine-project scope +- `quality/MUTATION_TESTING.md` — Stryker.NET setup, calibrated baselines per slice, and the engine-project scope (runnable since 2026-11-13 with a `test-case-filter`) ## Documentation Governance diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index fc07a3ad..701bde64 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -1,12 +1,28 @@ # SharpCoreDB Project Status -**Version:** 2.2.0 (`master`, net11.0 / C# 15 preview) · 2.0.0.3 (net10.0 / C# 14 stable, parked on `release/v2.0`) -**Status:** ✅ v2.2.0 released on the main branch · ✅ v2.0 stable line parked on `release/v2.0` · ✅ Performance-first line -**Last Updated:** November 28, 2026 +**Version:** 2.2.1 (`master`, net11.0 / C# 15 preview) · 2.0.0.3 (net10.0 / C# 14 stable, parked on `release/v2.0`) +**Status:** ✅ v2.2.1 released on the main branch · ✅ v2.0 stable line parked on `release/v2.0` · ✅ Performance-first line +**Last Updated:** November 30, 2026 ## Current Status -The **current release is `2.2.0` (2026-11-28)** — a minor release: the .NET 11 dependency majors (EF Core / +The **current release is `2.2.1` (2026-11-30)** — the quality patch on the net11.0 / C# 15 line. It carries +the plan-009 owner decisions (D1=A composite keys enforced, D2=A `COLLATE` persisted, D3=B batch INT overflow +throws, D4=C in-box Zstandard confirmed), prepared-batch DELETE parity, parallel AES-GCM for the batch crypto +path (−19% at-rest UPDATE tax), `SingleFileDatabase : IMetadataProvider`, the AOT re-verification, and the +2026-11-30 test pass: four new suites over previously untested surfaces (`PageBasedAdapter`, +`CorruptionDetector`, `SimdHelper`, single-file key moves) and **six product defects they found, all fixed +red→green** (storage-provider read-your-writes, `PageBasedAdapter` persistence, single-file UPDATE statement +atomicity, RTRIM/collation-aware key uniqueness, `HorizontalSum`, `DeserializeBatchDouble`). Known issues +**§10 and §11 are closed** and **§4 is fixed at the provider layer**. Validated across all 17 test projects: +**4,968 tests / 0 failed / 1 skipped**; line coverage of the shipped assemblies **49.00%** (engine assembly +**56.92%**); the write-path gate **PASSED** (8/8 capability metrics `ok`, worst `raw UPDATE` 1.22×, tolerance +1.50×). Quality state, the tiered coverage floors and the SonarCloud triage: +[`quality/SONAR_AND_COVERAGE.md`](quality/SONAR_AND_COVERAGE.md); mutation baselines: +[`quality/MUTATION_TESTING.md`](quality/MUTATION_TESTING.md). Notes: [`CHANGELOG.md`](CHANGELOG.md) › +`[2.2.1]`. + +The **previous release was `2.2.0` (2026-11-28)** — a minor release: the .NET 11 dependency majors (EF Core / ASP.NET Core / Extensions **11.0.0**, Aspire.Hosting **17.0.0**, MailKit/MimeKit **5.0.0**, Serilog **11.0.0**), **EF Core 11 compatibility** for the provider, and **option 2 of issue [#525](https://github.com/MPCoreDeveloper/SharpCoreDB/issues/525)** — an unquoted value in `UPDATE … SET` / @@ -31,7 +47,7 @@ suites — 0 failed, 0 errors, 16 skipped** (core 1,916), the write-path regress the full benchmark arm set (comparative, fair-PK, pure-default, PageBased, multi-row INSERT) measured in the product-default regime. Release notes: [`2.1.0-RC.3_WHAT_CHANGED.md`](2.1.0-RC.3_WHAT_CHANGED.md). `2.1.1` followed on **2026-10-25** with the SQL vector fixes; `2.1.2` (2026-10-26) with the statement-path -literal scanner; `2.1.3` added the LINQ to DB adapter fix; `2.1.4` (2026-11-13) was the quoted-identifier patch; `2.2.0` (2026-11-28) is the current release. +literal scanner; `2.1.3` added the LINQ to DB adapter fix; `2.1.4` (2026-11-13) was the quoted-identifier patch; `2.2.0` (2026-11-28) was the dependency-majors release; `2.2.1` (2026-11-30) is the current release. ### .NET 11 GA upgrade (released as 2.1.3 on 2026-11-12) @@ -75,7 +91,7 @@ The **v2.0 stable packages (`2.0.0.3`)** are the net10.0 / C# 14 line, parked on `SharpCoreDB.HybridSearch` and `SharpCoreDB.Aspire.Hosting` ship on this line for the first time - ✅ **2.1.0 was published from `master`, and `2.1.1` followed as a patch (2026-10-25)** — the publish trigger is the `push: branches: [master]` job in `.github/workflows/ci.yml`, which packs and pushes the - 28 packages; `2.2.0` is the current release. History: [`CHANGELOG.md`](CHANGELOG.md). + 28 packages; `2.2.1` is the current release. History: [`CHANGELOG.md`](CHANGELOG.md). - ✅ **Linux/macOS data-integrity defect fixed** — the AES-GCM cipher caches were shared across threads, which is only safe on Windows (dotnet/runtime#53320); they are thread-affine now, so concurrent encryption cannot corrupt a cipher's native state or repeat a nonce off Windows @@ -153,8 +169,9 @@ The **v2.0 stable packages (`2.0.0.3`)** are the net10.0 / C# 14 line, parked on `docs/performance/INSERT_UPDATE_PERFORMANCE_PLAN.md` §11. - [ ] **PageBased UPDATE** (4.9× behind on the fixed-width layout) — profiled, needs the same instrumentation the append-only batch path has. -- [ ] **.NET 11 / C# 15 migration** (after Nov 2026 GA) — Runtime Async, AVX-VNNI-512/SVE2 behind - `SIMD_ENABLED`, optional Zstandard compression. +- [ ] **.NET 11 / C# 15 migration** (after Nov 2026 GA) — Runtime Async ✅, optional Zstandard compression ✅ + (`DatabaseOptions.BlockCompression = BlockCompressionMode.Zstd`, in-box .NET 11 `ZstandardStream`, header-recorded + mode enforced on open), AVX-VNNI-512/SVE2 behind `SIMD_ENABLED` still open. - [ ] **Native AOT warning cleanup** — interface-based B-tree factory (replace `GetMethod`/ `Activator.CreateInstance`), source-gen `.scdb`/`ParseVectorValue` JSON. - [ ] **Single-file metadata parity:** make `SingleFileDatabase` explicitly implement diff --git a/docs/README.md b/docs/README.md index 3f122506..a2311267 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # SharpCoreDB Documentation -This folder contains the maintained documentation set for SharpCoreDB (`v2.0.0`). +This folder contains the maintained documentation set for SharpCoreDB (`v2.2.1`). ## Start Here diff --git a/docs/Vectors/README.md b/docs/Vectors/README.md index 00d781fa..657bdcda 100644 --- a/docs/Vectors/README.md +++ b/docs/Vectors/README.md @@ -76,10 +76,10 @@ This is the foundation for: ```bash # Core database -dotnet add package SharpCoreDB --version 2.2.0 +dotnet add package SharpCoreDB --version 2.2.1 # Vector search extension -dotnet add package SharpCoreDB.VectorSearch --version 2.2.0 +dotnet add package SharpCoreDB.VectorSearch --version 2.2.1 ``` ### 2. Register Vector Search diff --git a/docs/analytics/README.md b/docs/analytics/README.md index bb73854f..c2ee949f 100644 --- a/docs/analytics/README.md +++ b/docs/analytics/README.md @@ -32,7 +32,7 @@ The SharpCoreDB Analytics Engine provides high-performance data aggregation, win ### Installation ```bash -dotnet add package SharpCoreDB.Analytics --version 2.2.0 +dotnet add package SharpCoreDB.Analytics --version 2.2.1 ``` ### Basic Aggregation diff --git a/docs/cqrs/README.md b/docs/cqrs/README.md index 38f7394f..3a68895f 100644 --- a/docs/cqrs/README.md +++ b/docs/cqrs/README.md @@ -54,7 +54,7 @@ Non-goals: ## 2. Installation ```bash -dotnet add package SharpCoreDB.CQRS --version 2.2.0 +dotnet add package SharpCoreDB.CQRS --version 2.2.1 ``` --- diff --git a/docs/graphrag/README.md b/docs/graphrag/README.md index cee01719..231dca1d 100644 --- a/docs/graphrag/README.md +++ b/docs/graphrag/README.md @@ -49,9 +49,9 @@ For package-level mapping, see `../FEATURE_MATRIX.md`. ## Quick start ```bash -dotnet add package SharpCoreDB.Graph.Advanced --version 2.2.0 -dotnet add package SharpCoreDB.Graph --version 2.2.0 -dotnet add package SharpCoreDB.VectorSearch --version 2.2.0 +dotnet add package SharpCoreDB.Graph.Advanced --version 2.2.1 +dotnet add package SharpCoreDB.Graph --version 2.2.1 +dotnet add package SharpCoreDB.VectorSearch --version 2.2.1 ``` ```csharp diff --git a/docs/manual/performance.md b/docs/manual/performance.md index dd46a899..b82084cf 100644 --- a/docs/manual/performance.md +++ b/docs/manual/performance.md @@ -1,6 +1,6 @@ # 7. Performance Guide -> **The headline:** SharpCoreDB v2.1.0 is the current *performance-first* release, on the .NET 11 / +> **The headline:** SharpCoreDB v2.2.1 is the current *performance-first* release, on the .NET 11 / > C# 15 line. The v1.x gap (point reads/updates/deletes ~16–52x behind SQLite, because every update > appended a new row) is closed as an engine behaviour, and re-measured on 2026-10-11 (`92794084`) > the **default posture is INSERT 1,17x (1,03–1,27) and READ 1,13x (1,12–1,15) ahead of SQLite** while diff --git a/docs/manual/quickstart.md b/docs/manual/quickstart.md index f000c4b2..439ea59c 100644 --- a/docs/manual/quickstart.md +++ b/docs/manual/quickstart.md @@ -8,7 +8,7 @@ ## 1.1 Install ```bash -dotnet add package SharpCoreDB --version 2.2.0 +dotnet add package SharpCoreDB --version 2.2.1 ``` The engine targets **.NET 11** and **C# 15**. No native dependencies, no external processes — diff --git a/docs/performance/WORKLOG.md b/docs/performance/WORKLOG.md index 3104d2c4..086374fa 100644 --- a/docs/performance/WORKLOG.md +++ b/docs/performance/WORKLOG.md @@ -5457,3 +5457,433 @@ One consequence worth stating precisely, because it is easy to misread the red a - Commit: five commits on `release/net11-ga-20261112` (`f2d4bc6b`, `a514f496`, `da492ad3`, `242f2faa`, `c8a28519`), pushed. **Not merged** — merging to `master` runs `pack` and publishes to NuGet.org. - NEXT: (1) **owner, blocks the release** — bump `Aspire.Hosting` and `Aspire.Hosting.AppHost` to **13.6.5** in `Directory.Packages.props` (NU1903 / CVE-2026-120006); that turns the three `Build and Test` jobs into full build+test runs on the runners. (2) **owner** — version metadata (`Version`/`AssemblyVersion`/`FileVersion`, ``), the tag, the merge that packs and publishes (or **Manual NuGet Publish** with an explicit `packVersion`), the GitHub release with §1–§3 of `GA_RELEASE_NOTES.md`, and the image push. (3) **optional, no longer blocking** — re-record the baseline from an elevated quiet shell; the capability statistic is already reproducible to ~1 % on the UPDATE cells. (4) unchanged queue head — P2's deferred-span classification for UPDATE, gated on a measured timing win. + +### 2026-11-29 (session 88) — prepared DELETE landed; "we are behind on READ/INSERT" re-read against the code and corrected + +- Session: 88 (owner: "I thought we were only still behind on UPDATE and INSERT — give that extra attention besides the READ finding, and write a good spec-kit plan"). +- Command(s): DELETE branch added to `Database.ExecuteBatchPrepared`; `dotnet build tests/SharpCoreDB.Tests/SharpCoreDB.Tests.csproj -c Release -f net11.0`; MTP `-filterVSTest 'FullyQualifiedName~ExecuteBatchPreparedTests'`; `git stash` of only `Database.Batch.cs` for the red proof; wider suite with the CI category filter; the eight standing canaries; `specs/004-read-insert-delete-parity/{spec,plan,tasks}.md`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT. No new wall-clock verdict is claimed for this change (correctness + red→green is the deliverable); the ratios quoted below are the same-run `--pk` numbers already recorded in `specs/002`. +- Verdict: **SHIPPED — prepared DELETE (red 2 failures → green 0).** The READ and INSERT "behind" premises are **FINDINGS, corrected**: READ's parse is already skipped and `ExecuteQueryStruct` already exists; INSERT is ahead on plaintext and behind only by the deliberate encryption tax. UPDATE's remaining lever is write-volume, which is a durability decision (`BLOCKED`, owner). + +**1. Prepared DELETE — the one remaining safe, contained lever.** `ExecuteBatchPrepared` accepted only the canonical UPDATE template; the canonical DELETE halves (`table`, `whereCol`, `whereValRaw`) were already produced by `TryScanCanonicalDml` and then discarded by the `setCol.Length == 0` rejection. The branch now binds each parameter set's already-typed key into `DeleteBatchStructured` — the same PK / hash-index / contiguous resolvers the SQL batch DELETE path and the SQL-free `DeleteBatch` run — inside the same `RunInBatchTransaction` every batch path uses. Signature unchanged, so no caller or interface breaks. Non-canonical templates, a literal WHERE value and a missing parameter still throw `ArgumentException`; a null key is rejected by `DeleteBatchStructured`. Red→green proven by stashing only `Database.Batch.cs`: **Failed: 2 → Failed: 0** (the two positive DELETE tests), with the pre-existing UPDATE test and non-parameter rejection green on both sides. + +**2. The READ finding, corrected before it was built.** The earlier hypothesis was "the SQL READ re-parses per call, so a compiled SELECT plan is the lever". Reading `Database.Execution.ExecuteQuery` → `SqlParser.ExecuteQuery(CachedQueryPlan)` showed the point-lookup shape **already skips the parse**: `SimpleSelectPlan.TryCreate` + `TrySelectIndexedPointLookup` resolve `WHERE indexed_col = @param` straight through the hash index with no WHERE-string rebuild and no SQL re-parse, and the benchmark's READ arm (`SELECT * FROM docs WHERE name = @name`) is exactly that shape. The residual `ExecuteQuery` gap is the `List>` materialisation (one boxed `object` per column in `DeserializeRowWithSimd` / `DeserializeRowFixedWidth`), which is **inherent to the `ExecuteQuery` contract** — and the StructRow SQL read already exists as `ExecuteQueryStruct`. **Nothing was built for a "compiled SELECT"; the honest guidance is `ExecuteQueryStruct` for a caller that needs Direct-READ shape through SQL.** (No engine change: the fast paths were already there and are pinned by their tests.) + +**3. INSERT — "behind" only in the encrypted default.** Same-run `--pk`: FW **plaintext** INSERT 199.364–230.983 vs SQLite 185.766 (**1,07–1,35× ahead**); FW **at-rest** 167.421 (**~0,90×**). The at-rest gap is the encryption tax (~1,34×, already down from 1,90× by the cipher pool + nonce counter, session 62), which SQLite never pays because its benchmark arm is plaintext. The only knob left is the existing opt-in `EnableBatchEncryption`; the honest floor is the GCM framing (28 B/record) + AES work. **No defect to fix.** + +**4. UPDATE/DELETE raw — the remaining lever is write-volume, which is durability.** The safe levers are landed: the contiguous fixed-width patch (Phase 7, `row-locate` alloc −21 %, gap ~1,4× → ~1,2×) and the prepared UPDATE API (PR #534, 4,69× raw). What is left is the write **volume**: 10.000 × ~620 B = **6,2 MB per batch** to change one 8 B field, with `commit` + `commit-ovw-*` ~19 % of the profiled pass and `commit-ovw-write` 0,1 % (so it is not I/O syscalls). A field-level in-place write and a WAL-fsync-policy change are **durability/write-path changes** — recorded `BLOCKED` on the owner, with the evidence in `specs/002` Phase 10 and `specs/004` US4. + +- Verification: build **0 errors**; `ExecuteBatchPreparedTests` **5/5** (2 failed with the src change stashed); wider suite `Category!=Debug&Category!=Manual&Category!=Performance` **2985 / 0 failed / 6 skipped**, exit 0; the eight standing canaries **57 / 0 failed**; `specs/004` spec+plan+tasks written; `docs/CHANGELOG.md` entry added under `[Unreleased]`. +- Commit: none — nothing committed or pushed. +- NEXT: (1) **owner decision (BLOCKED)** — field-level in-place write (`OverwriteFieldAt`) and/or the WAL fsync policy vs SQLite `synchronous=NORMAL`, with the reopen round-trip matrix as the durability gate; this is the only lever that can move raw UPDATE/DELETE below ~0,83×. (2) optional — a `--pk` read arm comparing `ExecuteQueryStruct` against `FindByIndex` on the same run, so StructRow SQL parity is a measured column rather than an inference (`specs/004` T015). (3) optional — a `--pk-prepared`-style DELETE arm to quote the prepared DELETE wall number (the correctness/red→green proof is already in). (4) owner-only — merge; the agent does not push to `master`. + + +### 2026-11-29 (session 88, addendum) — the commit flush's page-read lever REFUTED and reverted: commit 10,6 → 32,0 ms + +- Session: 88 (addendum — the surviving candidate from the field-level-write / WAL-fsync investigation, built and measured against `--pk-profile`). +- Command(s): implemented full-page assembly in `Storage.Append.cs`'s `FlushOverwritePages` (+ `CanAssemblePage`, `IndexCrossPageRecords`, a `commit-ovw-read` stage, the `CommitOverwritePagesRead`/`CommitOverwritePagesAssembled` counters and `CommitOverwritePageAssemblyTests`); `--pk-profile` with the PRE (stashed) and POST binaries; an instrumented split (`sort`/`index`/`precheck`/`loop`); reverted both source files and deleted the test. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`. No quiet-machine verdict is claimed — the direction is a 3× regression in `commit`, far outside this box's noise. +- Verdict: **REJECTED, reverted in the same session. The page-read premise does not hold in the `--pk` flow.** + +**What was tried.** A page whose complete new content is its own overwritten records was assembled from the buffered payloads without reading the file (length prefixes derived from `payload.Length` under the same-length overwrite invariant), with cross-page records indexed by both pages they touch. The premise: the code's own 2026-09-21 note measured **~17,5 ms of page READS** in a 29,8 ms flush. + +**The measurement (same box, PRE = stashed change, POST = the change):** + +| stage | PRE (ms) | POST (ms) | +|---|---:|---:| +| `commit` | **10,6** | **32,0** | +| `commit-ovw-prep` | 5,1 | 5,1 | +| `commit-ovw-write` | 0,1 (2 calls) | 0,6 (284 calls) | +| `commit-ovw-read` | — | 0 (absent — every page assembled) | +| pages | 2 coalesced runs read | **1 read · 283 assembled** | +| UPDATE ops/s | 105.652 | 85.538 | + +Instrumented POST split: `sort 1,28 ms · index 0,60 ms · precheck 5,20 ms · loop 16,04 ms`. + +**Why the premise was wrong.** The pre-change flush coalesces consecutive pages into ONE read + ONE write (≤1 MB per range) — **2 reads and 2 writes** for the whole 10.000-row batch, and both reads are **page-cache hits** because `TryBulkUpdateContiguousFixedWidth` has just read the same span into `raw`. The 17,5 ms figure came from a cold page set; the benchmark's data file is **11,6 MB**, so it is resident after the insert phase. Removing cache-hit reads saves ~nothing, and the replacement costs 284 coverage passes (5,2 ms) plus **284 per-page writes instead of 2 coalesced 1 MB writes** (16,0 ms). + +**What the wider suite caught in the first cut (worth keeping as a lesson).** A length prefix that straddles a page **end** (not just a page start) produced a 2-byte `WriteInt32LittleEndian` → `ArgumentOutOfRangeException`, surfaced by `FixedWidthBulkDeleteTests.AscendingUpdateBatch_BatchedPageFlush_AppliesEveryRow_AcrossReopen`. Fixed by disqualifying straddling pages, after which the wider suite read **2986 / 0 failed / 6 skipped** and the canaries **58 / 0** — but the perf verdict was already negative, so the change did not ship. The lesson: for a page-granular flush, a byte-level optimisation must also be verified **at both page boundaries**. + +**Settled by evidence, not left open.** (1) **Field-level write**: the flush is page-granular read-modify-write, so smaller patches change neither the page count, the reads, nor the writes — its only saving is transient buffer memory (~6 MB/batch) and the row-locate copies, i.e. wall-neutral. (2) **WAL-fsync policy**: the comparator's SharpCoreDB arm already runs `WalDurabilityMode = Async` (`Program.cs` — `FullSync` only via `SHARPCOREDB_WAL_DURABILITY=fullsync`), the overwrite writes are OS-buffered (`RandomAccess.Write`, `FileOptions.None`) and `transactionBuffer.Flush()` is empty for a pure UPDATE batch — so the measured `commit` contains **no fsync**. SQLite's `synchronous=NORMAL` posture is already matched; `FullSync` stays the library default and is not weakened. + +- Verification: pre-revert wider suite **2986 / 0 / 6**, canaries **58 / 0**, the caught defect fixed and both rails green; after the revert the tree is back to the green state (source files at `HEAD`, test deleted, `specs/005` records the refutation). +- Commit: none — nothing committed or pushed. +- NEXT: (1) the raw UPDATE arm's honest remaining cost is `parse` (20-34 %) — solved for prepared callers by `ExecuteBatchPrepared` (4,69×), with the internal DML shape cache refuted in `specs/003` — and the `row-locate` span read, which is the data movement a patch needs. (2) `specs/005` is the closed record for the commit-flush lever; do not re-open it without a cold, larger-than-cache data set to measure against. (3) owner-only — merge; the agent does not push to `master`. + + +### 2026-11-29 (session 88, addendum 2) — §5.4 providers re-validation + the three harness arms + a documented gate re-run + +- Session: 88 (addendum 2 — brief §5.4, due after every core change; the prepared-DELETE branch is the core change, session count for §5.4 = 1 of 1). +- Command(s): built and ran the six provider suites; `--pk`, `--pk-default`, `--multirowinsert` on the clean build; `scripts/quiet-machine.ps1` then `-Apply -StopServices`; `--gate` **twice** (the first failed, the re-run passed — documented, not a silent retry). +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`. The quiet check returned **NOISY**: `WSearch` (needs elevation — the known privilege limit) and 12 idle build servers (shut down by `-Apply`). The gate has passed on this box with `WSearch` running (attempts 9/10; sessions 64–67). +- Verdict: **§5.4 DONE — no provider re-introduces row-by-row overhead; the three arms are recorded on the clean build; the gate PASSED on the documented re-run.** + +**Providers (six suites, current build, all exit 0):** EF Core **116**, Functional.Dapper **3**, Functional.Linq2DB **96**, Functional **98**, Functional.EntityFrameworkCore **3**, Provider.Sync **135** = **451 tests / 0 failed**. (YesSql and `Data.Provider` have no separate suite — exercised inside the core and functional projects, as §5.4 records.) + +**`--pk` (fair-PK, median of the harness's paired reps, same-run SQLite):** + +| arm | INSERT | READ | UPDATE | DELETE | +|---|---:|---:|---:|---:| +| SharpCoreDB legacy plaintext | 231.480 | 149.107 | 383.212 | 562.936 | +| SharpCoreDB FW plaintext | **248.930** | **178.155** | **742.853** | **833.423** | +| SharpCoreDB FW at-rest | 215.972 | 130.481 | 353.933 | 585.161 | +| SQLite (reference) | 187.158 | 124.156 | 811.484 | 1.088.660 | + +Gap (SQLite ÷ ours; >1 means SQLite faster): INSERT **0,8× legacy / 0,8× FW / 0,9× at-rest** (we are +**1,11–1,25× ahead**), READ **0,8× / 0,7× / 1,0×** (FW plaintext **1,43× ahead**), UPDATE **2,1× / 1,1× / 2,3×** +(FW plaintext 0,91× — the prepared-API and contiguous-patch work has brought the raw arm to ~parity), DELETE +**1,9× / 1,3× / 1,9×**. At-rest tax, same arm shape: INSERT **1,15×**, READ **1,37×**, UPDATE **2,10×**, +DELETE **1,42×** — the encrypted/default gap is the deliberate tax (SQLite's arm is plaintext), reported beside +the plaintext numbers as §III requires. + +**`--pk-default` (default config, PK-less, not like-for-like — trap 4):** INSERT **1,22×** (1,21–1,29), +READ **1,10×** (0,91–1,11 — straddles 1,0, inside the box's noise), UPDATE **0,58×** (0,53–0,59), DELETE +**0,63×** (0,54–0,65). INSERT and READ ahead on the default arm too. + +**`--multirowinsert` (the INSERT budget, clean build):** **100.203 rows/s**, **3.143 B/row**, +data file **2.320.000 B**, overflow arena **0 B** — byte-identical to the record; stages: `dispatch` 35,1 %, +`table-batch` 18,2 %, `validate` 12,3 %, `encode` 11,3 %, `row-build` 7,6 %, `parse` 6,3 %, `index-maint` 2,3 %, +`engine-write` 1,4 %, `commit` 1,0 %. The remaining INSERT cost is the SQL dispatch/parse + the serialized +record itself — §5.1's close note stands, no new lever. + +**Gate — documented re-run.** Run 1: **FAILED** on `default UPDATE` capability (**1,56×** vs baseline, band +1,50). Nothing in this session touches that path (`git diff` is `ExecuteBatchPrepared` + doc comments + specs + +the bulk-delete tests; `Storage.Append.cs` and `Table.CRUD.cs` are at `HEAD`), and the same code path measured +363,6K on the raw arm. The quiet check named `WSearch` + 12 build servers; `-Apply -StopServices` shut the +servers (WSearch needs elevation). Run 2: **GATE PASSED** — 8/8 capability metrics `ok`, `default UPDATE` +**1,16×** (285.720 best-of-reps). The first failure was the box, as the gate's own guidance predicts; both runs +are recorded here rather than retried silently. + +- Verification: provider suites **451 / 0**; build 0 errors; core suite **2985 / 0 / 6** and canaries **58 / 0** + (recorded in the previous addendum, post-revert); `--gate` **PASSED** (re-run). +- Commit: the prepared-DELETE branch + `specs/004` + `specs/005` + this worklog, committed on + `perf/002-sqlite-update-delete-parity` and pushed as a feature branch. **Not merged** — merging runs `pack` + and publishes, which stays an owner action. +- NEXT: (1) **owner-only** — merge the feature branch; the agent stops at the push. (2) The fair-PK plaintext + arm is now **INSERT 1,25× / READ 1,43× ahead, UPDATE 0,91×, DELETE 0,77×**; the raw UPDATE/DELETE remainder + has no safe lever left (`specs/005` closed the commit-flush candidate; `parse` is solved for prepared callers + at 4,69×; the DML shape cache is refuted in `specs/003`), so a next session needs a **new** lever or an owner + decision before re-opening it. (3) Optional measurement gap — a `--pk` DELETE/INSERT arm for the prepared API + to quote those wall numbers (correctness/red→green already proven). + + +### 2026-11-30 (session 89) — plans 006–009 written; plan 006 US1+US2 shipped: at-rest UPDATE tax 1,945× → 1,585× (−19 %) + +- Session: 89 (owner: "werk 1,2,3,4 uit als plan en start dan aan 1"; item = plan 006, session count for it = 1 of 2). +- Command(s): wrote `specs/006-parallel-record-encryption/spec.md`, `specs/007-native-aot-cleanup/spec.md`, `specs/008-single-file-metadata-parity/spec.md`, `specs/009-owner-decisions/spec.md`; implemented US1 (parallel span decrypt) + US2 (parallel record seal); `ParallelRecordEncryptionTests`; red proofs by flipping each guard; PRE/POST `--pk` A/B (4 pairs); wider suite; canaries; `--gate` twice (first failed, documented re-run passed). +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`; quiet check **NOISY** (WSearch = the standing privilege finding; build servers shut down by `-Apply`). +- Verdict: **SHIPPED — plan 006 US1+US2, at-rest UPDATE tax −19 % (median), DELETE directionally better, byte-identical results, no format/encryption-strength/durability change.** + +**The four plans (deliverable half of the request).** 006 parallel record encryption (this session's code); +007 Native AOT cleanup (interface B-tree factory + source-gen JSON); 008 single-file metadata parity +(`SingleFileDatabase : IMetadataProvider`); 009 the four owner decisions with evidence +(single-file PK/composite keys §11, single-file `COLLATE` §10, `INTEGER` affinity §6, optional Zstandard). + +**What shipped (006 US1+US2).** `TryReadContiguousFixedWidthRecords` decrypts the contiguous span on +`Parallel.For` when `count >= 64`; `TryBulkUpdateContiguousFixedWidth` seals the patched payloads the same way +for encrypted files. Both latch a failure (no early worker return) so the whole batch still rejects as one, and +both are safe because `AesGcmEncryption` already keeps one cipher per thread and derives nonces from an +`Interlocked` counter. `BufferOrWriteOverwriteInPlace`'s base-length cache moved INSIDE `appendLock` — it was +outside, a latent race once the batch path calls it from parallel workers. Diagnostics: +`BulkContiguousParallelDecryptBatches` / `BulkContiguousParallelEncryptBatches`; `ParallelRecordEncryptionTests` +(2 cases) asserts both engage above the threshold, neither below it, and a full-scan-after-reopen equality. + +**Red proofs.** Decrypt guard off → `Expected: 1, Actual: 0`, Failed 1. Seal guard off → same. Restored, 2/2. + +**Measurement** (`--pk`, PRE binary vs POST, 4 pairs; tax = at-rest ÷ plaintext **within the run**): + +| pair | POST UPDATE | PRE UPDATE | POST DELETE | PRE DELETE | +|---|---:|---:|---:|---:| +| 1 (US1) | 1,61 | 1,81 | 1,55 | 1,86 | +| 2 (US1) | 2,16 | 2,07 | 1,61 | 1,68 | +| 3 (US1+US2) | **1,56** | **2,05** | **1,16** | **1,40** | +| 4 (US1+US2) | **1,61** | **1,84** | 1,44 | 1,30 | + +US1 alone: neutral on UPDATE (the write-side seal dominates — which is why US2 exists) and better on DELETE in +2/2 pairs. US1+US2: UPDATE tax median **1,945 → 1,585** (−19 %), POST better in both pairs; DELETE mixed +(1,16 vs 1,40; 1,44 vs 1,30) — box noise dominates that cell. READ is untouched by the change (point-read +decrypt path); its movement in the table is noise and is not claimed. + +**Gate — documented re-run.** Run 1 **FAILED** (`default UPDATE` capability 1,61× on a NOISY box); quiet check ++ `-Apply`, build servers shut down; run 2 **GATE PASSED**, 8/8 `ok` (`default UPDATE` **1,10×**, `raw UPDATE` +1,23×). The failing cell is the PK-less legacy arm, which this change does not enter (the parallel branches +require fixed-width + an explicit PK; the only shared change is the lock merge). + +- Verification: build **0 errors**; focused rails **38/38**; wider suite **2987 / 0 failed / 6 skipped**; + canaries **59 / 0**; gate **PASSED** (re-run). +- Commit: `Table.CRUD.cs` + `Storage.Append.cs` + `ParallelRecordEncryptionTests.cs` + specs 006–009 + + CHANGELOG + this worklog, committed on `perf/002-sqlite-update-delete-parity` and pushed. Not merged. +- NEXT: (1) **plan 007** (Native AOT cleanup) — the next safe item; (2) **plan 008** (single-file metadata + parity); (3) **plan 009** needs owner decisions (four items with evidence); (4) owner-only — merge. + + +### 2026-11-30 (session 89, addendum) — plan 007 VERIFIED DONE (0 IL/AOT warnings, smoke pass) + plan 008 shipped (`SingleFileDatabase : IMetadataProvider`) + +- Session: 89 (addendum — owner: "ga naar de volgende plan"; items 007 and 008; session count per item = 1 of 1 each). +- Command(s): `dotnet publish tools/SharpCoreDB.AotSmoke -c Release -r win-x64 -p:PublishAot=true`; the published native exe; one-line interface addition + `SingleFileMetadataParityTests`; red proof by removing the interface; wider suite; canaries; `--gate`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`; quiet check **NOISY** (WSearch = the standing privilege finding; build servers shut down). +- Verdict: **007 VERIFIED DONE (the roadmap item was stale — both halves were already implemented); 008 SHIPPED (one-line interface + red→green parity test).** + +**007 — Native AOT cleanup: already done, verified end to end.** `BTreeIndexManager.CreateBTreeIndex` is the +closed-generic `switch` that replaced the `GetBTreeIndexType` + `Activator.CreateInstance` pair (IL3050), and +`ITypeErasedIndex` replaced `GetType().GetMethod("Add")`/`("FindRange")`. `AotJsonSerializer` picks its resolver +by runtime (`JsonSerializer.IsReflectionEnabledByDefault`) — reflection where available, the source-generated +`SharpCoreDBJsonContext` + `SharpCoreDBAotJsonContext` under AOT — and every call site resolves +`GetTypeInfo()`. Measured: the AOT publish of the whole engine + smoke tool reports **0 errors and 0 +IL/AOT warnings**; the native exe prints `IsReflectionEnabledByDefault = False` and **PASS, exit 0** (1000 +inserts, point lookup, StructRow point + full scan, reopen, full vacuum, at-rest encryption + password/key +rotation). No code change; the item is recorded as verified so it is not re-opened. + +**008 — single-file metadata parity: shipped.** `SingleFileDatabase` already had `GetTables()`/`GetColumns()` +(via `IDatabase`) but did not declare `IMetadataProvider`, so `db is IMetadataProvider` was true for a directory +database and false for a `.scdb` file. One interface was added to the class declaration (implicit +implementation, the shape `Database` uses); the methods already answered from the single-file catalog. +`SingleFileMetadataParityTests` asserts the probe for both modes, the table listing, and column-for-column +equality (table, name, data type, ordinal, nullability, collation). Red proof: removing the interface makes the +test fail with `single-file database must be an IMetadataProvider`; restoring it is green. + +- Verification: AOT publish **0 errors / 0 IL-AOT warnings**, native smoke **PASS exit 0**; build 0 errors; + focused 18/18; wider suite **2988 / 0 failed / 6 skipped**; canaries **60 / 0**; `--gate` **PASSED** + (`raw UPDATE` 1,42× and `default UPDATE` 1,36× were `watch` on a loaded box, both under the 1,5× threshold). +- Commit: the interface line + the parity test + specs 007/008 + CHANGELOG + this worklog, committed on + `perf/002-sqlite-update-delete-parity` and pushed. Not merged. +- NEXT: (1) **plan 009** — the four owner decisions (single-file PK/composite keys §11, single-file `COLLATE` + §10, `INTEGER` affinity §6, optional Zstandard) are written up with evidence and need the owner; (2) optional + — the `--pk` prepared DELETE/INSERT measurement arms; (3) owner-only — merge. + + +### 2026-11-30 (session 89, addendum 3) — owner decisions D1=A / D2=A / D3=B shipped on single-file storage; D4=C BLOCKED on the package rail + +- Session: 89 (addendum 3 — owner answered D1=A, D2=A, D3=B, D4=C; session count per item = 1 of 1 for each). +- Command(s): single-file DDL/format changes (key columns + collation), `SingleFileTable` enforcement, batch literal parser fix, `IntegerAffinityTests` (3), `SingleFileCollationTests` (3), four previously-skipped `PrimaryKeyUniquenessTests` cases enabled, the skipped ORDER BY collation test enabled; wider suite; canaries; `--gate`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`; quiet check NOISY (WSearch = the standing privilege finding; build servers shut down). +- Verdict: **D1, D2, D3 SHIPPED (all red→green); D4 BLOCKED with evidence — no inbox Zstandard in .NET 11.** + +**D1=A — single-file key modelling + enforcement.** The parser now records **every** key column (the table-level +`PRIMARY KEY (a, b)` form no longer throws, and inline declarations accumulate) and the writer flags each of +them plus a free marker bit (`ColumnDefinitionEntry.KeyModelledFlag`, bit 6). `SingleFileTable` collects them on +reload, keeps the last as the storage key (unchanged behaviour), and enforces the key tuple's uniqueness on +INSERT, multi-row INSERT (validate-all-then-add, so a duplicate inside the statement keeps no row) and all three +UPDATE paths — a moved key cannot land on another row. A file written before the marker stays unenforced, which +is what makes this safe for existing databases. The four skipped `PrimaryKeyUniquenessTests` single-file cases +now pass (duplicate, multi-row against existing, duplicate within the statement, after reopen). + +**D2=A — single-file `COLLATE`.** Parsed in the DDL, persisted in the free flag bits 8–11 +(`GetCollation`/`SetCollation`), reloaded on reopen and honoured by the WHERE evaluator (`ComparisonForColumn`, +with the compiled ordinal fast path bypassed for such a column) and by ORDER BY (single-file comparer; the SQL +layer's `SqlOrderBy` already read `ColumnCollations`). The skipped +`OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively` test now runs and passes; `SingleFileCollationTests` +covers WHERE equality/range, BINARY staying case-sensitive, ordering and a reopen. Red proof: reverting the +reader makes the reopen test fail. + +**D3=B — Int32 stays the default, but its two defects are fixed.** The batch literal path stored an out-of-range +INTEGER as **0** (silent corruption) — it now throws the same actionable message as the single-statement path, +keeping the lenient 0 only for non-numeric text; and the single-file DDL hardcoded `UseSqliteIntegerAffinity: false`, +so the opt-in the message names had no effect there — it now reads the config. Both proven red. + +**D4=C — BLOCKED (package rail).** Verified that .NET 11's `System.IO.Compression.dll` (11.0.0) has ZLib but +**no Zstandard/Zstd**, so Zstd needs a third-party package and a version in `Directory.Packages.props` — a +standing owner rail. Recorded in `specs/009` with the two ways forward: authorise `ZstdSharp` (+ version), or +ship the opt-in compression layer over the inbox `ZLib`/`Brotli` codec and plug Zstd in later. + +- Verification: build **0 errors**; focused rays **86/86**; wider suite **2994 / 0 failed / 1 skipped**; + canaries **75 / 0**; `--gate` **PASSED** (8/8 capability `ok`, `raw UPDATE` 1,30× watch only). +- Commit: the three fixes + the enabled tests + `specs/009` + CHANGELOG + this worklog, committed on + `perf/002-sqlite-update-delete-parity` and pushed. Not merged. +- NEXT: (1) **owner** — decide D4's route (package authorisation or the inbox-codec variant); everything else + in plans 006–009 is delivered or verified. (2) optional — the `--pk` prepared DELETE/INSERT measurement arms. + (3) owner-only — merge. + + +### 2026-11-30 (session 89, addendum 4) — D4 CORRECTED: Zstd is in-box and already implemented; the wider suite then caught a real cross-database cache bug, fixed + +- Session: 89 (addendum 4 — owner corrected the D4 "blocked" verdict with the .NET 11 `ZstandardStream` docs; session count for D4 = 1 of 1). +- Command(s): re-verified the API by scanning the `11.0.0` ref pack for **`Zstandard`** (the earlier scan searched `ZStandard` and missed it); read `BlockCompressor`/`BlockCompressionMode`/the SCDB header; fixed two stale doc claims; added `SingleFileCompressionTests`; fixed the single-file batch INSERT cache key + `SingleFileBatchSchemaIsolationTests`; wider suite twice; canaries; `--gate`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT, `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`. +- Verdict: **D4 CORRECTED — no block, no package: .NET 11 ships in-box Zstandard and the engine already implements it. The wider suite then caught a genuine cross-database defect, fixed with a red→green regression test.** + +**The correction, precisely.** The earlier entry said ".NET 11 ships no inbox Zstandard (verified)". That was wrong twice: the availability check scanned `System.IO.Compression.dll` for **`ZStandard`** while the API is **`Zstandard`** (and the docs page the owner pointed at shows it), and the existing compression layer was never read. Re-scanned: the `11.0.0` ref pack and runtime both contain `ZstandardStream`, `ZstandardEncoder`, `ZstandardCompressionOptions`; `BlockCompressor` already has a `Zstd` mode (thread-static encoder, pooled destination, documented RC.1 allocation measurement), `DatabaseOptions.BlockCompression` selects it, `ScdbFileHeader.CompressionMode` records it and `ValidateHeader` refuses a mismatched open with an actionable message. **No package, no package-rail conflict.** This session's D4 work: fixed the two stale doc claims (`BlockCompressionMode.Zstd` said the mode throws; `BlockFlags.Compressed` said "reserved, always 0") and added the missing end-to-end test — Zstd write → 200-row round-trip after reopen → update → wrong-mode open throws `BlockCompression = Zstd`; plus an encrypted compress-then-encrypt round-trip. `PROJECT_STATUS.md`'s roadmap line now marks the Zstd item done. + +**The bug the wider suite caught (fixed here).** After the D4 work the wider suite went **2996 / 0 → 21 failed**: `SingleFileTests.SingleFileDatabase_VacuumFull_…` and the whole `VacuumStressTests` matrix, all with `Column 'name' cannot be NULL in row 0` on a valid `INSERT INTO docs (name, age)`. Reading the batch path found the cause: `SingleFileDatabaseBatchExtension` keeps a **static** `_insertStatementCache` keyed by the table **name only**, so `SingleFileCompressionTests`' `docs (id, body)` had filled it and `SingleFileTests`' `docs (name, age)` was mapped through that foreign column list — a real cross-database defect (a server hosting two single-file databases with same-named tables hits it), not a test artifact. Fixed by keying the cache on the column signature (name + ordered columns + types) and bounding it at 256 shapes. `SingleFileBatchSchemaIsolationTests` reproduces it: with the name-only key restored the test fails with exactly `Column 'name' cannot be NULL`, and it passes with the shape key. + +- Verification: `SingleFileCompressionTests` **2/2**; `SingleFileBatchSchemaIsolationTests` **1/1** (red→green proven); wider suite **2997 / 0 failed / 1 skipped** (exit 0); canaries **116 / 0**; `--gate` **PASSED** (8/8 `ok`, `raw UPDATE` 1,29× watch). +- Commit: the two doc fixes + the compression tests + the cache-key fix + the regression test + `specs/009`/`PROJECT_STATUS`/CHANGELOG + this worklog, committed on `perf/002-sqlite-update-delete-parity` and pushed. Not merged. +- NEXT: (1) **owner-only** — merge; everything in plans 006–009 is delivered or verified. (2) optional — the `--pk` prepared DELETE/INSERT measurement arms; the AVX-VNNI-512/SVE2 item in the roadmap remains the only open .NET 11 line item. + + +### 2026-11-30 (session 90) — Owner request: coverage, mutation, Sonar and docs; four new suites and six defects fixed + +- Session: 90 (quality pass, in the owner's stated order: tests first, then SonarCloud, then docs). +- Command(s): `pwsh tools/measure-coverage.ps1 -Floor 0.18 -Filter 'Category!=Debug&Category!=Manual&Category!=Performance&Category!=Allocation'` (baseline and final); the MTP host for every suite run; `dotnet tool run dotnet-stryker --test-case-filter "FullyQualifiedName~SqlFunctionsTests"`; the SonarCloud `api/issues/search` reads. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT. No benchmark or `--gate` run this session — no measured hot path changed, except the provider read path, which the gate does not measure. +- Verdict: **Coverage 47.89 % → 49.00 % (engine 55.32 % → 56.92 %); four new suites; six product defects found and fixed red→green; SonarCloud triaged (24 S3358 sites fixed, the rest documented); docs brought to the current state.** + +**Coverage, measured honestly.** The baseline (same filter, before any change) reported **47.89 %** of 62,864 +lines; the final run **49.00 %** of 62,791 (30,766 covered), four suites green. The engine assembly carries the +movement: **55.32 % → 56.92 %**. The owner asked for ≥ 90 %; a whole-repository 90 % means **56,512 covered +lines — 25,746 more than today**, across 12 assemblies including `Client.Protocol` (0 %), `Distributed` +(8.39 %) and `Graph.Advanced` (3.93 %), which have no suites at all. That is a multi-month body of work, and a +blanket number does not follow the risk, so `docs/quality/SONAR_AND_COVERAGE.md` now records a **tiered floor**: +engine 50 % (measured 56.92 %, next gate 60 %), adapters at peak −2, optional packages "a suite first, then a +floor". The script enforces any `-Floor`. + +**The four suites (and the six defects they found).** `SimdHelperTests` (every public SIMD primitive on a +short and a long span, plus the deserializers' wire layouts), `PageBasedAdapterTests` (insert/read/update/ +delete/batch/metrics/transactions/reopen — the adapter had **0 %** coverage), `CorruptionDetectorTests` (all +four validation modes, 0 % before) and `SingleFileKeyMoveTests` (D1=A on every UPDATE/DELETE path). Writing +them found, and this session fixed: + +1. **Read-your-writes was broken in the storage provider** — `WriteBlockAsync` only queues, `ReadBlockAsync` + read the file anyway, and the checksum "self-heal" then rewrote the registry to match the zeros, losing + the block for good. Every `PageBasedAdapter` insert failed with `Page full`. Fixed by draining the queue + before the read, and by clearing the pending flag only when the queue is empty (a write enqueued during + a flush escaped `HasPendingChanges` — a durability gap on close). +2. **`PageBasedAdapter.Dispose` never flushed** the shared provider, so a reopen lost every page. +3. **A rejected single-file UPDATE left the row altered** — all four UPDATE paths wrote first and checked the + moved key afterwards. One shared `ApplyMatchedUpdates` now validates the prospective tuple set before the + first write (statement atomicity, two rows moving onto the same key included); `UpdateByPrimaryKey` gained + the check it never had; `DELETE FROM t` releases the key set. +4. **RTRIM was parsed but compared ordinally**, and the key-tuple set always compared ordinal text — a + `NOCASE` key accepted `'aa'` and `'AA'` while `WHERE k = 'AA'` matched both. `CanonicalKeyPart` + canonicalises per collation; `CompareText` trims for RTRIM in WHERE/BETWEEN/ORDER BY. +5. **`SimdHelper.HorizontalSum` summed 8 instead of 15** on a five-element span (the 128-bit path widened + only the low two int32s of each lane). +6. **`DeserializeBatchDouble` ignored its null flags** ("assumes no nulls for performance"). + + +Red proof: with only `src/SharpCoreDB/SingleFileTable.cs` reverted, **9 of 24** new SingleFile tests failed; +`PageBasedAdapterTests.Insert_ThenRead_RoundTripsTheRecord` failed with `Page full` before the provider fix; +`HorizontalSum` and the double deserializer failed before theirs. After the fixes: focused **51/51**, then the +wider suite **3060 / 0 failed / 1 skipped** — run twice, the second time after the SonarCloud refactors. + +**Mutation testing.** `dotnet-stryker` 5.1.0 with the committed `tests/SharpCoreDB.Tests/stryker-config.json` +(scope `**/SqlFunctions.cs`) and the documented `--test-case-filter "FullyQualifiedName~SqlFunctionsTests"` — +without it the full-suite engine run pays the coverage-relay `Dubious` storm (see +`docs/quality/MUTATION_TESTING.md`). Result: **33 killed / 22 survived / 70 no-coverage over 125 tested +mutants → 26.40 %**, 4 m 14 s (2026-11-13: 27.73 % over 119). The same 33 are killed and the same 70 are +unreached; the six extra survivors are a test-*selection* difference, not a regression, and the survivor +list is the recorded work queue. The tool, scope and `break: 0` threshold are unchanged. + +**SonarCloud.** 307 open findings, all `CODE_SMELL`, no bug and no vulnerability. Fixed **24 real S3358 sites** +(nested ternaries) across `Table.CRUD`, `Table.UniqueKeys`, `SqlOrderBy`, `SqlScalarExpression`, +`SqlParser.DML`, `SqlParser.InformationSchema`, `SubqueryExecutor`, `SimdAggregates`, `PlatformOptimizations` +and `SimdFilter`. The rest is triaged by rule in `docs/quality/SONAR_AND_COVERAGE.md`: S3776/S127/S3267 are +accepted by design (hot-path complexity, scanner index loops, no LINQ allocation on measured paths); S1192 is +the SQL standard's column-name vocabulary; several findings name stale line numbers because automatic analysis +last ran on an older commit — the next push re-analyses, and only then is the residue real. + +- Verification: coverage **PASS 49.00 %, floor 18.00 %** (four suites green: 3060 + 255 + 116 + 96); +wider suite **3060 / 0 / 1**; focused **51/51** and **44/44**; the ten-file SonarCloud refactor set is covered +by the second full run. +- Commit: four test files + `src` fixes (`SingleFileTable`, `SingleFileStorageProvider`, `PageBasedAdapter`, + `SimdHelper.Operations`, `SimdHelper.Deserialization`) + the ten SonarCloud refactor files + CHANGELOG, + known issues, PROJECT_STATUS, both `docs/quality` files and this worklog — on + `perf/002-sqlite-update-delete-parity`, pushed. Not merged. +- NEXT: (1) **owner-only** — merge. (2) The tiered coverage climb: engine 60 % (case matrices for the + `SqlParser`/`Table` partials), then a suite per optional package (`Distributed`, `Graph.Advanced`, + `Client.Protocol`). (3) Re-read SonarCloud after this push's automatic analysis and fix whatever the fresh + +### 2026-11-30 (session 90, addendum 1) — Owner-requested full verification: all 17 suites and the write-path gate, both green + +- Session: 90 (addendum 1 — the "no regressions, check everything" pass; session count for this verification = 1 of 1). +- Command(s): `dotnet restore SharpCoreDB.CI.slnf --configfile NuGet.Config /p:UseLocalProjectReferences=true` · `dotnet build SharpCoreDB.CI.slnf -c Release --no-restore /p:ContinuousIntegrationBuild=true /p:UseLocalProjectReferences=true` · 13 further test projects built individually with `/p:UseLocalProjectReferences=true` · every MTP suite with CI's `Category!=Debug&Category!=Manual&Category!=Performance` · `pwsh scripts/quiet-machine.ps1 -Apply -BenchTempDir D:\scdb-bench-tmp` · `dotnet run -c Release --project tests/benchmarks/SharpCoreDB.Benchmarks.Comparative /p:UseLocalProjectReferences=true -- --gate`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT; `SHARPCOREDB_BENCH_TEMP=D:\scdb-bench-tmp`; Defender exclusion proven in force (control ÷ data open 1,81×), build servers shut down, CPU idle, disk queue 0; `WSearch` running (the documented privilege limit — the gate has passed with it five times). +- Verdict: **NO REGRESSION — 4 968 tests / 0 failed / 1 skipped across all 17 test projects, and the write-path gate PASSED (8/8 capability metrics `ok`, worst `raw UPDATE` 1,22×).** + +**The full suite, all 17 projects** (CI filter; the four CI suites plus the thirteen CI does not build, each +built and run locally with project references so it exercises this tree, not a package): + +| Suite | Total | Failed | +|---|---|---| +| `SharpCoreDB.Tests` (core, Allocation canaries included) | 3 062 | 0 | +| `SharpCoreDB.VectorSearch.Tests` | 255 | 0 | +| `SharpCoreDB.Server.IntegrationTests` | 208 | 0 | +| `SharpCoreDB.Search.Tests` | 257 | 0 | +| `SharpCoreDB.Analytics.Tests` | 393 | 0 | +| `SharpCoreDB.Provider.Sync.Tests` | 135 | 0 | +| `SharpCoreDB.EntityFrameworkCore.Tests` | 116 | 0 | +| `SharpCoreDB.CQRS.Tests` | 99 | 0 | +| `SharpCoreDB.Functional.Tests` | 98 | 0 | +| `SharpCoreDB.Functional.Linq2DB.Tests` | 96 | 0 | +| `SharpCoreDB.EventSourcing.Tests` | 90 | 0 | +| `SharpCoreDB.Identity.Tests` | 53 | 0 | +| `SharpCoreDB.Graph.Advanced.Tests` | 50 | 0 | +| `SharpCoreDB.Projections.Tests` | 44 | 0 | +| `SharpCoreDB.HybridSearch.Tests` | 6 | 0 | +| `SharpCoreDB.Functional.Dapper.Tests` | 3 | 0 | +| `SharpCoreDB.Functional.EntityFrameworkCore.Tests` | 3 | 0 | +| **TOTAL** | **4 968** | **0** (1 skipped) | + +Build: `SharpCoreDB.CI.slnf` **0 errors / 305 warnings**; the 13 extra suites **0 errors** each. Nothing needed +a fix — the suite found no regression from the session's provider/UPDATE/SIMD changes. + +**The write-path gate** (`--gate`, 3 reps, tolerance 1,50×, 8 discarded warm-up reps; median decides, and the +baseline carries best-of-reps entries so capability decides the verdict): + +| Metric | Baseline | Current (best) | Ratio | Verdict | +|---|---|---|---|---| +| raw INSERT | 213 624 | 210 948 | **1,01×** | ok | +| raw READ | 189 046 | 189 036 | **1,00×** | ok | +| raw UPDATE | 477 824 | 390 736 | **1,22×** | ok (watch candidate) | +| raw DELETE | 552 971 | 544 108 | **1,02×** | ok | +| default INSERT | 193 369 | 190 513 | **1,01×** | ok | +| default READ | 147 968 | 140 842 | **1,05×** | ok | +| default UPDATE | 332 458 | 318 587 | **1,04×** | ok | +| default DELETE | 158 846 | 158 196 | **1,00×** | ok | + +**GATE PASSED: nothing is slower than baseline × 1,50.** The median table additionally shows +`default UPDATE` at **1,37×** (verdict `watch`): that cell's median is disturbance-dominated (22–35 ms window; +its best rep agrees across runs to 1 %), which is exactly the reason the gate reads best-of-reps when the +baseline carries it — and `raw UPDATE`'s median is **1,09×** in the same run. The one launcher artefact: the +gate process printed `D:\scdb-bench-tmp: The term … is not recognized` on stderr because the nested +`$env:` assignment in the `-Command` string was mis-quoted; the regime lines in the report confirm the data +dir and SQLite reference were applied (the variable was inherited from the parent shell), so the verdict is +from the intended regime, not a silent default. + +- Verification: build **0 errors**; **4 968 / 0 / 1** across 17 suites; gate **PASSED** (8/8 `ok`); quiet-machine + state as documented (WSearch the only finding, privilege-limited). +- **Confirmation run (cleanly invoked, `dotnet run … -- --gate`, no wrapper quoting):** PASSED again, 8/8 `ok` — + raw INSERT 1,06× · raw READ 1,00× · raw UPDATE **1,19×** · raw DELETE 1,06× · default INSERT 1,13× · + default READ 1,20× · default UPDATE 1,12× · default DELETE 1,00× — with an empty stderr, so the first run's + quoting artefact is confirmed harmless and the verdict reproduces. +- Commit: this worklog addendum + the `PROJECT_STATUS` verification line, on + `perf/002-sqlite-update-delete-parity`, pushed. No `src`/test change was needed — this entry records a + verification, not a fix. + +### 2026-11-30 (session 90, addendum 2) — Release 2.2.1: version bump, docs to the current state, merge to `master` + +- Session: 90 (addendum 2 — owner instruction: "1 subminor omhoog", merge, documentation to the current state). +- Command(s): version bump of the 28 packable `src` projects + `Directory.Packages.props` (`SharpCoreDBVersion`; the missing `Search` and `HybridSearch` `PackageVersion` entries added) · `dotnet restore`/`build SharpCoreDB.CI.slnf -c Release /p:UseLocalProjectReferences=true` · focused `DocumentationConsistencyTests` + `SingleFileKeyMoveTests` + `SingleFileCollationTests` + `PageBasedAdapterTests` · `git merge --no-ff perf/002-sqlite-update-delete-parity` into `master`. +- Regime: GA SDK `11.0.100` / runtime `11.0.0`, Release/JIT. +- Verdict: **2.2.1 cut and merged — version metadata consistent across 28 packages, all documentation at the current state, build 0 errors, focused suites 45/45.** + +**The version bump.** `2.2.0` → `2.2.1` in the 28 packable `src` projects, `Directory.Packages.props`'s +`SharpCoreDBVersion`, and the one `SharpCoreDB.csproj` file-version block (`AssemblyVersion` stays `2.2.0.0`, +the convention `2.1.4` set: a patch does not move the assembly-binding line; `FileVersion` moves to +`2.2.1.0`). Two family members (`SharpCoreDB.Search`, `SharpCoreDB.HybridSearch`) had no central +`PackageVersion` entry — a real consumer-side gap, now closed, so the central list matches the 28 packable +projects. Tools/tests keep their own `2.1.0` — they are not packed. + +**Documentation, brought to the current state.** `README.md` (current release, previous-release, the two-line +table, a new "What's new in v2.2.1", the 30 install commands at 2.2.1), `docs/CHANGELOG.md` (`[Unreleased]` +→ `[2.2.1] - 2026-11-30` with the release summary and a fresh stub), `docs/PROJECT_STATUS.md` (version, +status, current-release narrative, history line), `docs/INDEX.md`, `docs/README.md`, +`docs/manual/performance.md`, and the package guides' install snippets (`docs/manual/quickstart.md`, +`docs/analytics`, `docs/cqrs`, `docs/graphrag`, `docs/scdb/PRODUCTION_GUIDE.md`, `docs/Vectors`). Historical +references (`[2.2.0]`, `2.1.0-RC.3_WHAT_CHANGED.md`, release notes) stay as they are. `AGENTS.md`'s line +description now names 2.2.1. + +- Verification: `SharpCoreDB.CI.slnf` **0 errors** after the bump; `DocumentationConsistencyTests` + + `SingleFileKeyMoveTests` + `SingleFileCollationTests` + `PageBasedAdapterTests` **45 / 0**. +- Merge: `perf/002-sqlite-update-delete-parity` → `master` with a `--no-ff` merge commit; pushing `master` runs + `.github/workflows/ci.yml` (build + tests + pack) and, after a green run, `publish.yml` publishes 2.2.1 to + NuGet.org through trusted publishing. +- NEXT: (1) watch the `CI/CD Pipeline` run on `master` and the `publish.yml` follow-up; (2) the tiered + coverage climb (engine 60 %, then a suite per optional package); (3) re-read SonarCloud after the master + push's re-analysis. + +- NEXT: (1) **owner-only** — merge. (2) The tiered coverage climb (engine 60 %, then a suite per optional + package). (3) Re-read SonarCloud after the push's re-analysis. + + line numbers show. (4) Optional — the `--pk` prepared DELETE/INSERT measurement arms. + diff --git a/docs/quality/MUTATION_TESTING.md b/docs/quality/MUTATION_TESTING.md index f3ec138e..ae79aa5e 100644 --- a/docs/quality/MUTATION_TESTING.md +++ b/docs/quality/MUTATION_TESTING.md @@ -173,6 +173,27 @@ mutant). Two consequences drive the matrix design: `SqlFunctions` is a good example of what mutation testing is for: a file with passing tests, 70 mutants no test reaches at all, and 16 wrong behaviours that a green suite accepts. That is the work queue. +**Re-run 2026-11-30 (session 90)** — same scope (`**/SqlFunctions.cs`), same committed config, same +`--test-case-filter "FullyQualifiedName~SqlFunctionsTests"`, but against the branch's current test suite +(3 060 core tests, 11 in the filter): + +```powershell +Set-Location tests\SharpCoreDB.Tests +dotnet tool run dotnet-stryker --output ../../artifacts/stryker-s90 --verbosity info --skip-version-check ` + --test-case-filter "FullyQualifiedName~SqlFunctionsTests" +``` + +| Mutants | Killed | Survived | NoCoverage | CompileError | Ignored | Score | Wall | +|---|---|---|---|---|---|---|---| +| 125 tested (119 in scope) | **33** | **22** | **70** | 396 (assembly-wide) | 2 754 (outside `mutate`) | **26.40 %** | **4 m 14 s** | + +The score is unchanged in substance: the same 33 mutants are killed and the same 70 lie in code no filtered +test reaches. **Six more survive now (22 vs 16)** — read that as the test *selection* having changed, not as a +regression in the file: the 2026-11-13 number came from a minimal 11-test harness whose filter matched +differently, and `perTest` only runs tests whose coverage includes the mutant. The report's survivor list +(`artifacts/stryker-s90/reports/mutation-report.{json,html}`) is the current work queue; the tool, the scope +and the runner are intact, and the run stays inside the `break: 0` threshold so it can never fail a pipeline. + ## Choosing the test host (measured 2026-11-13) The host matters, but not for the reason the first attempts assumed. Three runs, each with diff --git a/docs/quality/SONAR_AND_COVERAGE.md b/docs/quality/SONAR_AND_COVERAGE.md index 933e2515..1e23722f 100644 --- a/docs/quality/SONAR_AND_COVERAGE.md +++ b/docs/quality/SONAR_AND_COVERAGE.md @@ -9,6 +9,28 @@ owner action. It exists so the same investigation is not repeated and so the two Gate definitions live in SonarCloud, not in this repository. Current status on `master`: **OK**. +### Issue backlog (2026-11-30): 307 open findings, triaged by rule + +SonarCloud **automatic analysis** reports 307 open issues (all `CODE_SMELL`; no open bug or +vulnerability). Read by rule, and what was decided: + +| Rule | Count | Decision | +|---|---|---| +| `csharpsquid:S3776` cognitive complexity | 80 (+11 in PowerShell tooling) | **Accepted by design** in the SQL parser/generator and the SIMD dispatch chains. Splitting those methods would add call frames and indirection to hot paths the gates measure — the same reason the code already carries `// NOSONAR:S3776 - ` on `SingleFileTable.UpdateAffectedCount`, `UpdateBatch` and `Insert`. New methods that trip the rule get the same annotated suppression with the reason, not a refactor. | +| `csharpsquid:S1192` repeated string literal | 33 (17 in `SqlParser.InformationSchema.cs`, 14 in the comparative benchmark) | **Accepted**: the literals are the SQL standard's column names (`table_catalog`, `ordinal_position`, …). A constant would introduce a second name for the same standard token and make the row builders harder to read against the spec. | +| `csharpsquid:S3358` nested ternary | 28 | **Fixed (24 sites)** on 2026-11-30 across `Table.CRUD`, `Table.UniqueKeys`, `SqlOrderBy`, `SqlScalarExpression`, `SqlParser.DML`, `SqlParser.InformationSchema`, `SubqueryExecutor`, `SimdAggregates`, `PlatformOptimizations`, `SimdFilter`. The remainder are re-reported at stale line numbers (automatic analysis ran before the fixes; see below). | +| `csharpsquid:S3267` loop can be simplified with LINQ | 25 (mostly `SharpCoreDB.VectorSearch` and the search index) | **Rejected**: a LINQ rewrite allocates an enumerator and a delegate per row on paths the performance brief measures. S127 (below) and this rule are the two where "simpler" costs throughput. | +| `csharpsquid:S127` loop counter modified in body | 24 | **Accepted**: the SQL scanners advance the index over quotes, escapes and parentheses by design (`SqlLiteralScanner`, `SqlInPredicate`, `SqlLikePattern`, `PreparedStatements`). The rule's suggested rewrite would need an explicit state machine for the same result. | +| `csharpsquid:S4136` / `S2325` / `S108` / `S2094` / `S3871` / `S3376` / `S6588` / `S1125` / `S1481` / `S2589` / `S1066` / `S3928` / `S6667` / `S3218` / `S2696` / `S1939` / `S1133` / `S2933` / `S3247` / `S3626` / `S4144` / `S1694` / `S125` | 1–9 each | **Triaged individually**; several are stale (they name members that use instance state, e.g. `HasTriggersFor` reads `_triggers`/`_triggerLock`) and most of the rest sit in `tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs` or tooling scripts. The live ones are fixed as the files are touched. | +| `powershelldre:S8677` / `S8657` / `S8659`, `typescript:S7503` / `S9382`, `javascript:S9382`, `shell:S7677`, `githubactions:S7689`, `python:S6546`, `Web:S9379` | 1–18 each | Tooling scripts and the demo web pages, not the engine. Triaged when those files change. | + +**Why the line numbers are stale:** automatic analysis runs on a pushed commit, so its findings name +the revision it last saw. Several reported sites (e.g. `Table.CRUD.cs:2776`) now hold comments or +already-refactored code. Read a finding against the **current** file before acting on it — the +2026-11-30 pass fixed 24 real sites this way and left the rest for the next push's re-analysis. + +### Gate conditions (state on `master`) + | Condition | Threshold | Value | Note | |---|---|---|---| | New reliability rating | A | A | 1.0 | @@ -67,6 +89,50 @@ Two different systems report coverage today, and neither is Sonar: - **codecov.** `artifacts/coverage/*.cobertura.xml` is uploaded unpinned to codecov, which reports **42.51% of 59,211 lines** on `master` (2026-11-13) and enforces the 50%-of-new-lines patch status. +### Measured coverage (2026-11-30, `perf/002-sqlite-update-delete-parity`) + +`pwsh tools/measure-coverage.ps1 -Filter 'Category!=Debug&Category!=Manual&Category!=Performance&Category!=Allocation'` +run over the four CI suites, all green (3 060 + 255 + 116 + 96 tests): + +| Assembly | Lines | Covered | Rate | +|---|---|---|---| +| `SharpCoreDB` (engine) | 44,026 | 25,058 | **56.92%** | +| `SharpCoreDB.Functional.Linq2DB` | 225 | 212 | 94.22% | +| `SharpCoreDB.VectorSearch` | 2,302 | 1,934 | 84.01% | +| `SharpCoreDB.Graph` | 1,813 | 1,223 | 67.46% | +| `SharpCoreDB.Data.Provider` | 828 | 379 | 45.77% | +| `SharpCoreDB.EntityFrameworkCore` | 2,525 | 1,006 | 39.84% | +| `SharpCoreDB.Extensions` | 2,100 | 335 | 15.95% | +| `SharpCoreDB.Client` | 326 | 35 | 10.74% | +| `SharpCoreDB.Functional` | 456 | 45 | 9.87% | +| `SharpCoreDB.Distributed` | 5,660 | 475 | 8.39% | +| `SharpCoreDB.Graph.Advanced` | 1,629 | 64 | 3.93% | +| `SharpCoreDB.Client.Protocol` | 901 | 0 | 0.00% | +| **TOTAL** | **62,791** | **30,766** | **49.00%** | + +Baseline in this session was **47.89%** (30,104 / 62,864) with the same filter; the four suites added on +2026-11-30 (`SimdHelperTests`, `PageBasedAdapterTests`, `CorruptionDetectorTests`, `SingleFileKeyMoveTests`) +moved the engine assembly 55.32% → 56.92%. + +### The target: a tiered floor, because 90% of the whole repository is a different project + +A 90% whole-repository line rate would need **56,512 covered lines — 25,746 more than today**, i.e. more +than the entire engine assembly's current coverage again, across 12 assemblies and their own fixtures +(protocol, distributed, EF Core, Graph.Advanced). Written down honestly: that is a multi-month body of work, +not a session's, and a blanket number also hides where the risk is. The floors below are the actionable +version, and `tools/measure-coverage.ps1 -Floor` can enforce any of them per run: + +| Tier | Assemblies | Floor now | Next gate | +|---|---|---|---| +| Core engine | `SharpCoreDB` | **50%** (measured 56.92%) | 60% when the `SqlParser`/`Table` partials gain their case matrices | +| Adapters with real suites | `VectorSearch` 84.01%, `Graph` 67.46%, `Data.Provider` 45.77%, `EntityFrameworkCore` 39.84%, `Functional.Linq2DB` 94.22% | peak −2 (the codecov rule) | raise each as its own suite grows | +| Optional packages with little or no suite | `Distributed` 8.39%, `Graph.Advanced` 3.93%, `Extensions` 15.95%, `Functional` 9.87%, `Client`/`Client.Protocol` | none yet | a suite per package, then a floor | +| Generated / unreachable-branch code | `SharpCoreDBJsonContext` (source-generated), SIMD fallbacks off-CPU | excluded where codecov.yml excludes it | — | + +Read a rate as "lines executed", never as "behaviour pinned": mutation testing (`docs/quality/MUTATION_TESTING.md`) +is the second question, and a slice can be green at 70% line coverage and 30% mutation score. The two belong +together. + **Sonar has no coverage measures at all**, because the project is analysed by SonarCloud *automatic analysis*, which cannot import a coverage report. That is also why the gate's `new_coverage` condition shows an empty value: it is inert until coverage arrives — and, per its 80% threshold, it will start failing on new code the moment it diff --git a/docs/scdb/PRODUCTION_GUIDE.md b/docs/scdb/PRODUCTION_GUIDE.md index 9582c38e..610336f1 100644 --- a/docs/scdb/PRODUCTION_GUIDE.md +++ b/docs/scdb/PRODUCTION_GUIDE.md @@ -46,7 +46,7 @@ This guide covers deploying SharpCoreDB with the **SCDB (SharpCore DataBase)** s dotnet --version # Should show 11.0 or higher # NuGet Package -dotnet add package SharpCoreDB --version 2.2.0 +dotnet add package SharpCoreDB --version 2.2.1 ``` The 2.0.x servicing line on `release/v2.0` targets .NET 10 instead; match the runtime to the package diff --git a/docs/sharpcoredb-known-issues.md b/docs/sharpcoredb-known-issues.md index eb48754e..2b97b58e 100644 --- a/docs/sharpcoredb-known-issues.md +++ b/docs/sharpcoredb-known-issues.md @@ -13,7 +13,7 @@ SharpCoreDB repository: --- -## 1. 🔴 Table data is NOT encrypted even with `EnableBatchEncryption=true` +## 1. ✅ FIXED — Table data is NOT encrypted even with `EnableBatchEncryption=true` > ✅ **RESOLVED (opt-in).** Storage now supports per-record AES-256-GCM at-rest encryption > behind `DatabaseConfig.EnableAtRestRecordEncryption` — **default `true` since the v2.1 flip @@ -61,7 +61,7 @@ when `!noEncryption`, and `FlushBufferedAppends` should actually write the encry --- -## 2. 🟠 `Table.Insert` throws `ArgumentOutOfRangeException` after reopening a database +## 2. ✅ FIXED — `Table.Insert` throws `ArgumentOutOfRangeException` after reopening a database > ✅ **RESOLVED (verified 2026-10-10, 2.1.0).** `Database.Core.Load()` now pads *all seven* per-column > lists to `Columns.Count`, including the two this report found short: @@ -89,7 +89,7 @@ column count. --- -## 3. 🟠 Single-file (.scdb) mode has a no-op B-tree index +## 3. ✅ FIXED — Single-file (.scdb) mode has a no-op B-tree index > ✅ **RESOLVED (verified 2026-10-10, 2.1.0).** `SingleFileTable` now keeps a primary-key hash index > (`_pkIndex`, marked "Issue A1" in `src/SharpCoreDB/SingleFileTable.cs`) built from the PK column, so @@ -115,15 +115,26 @@ mode. --- -## 4. 🟡 No read-after-write consistency without an explicit `Flush()` +## 4. ✅ FIXED — No read-after-write consistency without an explicit `Flush()` -> ✅ **RESOLVED (verified 2026-10-10, 2.1.0).** `Database.ExecuteQuery` now flushes pending **batch** +> ✅ **RESOLVED in two layers.** (1) 2026-10-10, 2.1.0 — `Database.ExecuteQuery` flushes pending **batch** > writes before running the query (`src/SharpCoreDB/Database/Execution/Database.Execution.cs`, > "FIX (Known Issue 4)"), so rows written through `ITable.Insert` / `UpdateByPrimaryKey` are visible to > `FindByPrimaryKey` / `Select()` without an explicit `db.Flush()`. One asymmetry is deliberate and > documented in the code: a plain `_metadataDirty` flag is *not* flushed, because SQL `INSERT`s are > already visible in-memory on the default engine and a blanket metadata flush there costs more than it > buys. `IDatabase.Flush()` remains the explicit durability boundary. +> +> (2) **2026-11-30 — the storage-provider layer, found by the first `PageBasedAdapter` test ever written.** +> `SingleFileStorageProvider.WriteBlockAsync` only *queues* the bytes for the write-behind worker, and +> `ReadBlockAsync` read the file without draining the queue: a read issued in between saw the zero fill of +> an unwritten region, reported a checksum mismatch and *repaired the registry entry to match the zeros*, so +> the block was lost even to later reads (a `PageBasedAdapter` insert therefore failed with `Page full`). +> `ReadBlockAsync` now flushes pending writes before reading, and the pending-writes flag is cleared only +> when the queue is empty (a write enqueued during a flush was hidden from `HasPendingChanges`, letting +> `FlushAsync` early-return and leave it queued). Pinned by +> `PageBasedAdapterTests.Insert_ThenRead_RoundTripsTheRecord` and `Reopen_SeesThePersistedTableAndItsRecords`; +> see `docs/CHANGELOG.md` `[Unreleased] → Fixed`. **Location:** `src/SharpCoreDB/Database/Execution/Database.Execution.cs` @@ -143,7 +154,7 @@ explicit `IDatabase.Flush()` perform.) --- -## 5. 🟡 SQL parameter validation does not match `@`-prefixed keys +## 5. ✅ FIXED — SQL parameter validation does not match `@`-prefixed keys > ✅ **RESOLVED (verified 2026-10-10, 2.1.0).** `SqlQueryValidator` normalises keys before comparing: > `NormalizeKey` strips a leading `@` or `:` (its comment states "a @-prefixed key and an unprefixed key @@ -166,7 +177,7 @@ its behavior is consistent with `SqlParser.ResolveParameter`. --- -## 6. 🟡 `INTEGER` columns map to Int32 instead of Int64 +## 6. 🟡 `INTEGER` columns map to Int32 instead of Int64 (opt-in exists for SQLite affinity) > ⚠️ **STILL TRUE BY DEFAULT, with an opt-in (verified 2026-10-10, 2.1.0).** `INTEGER` → > `DataType.Integer` (Int32) remains the default, for backward compatibility with existing databases and @@ -474,9 +485,20 @@ persisted as `ColumnFlags.Unique`, but no write path checks it. **Why it is open --- -## 10. 🟡 OPEN (owner decision) — Single-file storage ignores a column's declared `COLLATE` - -> ⚠️ **STILL TRUE (verified 2026-11-17), pending an owner decision** on the column-entry format extension below. +## 10. ✅ FIXED (plan 009, D2=A) — Single-file storage ignores a column's declared `COLLATE` + +> ✅ **FIXED (2026-11-30, `specs/009-owner-decisions` D2=A).** The owner approved the format extension: +> the collation is persisted in free bits 8–11 of `ColumnDefinitionEntry.Flags` (a file written before +> decodes to 0 = BINARY, i.e. its old behaviour, so old files keep working). `COLLATE NOCASE | RTRIM | +> BINARY | UNICODE` is parsed by the single-file DDL, reloaded on reopen, honoured by the WHERE evaluator +> (`=`, ranges, BETWEEN — the ordinal fast path is bypassed for such a column), by ORDER BY, and by key +> uniqueness (the tuple key canonicalises through `CanonicalKeyPart`: upper-invariant for NOCASE, trimmed +> for RTRIM, culture-upper for UNICODE). The last part was still wrong after the first delivery: RTRIM +> compared ordinally and a NOCASE key accepted `'aa'` and `'AA'` as distinct rows while `WHERE k = 'AA'` +> matched both — fixed on 2026-11-30. Pinned by `SingleFileCollationTests` (WHERE equality/range/BETWEEN, +> BINARY staying case-sensitive, ORDER BY, RTRIM, reopen) and the `NoCaseKey_*` / `RTrimKey_*` cases in +> `SingleFileKeyMoveTests`. The previously skipped +> `SingleTableOrderByTests.OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively` runs and passes. Found 2026-11-17. On single-file storage `CREATE TABLE t (name TEXT COLLATE NOCASE)` behaves as BINARY: `WHERE name = 'X'` does not match `'x'`, and `ORDER BY name` sorts case-sensitively. Directory storage honours it. @@ -485,25 +507,26 @@ Three gaps make it up: the single-file `CREATE TABLE` parser (`DatabaseExtension single-file column entry (`ColumnDefinitionEntry`, 48 bytes) has no collation field; and the single-file WHERE evaluator (`SingleFileTable.EvaluateSingleCondition`) is static and has no collation support. -**Decision needed:** persisting the collation means claiming spare bits of `ColumnDefinitionEntry.Flags` (bits 8–11 -would hold `CollationType`; a file written before reads as 0 = BINARY, today's behaviour). That is compatible with -`docs/manual/upgrade-and-downgrade.md` — old files keep working, downgrade is already unsupported — but it is an -on-disk format extension. A `Locale(…)` collation would still need a name field. Pinned by the skipped -`SingleTableOrderByTests.OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively`. +**Decision needed (given):** persisting the collation meant claiming spare bits of `ColumnDefinitionEntry.Flags` (bits 8–11 +hold `CollationType`; a file written before reads as 0 = BINARY, today's behaviour). That is compatible with +`docs/manual/upgrade-and-downgrade.md` — old files keep working, downgrade is already unsupported. A +`Locale(…)` collation would still need a name field. --- -## 11. 🔴 OPEN (owner decision) — PRIMARY KEY uniqueness and composite keys +## 11. ✅ FIXED (plan 009, D1=A) — PRIMARY KEY uniqueness and composite keys -> ⚠️ **STILL TRUE for single-file storage (verified 2026-11-17), pending an owner decision** on modelling composite -> keys there. Single-file enforcement was implemented and backed out because of the compatibility hazard below. -> **Directory storage is fixed for tables created from `fix/composite-keys-update-atomicity-orderby` on:** a composite -> key — table-level `PRIMARY KEY (a, b)`, `CONSTRAINT name PRIMARY KEY (a, b)`, or `PRIMARY KEY` written on several -> columns as EF Core's `EnsureCreated` writes it — is enforced as SQLite enforces it in a rowid table: a UNIQUE -> constraint over all its columns, the row id staying the storage key (`CompositeKeyTests`). A directory table created -> earlier keeps the key it was created with (its last key column; the other columns were never recorded) and needs to -> be re-created to drop the false violations. The table-level form was worse than described below: it was read as a -> column called `PRIMARY` (or `CONSTRAINT`) that became the key, always NULL, so such a table held one row. +> ✅ **FIXED (2026-11-30, `specs/009-owner-decisions` D1=A).** Single-file tables created by this version +> persist **every** key column and set a marker bit (6) in the table entry, and the key tuple's uniqueness is +> enforced on INSERT, multi-row INSERT and every UPDATE path; files written before the marker stay unenforced +> (their key columns were never recorded, and enforcing there could reject legitimate rows). A composite key +> is enforced as SQLite enforces it in a rowid table: a UNIQUE constraint over all its columns. The 2026-11-30 +> follow-up closed the remaining write paths and made the check atomic: all four UPDATE paths validate the +> prospective tuple **before** the first write (one shared `ApplyMatchedUpdates`), `UpdateByPrimaryKey` had no +> uniqueness check at all, and `DELETE FROM t` without a WHERE clause left every key claimed. Pinned by the +> enabled single-file cases in `PrimaryKeyUniquenessTests`, `CompositeKeyTests` (all modes) and +> `SingleFileKeyMoveTests` (17 cases, 9 red before). Directory storage was fixed on +> `fix/composite-keys-update-atomicity-orderby` earlier (see below). Found 2026-11-17 while fixing single-file constraint enforcement. @@ -535,11 +558,11 @@ single-file cases in `PrimaryKeyUniquenessTests`. | 1 | Table data not encrypted | 🔴 High | Provider-level AES-256-GCM | **Fixed** — per-record AES-256-GCM on by default (`EnableAtRestRecordEncryption`), flippable since 2026-09-13 | | 2 | `Table.Insert` AOORE after reopen | 🟠 Medium | `RepairTableSchemaLists()` | **Fixed** — `Load()` pads every per-column list | | 3 | Single-file no-op index | 🟠 Medium | Directory mode forced | **Fixed** — `SingleFileTable` keeps a PK hash index | -| 4 | No read-after-write flush | 🟡 Low | Flush calls in provider | **Fixed** — `ExecuteQuery` flushes pending batch writes | +| 4 | No read-after-write flush | 🟡 Low | Flush calls in provider | **Fixed in two layers** — `ExecuteQuery` flushes pending batch writes; the storage provider drains its write-behind queue before a block read (§4) | | 5 | SQL validator `@` prefix | 🟡 Low | Keys without `@` prefix | **Fixed** — `NormalizeKey` strips `@` / `:` | | 6 | INTEGER → Int32 | 🟡 Low | `BIGINT` columns | **Still the default** — opt in with `UseSqliteIntegerAffinity` | | 7 | Bound text re-parsed as SQL | 🔴 High | Write through `ITable.Insert` instead of SQL text | **Fixed** — one `SqlLiteralScanner` (SQL/SQLite: a doubled quote is one quote, a backslash is data) behind every scanner; `ParseValue` strips one pair and un-collapses doubling; a tuple with too many values is rejected. `ParameterLiteralRoundTripTests` 74/74 | -| 8 | PK-changing UPDATE loses/duplicates a row | 🔴 High | — | **Fixed on directory storage** — every UPDATE path validates the new key first; single-file part tracked in §11 | -| 9 | Column `UNIQUE` not enforced | 🟠 Medium | — | **Fixed on directory storage** — automatic unique index, composite `UNIQUE (a, b)` included; single-file still open (format decision, §10/§11) | -| 10 | Single-file ignores `COLLATE` | 🟡 Low | — | **Open, owner decision** — needs a column-entry format extension (§10) | -| 11 | PK uniqueness / composite keys | 🔴 High | — | **Fixed on directory storage for new tables** (composite key = UNIQUE over its columns); **open, owner decision** for single-file storage, which enforces no PK uniqueness (§11) | \ No newline at end of file +| 8 | PK-changing UPDATE loses/duplicates a row | 🔴 High | — | **Fixed on both storage modes** — every UPDATE path validates the prospective key before writing; single-file moved to one shared atomic applier on 2026-11-30 (`ApplyMatchedUpdates`) | +| 9 | Column `UNIQUE` not enforced | 🟠 Medium | — | **Fixed on directory storage** — automatic unique index, composite `UNIQUE (a, b)` included; single-file column-level `UNIQUE` remains open (PK/composite keys are fixed, §11) | +| 10 | Single-file ignores `COLLATE` | 🟡 Low | — | **Fixed (D2=A)** — parsed, persisted (flags bits 8–11), reloaded, honoured in WHERE/ORDER BY/keys; RTRIM and collation-aware key uniqueness added 2026-11-30 (§10) | +| 11 | PK uniqueness / composite keys | 🔴 High | — | **Fixed (D1=A)** on both modes for tables created by this version — every key column persisted + marker bit, tuple uniqueness on INSERT/multi-row/UPDATE; older files stay unenforced by design (§11) | \ No newline at end of file diff --git a/specs/002-sqlite-update-delete-parity/plan.md b/specs/002-sqlite-update-delete-parity/plan.md new file mode 100644 index 00000000..cfe29bcb --- /dev/null +++ b/specs/002-sqlite-update-delete-parity/plan.md @@ -0,0 +1,93 @@ +# Implementation Plan: Close the SQLite UPDATE/DELETE gap + +**Branch**: `[002-sqlite-update-delete-parity]` | **Date**: 2026-11-29 | **Spec**: `specs/002-sqlite-update-delete-parity/spec.md` + +**Input**: Feature specification from `/specs/002-sqlite-update-delete-parity/spec.md` + +## Summary + +The only column behind SQLite on the fair-PK arm is UPDATE (0,73×) and DELETE (0,82×), and their one +structural remaining cost is the per-statement batch classification: `TryScanCanonicalDml` + +`TryParseUpdateForBatch` (`Database.Batch.cs`) materialise 5 strings + a `Dictionary` +(~432 B, ~0,6–0,8 µs) per statement, which the UPDATE core then consumes. The fix replaces that with a +**deferred-span / single-assignment** representation (C# 15 `ref struct` over the statement + a typed +key/value), threading a single-assignment shape into `UpdateMultiplePrepared`/`UpdateMultipleCore`, so +the `Dictionary` and the value strings are only materialised on the `SelectInternal` fallback. It is +default-off behind a `DatabaseConfig` flag and ships only on a measured win. + +## Technical Context + +**Language/Version**: C# 15 preview / `net11.0` (SDK `11.0.100` pinned in `global.json`) + +**Primary Dependencies**: `System.Runtime.Intrinsics` (SIMD keyword scan), `System.Buffers`/`SearchValues` + +**Storage**: AppendOnly fixed-width (the `--pk` arm) and PageBased; no format change + +**Testing**: Microsoft.Testing.Platform / `xunit.v3`; allocation canary via `GC.GetAllocatedBytesForCurrentThread` + +**Target Platform**: Windows / Linux / macOS, embedded engine + +**Constraints**: no encryption/durability/format change; no `System.Numerics.Vector` (SIMD_STANDARDS) + +## Constitution Check + +- **I. Security & Durability** — PASS. Classification-only; no WAL/format/encryption change. +- **II. SQLite Compatibility** — PASS. No SQL surface change; a full statement/parameter/type matrix guards the refactor. +- **III. Measured Performance, Honest** — PASS. Ratios only, same-run SQLite, encrypted + `NoEncryptMode` side by side; the wall is noise-dominated, so the deterministic allocation column carries the verdict. +- **IV. Verified Quality** — PASS. Allocation canary (red→green), wider suite, standing canaries, `--gate` capability. +- **V. Optional/Modular** — PASS. New flag is default-off; no public API break. + +No violations — Complexity Tracking empty. + +## Project Structure + +```text +specs/002-sqlite-update-delete-parity/ +├── spec.md # specification +├── plan.md # this file +└── tasks.md # task breakdown + +src/SharpCoreDB/ +├── Database/Execution/Database.Batch.cs # TryScanCanonicalDml / TryParseUpdateForBatch / TryParseDeleteForBatch +├── DataStructures/Table.CRUD.cs # UpdateMultiplePrepared / UpdateMultipleCore / TryBulkUpdateContiguousFixedWidth +└── DatabaseConfig.cs # default-off flag + +tests/SharpCoreDB.Tests/Net11/ +└── BatchUpdateClassificationAllocationTests.cs # the allocation canary +``` + +## Phase 0 — Research (resolved) + +- The identity-remap INSERT fast path is refuted (894→891 B/row); `new Dictionary(1)` saves nothing; `UnquoteSqlLiteral` is already allocation-free; flipping the FW layout default is a measured −24 % regression (forbidden). Do not retry these. +- Session 76 already moved the WHERE key "claim while spans"; the remaining allocation is the `Dictionary` + `table`/`setCol`/`setValRaw`/`whereCol`/`whereValRaw` strings. +- The DELETE per-key index cost is already removed (`EnableDeferredDeleteIndexes`); DELETE shares this classification cost. + +## Phase 1 — Design + +1. Add `DatabaseConfig.EnableDeferredSpanClassification` (default **false**). +2. `TryScanCanonicalDml` returns `ReadOnlySpan` halves; `TryParseUpdateForBatch` materialises strings only where required (table/column lookups) and, when the flag is on, builds an `UpdateAssignment` (single `string Column, object Value`) instead of a `Dictionary`. +3. Add `UpdateMultiplePreparedSingle` / a single-assignment overload of `UpdateMultipleCore` that runs the identical body; the fallback materialises the `Dictionary` only when `SelectInternal` is reached. +4. SIMD keyword/quote scans (`TryConsumeKeyword`, `TryReadLiteralUntilWhere`) with `Vector128/256` + scalar tail (no AVX-512: statements are < 1024 chars) — as an opt-in micro-opt behind its own measurement. + +## Complexity Tracking + +*(No constitution violations.)* + +## Measured baseline (this session, same build, `--pk-profile`) + +`UPDATE … WHERE id = ?` — 10.000 statements in one `ExecuteBatchSQL` over 100.000 rows, AppendOnly +fixed-width plaintext: + +| stage | total ms | calls | share | alloc | B/call | +|---|---:|---:|---:|---:|---:| +| **parse (classification)** | 27,9 | 10.000 | **35,0 %** | 4,7 MB | **497** | +| row-locate (whole-file snapshot) | 24,0 | 1 | 30,2 % | 6,2 MB | 6.462.272 | + +The timed `--pk` arm on the same box reads UPDATE **548.970 ops/s (1,82 µs/update)**, DELETE 636.395, +INSERT 230.983, READ 138.795, against a same-run SQLite of 752.439 / 780.019 / 171.670 / 107.380. The +`parse` stage being the largest *attributable* per-statement share — and 497 B/call matching the plan's +recorded ~500 B/statement — is what makes the deferred-span classification the target (and why the +whole-file `row-locate` snapshot is a separate, one-call cost, not a per-operation one). ⚠️ The profiled +pass dilates `parse` (profiler overhead); the timed arm is the ratio source, the stage shares the +attribution — never mix the two. + diff --git a/specs/002-sqlite-update-delete-parity/spec.md b/specs/002-sqlite-update-delete-parity/spec.md new file mode 100644 index 00000000..b546de4e --- /dev/null +++ b/specs/002-sqlite-update-delete-parity/spec.md @@ -0,0 +1,101 @@ +# Feature Specification: Close the SQLite UPDATE/DELETE gap (deferred-span batch classification) + +**Feature Branch**: `[002-sqlite-update-delete-parity]` + +**Created**: 2026-11-29 + +**Status**: Plan approved; Phase A (spec + canary) delivered, Phase B (core refactor) gated + +**Input**: Owner request: close the SQLite UPDATE/DELETE gap without regressing INSERT/READ, using +.NET 11 / C# 15 features. Grounded in `docs/performance/INSERT_UPDATE_PERFORMANCE_PLAN.md` (§4/§6/§7/§9/§11), +`docs/performance/NET11_C15_PERFORMANCE_PLAN.md` (§2/§4 P2), and the worklog queue head (session 87: +"deferred-span classification for UPDATE, gated on a measured timing win"). + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Close the UPDATE gap on the fair-PK arm (Priority: P1) + +On the fair-PK fixed-width plaintext arm (`--pk`), UPDATE is the only column behind SQLite on the +current build (measured 2026-11-29: **548.970 vs 752.439 ops/s, 0,73×**, same-run SQLite). A caller +issuing a batch of canonical `UPDATE t SET c = WHERE k = ` statements pays a per-statement +classification that materialises 5 strings + a `Dictionary` (~432 B, ~0,6–0,8 µs), which +is the largest attributable per-statement stage. + +**Why this priority**: it is the single column the owner called out and the only structural lever the +plan still carries (NET11 P2). + +**Independent Test**: `--pk` (FW plaintext) UPDATE ratio ≥ 1,0× against the same-run SQLite arm, +median-of-3, with INSERT and READ staying ≥ 1,0×; plus an allocation canary proving the per-statement +classification allocation drops. + +**Acceptance Scenarios**: + +1. **Given** a batch of canonical single-column UPDATE statements, **When** it is dispatched, **Then** the classifier no longer materialises a per-statement `Dictionary` on the canonical path. +2. **Given** the same batch shape, **When** the change is measured against the same-run SQLite arm, **Then** the UPDATE ratio is ≥ 1,0× and INSERT/READ are ≥ 1,0×. + +--- + +### User Story 2 - Close the DELETE gap (Priority: P1) + +DELETE shares the same per-statement classification floor (measured **636.395 vs 780.019, 0,82×**). +Its per-key index cost was already removed by `EnableDeferredDeleteIndexes`; what remains is the same +classification cost. + +**Why this priority**: same lever as US1, same acceptance shape. + +**Independent Test**: `--pk` DELETE ratio ≥ 1,0×, same protocol. + +**Acceptance Scenarios**: + +1. **Given** a batch of canonical `DELETE FROM t WHERE k = ` statements, **When** dispatched, **Then** no per-statement `Dictionary`/string blow-up occurs on the canonical path. +2. **Given** the measure, **Then** the DELETE ratio is ≥ 1,0× with INSERT/READ unregressed. + +--- + +### User Story 3 - Prove the lever with a deterministic allocation canary (Priority: P1) + +The wall-clock on this box is noise-dominated (§2 of both perf plans); the deterministic column is +per-statement allocation. The change is proven by a canary in the `InsertBatchAllocationTests` style. + +**Why this priority**: the plan's own rail — "ship only on a measured timing win; allocation alone is +not enough for the verdict, but it is the deterministic floor". + +**Independent Test**: `BatchUpdateClassificationAllocationTests` reads `GC.GetAllocatedBytesForCurrentThread()` +around a warmed batch of UPDATE statements and asserts a B/statement ceiling. + +**Acceptance Scenarios**: + +1. **Given** a warmed batch of 2.000 canonical UPDATE statements, **When** measured, **Then** the allocation is at most the pinned ceiling (and lower after P2 lands). + +--- + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: The batch classifier (`Database.Batch.cs` — `TryScanCanonicalDml`, `TryParseUpdateForBatch`, `TryParseDeleteForBatch`) MUST hand the UPDATE/DELETE core a **deferred-span / single-assignment** representation on the canonical path, materialising a `Dictionary`/strings only where the core genuinely needs them. +- **FR-002**: The change MUST be **default-off behind a `DatabaseConfig` flag** and reproduce the current behaviour byte-for-byte when off (full statement/parameter/type matrix). +- **FR-003**: The change MUST NOT alter storage format, encryption, durability or WAL semantics (constitution §I; NET11 non-goals §6). +- **FR-004**: The change MUST keep INSERT and READ at ≥ 1,0× vs the same-run SQLite arm (no regression). +- **FR-005**: A deterministic allocation canary MUST pin the per-statement classification allocation. + +### Key Entities + +- **Canonical DML statement**: `UPDATE SET = WHERE = ` / `DELETE FROM WHERE = ` — the shape the `--pk` arm issues. +- **Deferred-span classification**: a `ref struct` carrying `ReadOnlySpan` halves of the statement (C# 15 `ref` fields) + the typed key value; strings materialised lazily. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: `--pk` FW plaintext UPDATE ratio ≥ 1,0× against same-run SQLite (was 0,73×), median-of-3; INSERT and READ ≥ 1,0×. +- **SC-002**: `--pk` DELETE ratio ≥ 1,0× (was 0,82×), same protocol. +- **SC-003**: Encrypted (default) and `NoEncryptMode=true` reported side by side, never one alone (constitution §III). +- **SC-004**: The allocation canary passes; the wider core suite and the standing canaries stay green; `--gate` PASSED (capability statistic). +- **SC-005**: A change that measures "the same" is recorded as **not shipped**, never as a silent micro-change. + +## Assumptions + +- The wall-clock win is expected to be **single-digit %** (allocation ~12 % of per-statement cost per NET11 §2), so the verdict here is the **allocation** column plus the same-run ratio — not an absolute ops/s claim (constitution §III: ratios only). +- The full core refactor (threading a single-assignment struct through `UpdateMultiplePrepared` / `UpdateMultipleCore` / `TryBulkUpdateContiguousFixedWidth`) is a multi-step, gated item; this feature ships the plan + canary first and lands the refactor only on a measured win. + diff --git a/specs/002-sqlite-update-delete-parity/tasks.md b/specs/002-sqlite-update-delete-parity/tasks.md new file mode 100644 index 00000000..8083820c --- /dev/null +++ b/specs/002-sqlite-update-delete-parity/tasks.md @@ -0,0 +1,137 @@ +# Tasks: Close the SQLite UPDATE/DELETE gap + +**Input**: `/specs/002-sqlite-update-delete-parity/{spec,plan}.md` + +**Tests**: Allocation canary is required (deterministic floor). Wall-clock is noise-dominated; the +allocation column + same-run ratio carry the verdict. + +## Phase 1: Setup / measurement + +- [x] T001 Capture the same-run baseline: `--pk` FW plaintext INSERT 230.983 / READ 138.795 / UPDATE 548.970 (0,73×) / DELETE 636.395 (0,82×) vs SQLite 171.670 / 107.380 / 752.439 / 780.019. +- [ ] T002 [P] Record the `parse` stage share on both arms via `--pk-profile` (`SHARPCOREDB_WRITE_PROFILE`) as the before-number. + +## Phase 2: Foundational + +- [x] T003 Add `BatchUpdateClassificationAllocationTests` (allocation canary, `[Trait("Category","Allocation")]`) pinning the current B/statement for a warmed 2.000-statement canonical UPDATE batch. +- [ ] T004 Add `DatabaseConfig.EnableDeferredSpanClassification` (default false) + XML doc (default-off, format-neutral). + +## Phase 3: US3 — deferred-span classification (P1) + +- [ ] T005 [US3] Make `TryScanCanonicalDml` return `ReadOnlySpan` halves (C# 15 `ref struct` result); callers materialise only the strings the lookup needs. +- [ ] T006 [US3] Add the single-assignment path: `UpdateAssignment(string Column, object Value)` + `UpdateMultiplePreparedSingle`, running the identical core body; the `Dictionary` is materialised only on the `SelectInternal` fallback. +- [ ] T007 [US3] Wire the classifier to the single-assignment path when `EnableDeferredSpanClassification` is on; the text route is unchanged when off. +- [ ] T008 [US3] Prove the allocation canary red→green: ceiling lowered to the post-change B/statement. + +### Tests for US1/US2 (correctness matrix) ⚠️ + +- [ ] T009 [P] [US1] Full statement/parameter/type matrix: single/multi-column SET, quoted/bracketed keys, all operators (`=`,`<>`,`<`,`>`), unquoted literals, computed SET, missing WHERE — on columnar, page-based and single-file storage, with the flag on and off. +- [ ] T010 [P] [US2] DELETE matrix: canonical and non-canonical (`WHERE id IN`, `WHERE col = `), deferred-index contract preserved (`DeferredDeleteIndexTests`). + +## Phase 4: Measurement & shipping gate + +- [ ] T011 [US1] `--pk` + `--pk-default` interleaved A/B (flag on/off), median-of-3: UPDATE ratio ≥ 1,0×, INSERT/READ ≥ 1,0×; encrypted and `NoEncryptMode` side by side. +- [ ] T012 Ship only on a measured win; if "the same", record as **not shipped** (NET11 rail) and keep the canary. + +## Phase 5: Polish + +- [ ] T013 Standing canaries green: `ReopenRoundTripMatrixTests`, `FormatCompatPolicyTests`, `FixedWidthBulkUpdateTests`, `FixedWidthBulkDeleteTests`, `FixedWidthPatchTests`, `WritePathProfilerTests`, `FixedWidthInlineValueTests`, `SingleFileDirectoryParityTests`. +- [ ] T014 `--gate` PASSED (capability statistic); wider core suite green. +- [ ] T015 Worklog entry with `Session:`/`Verdict:`/`NEXT:` (append-only). + +## Dependencies + +T001→T002; T003/T004 foundational; T005→T006→T007→T008; T009/T010 gate correctness before T011; T011 gates T012; T013–T015 last. + +--- + +## Phase 6 (execution-ready design, verified this session) + +**Verified facts that make the refactor safe in principle:** +- The `updates` dictionary is **read-only** on the `UpdateMultipleCore` path — a grep for `updates.(Remove|Clear|Add|TryAdd)` and `updates[…] =` over `Table.CRUD.cs` returns **nothing**. So widening the parameter type from `Dictionary` to `IReadOnlyDictionary` is source-compatible for every `Dictionary` producer. +- The only per-statement heap allocation on the canonical UPDATE path is `new Dictionary { [setCol] = parsed }` (~216–240 B of the ~497 B `parse` allocation). The 5 strings and the boxed value remain necessary (they are used as lookup keys / typed values). + +**Minimal viable design — widen, then add a value-type-free single-item view:** +1. Add `DatabaseConfig.EnableDeferredSpanClassification` (default **false**). +2. Widen the tuple's `Updates` field from `Dictionary` to `IReadOnlyDictionary` at: + - `Database.Batch.cs:1431` (`UpdatesByTable`), `:1519` (`BatchOperationList<…>`), the `TryParseUpdateForBatch` out-tuple and its three `operation = …` assignments. + - `Table.CRUD.cs:2415`, `:2446` (`UpdateMultiplePrepared`), `:2473`, `:2516` (`UpdateMultipleCore`), `:3171` (`TryBulkUpdateContiguousFixedWidth`). +3. Widen the helper params on the `UpdateMultipleCore` path to `IReadOnlyDictionary`: `TryPatchOrSerializeRow` (:1978), `TryOverwriteFixedWidthInPlace`, `TryOverwriteFieldsInPlaceActual`, `TryDecodeIndexedOldValues`, `TryCaptureIndexedOldValues`. Leave the **public** `Update`/`UpdateAffectedCount`/`UpdateByPrimaryKey`/`UpdateMultiple` input signatures as `Dictionary` (widening a callee is safe; changing a public API is not). +4. Add `internal sealed class SingleItemUpdate : IReadOnlyDictionary` (Count=1, one Key/Value, `ContainsKey`/`TryGetValue`/`Keys`/`Values`/`this[]`/`GetEnumerator`) — ~80 B vs a `Dictionary`'s ~216 B. +5. In `TryParseUpdateForBatch`, when the flag is on, pass `new SingleItemUpdate(setCol, parsed ?? DBNull.Value)` instead of the `Dictionary`; the fallback (`SelectInternal`) materialises a `Dictionary` only when it actually runs. +6. Prove with `--pk-profile` that `parse`'s `B/call` drops (deterministic — no quiet machine needed for the allocation column), and with `--pk` interleaved A/B for the ratio (quiet machine for the verdict). + +**Honest predicted outcome:** the allocation drops (~+130 B/statement = ~27 % of `parse` allocation), but `parse` is ~35 % of the *profiled* pass and allocation is ~12 % of per-statement cost (NET11 §2), so the wall win is low-single-digit and likely inside this box's noise. Per the NET11 rail, that is a **“not shipped”** outcome unless a quiet-machine A/B shows a real timing win. The change is therefore only worth landing if the allocation canary is treated as the accepted deliverable (the same basis P1's insert work was accepted on). + +**Why this is not landed in the current turn:** it is ~15 coordinated signature changes across the shared UPDATE core + dispatcher, and a blind landing risks the `ReopenRoundTripMatrixTests` / `format` / durability canaries for a predicted-neutral timing result. The baseline is green (27/27 of the fixed-width + reopen canaries, this session), so the tree is clean for the dedicated session. + +### Phase 6a — what the live attempt revealed (2026-11-29, reverted) + +A mechanical `Dictionary` → `IReadOnlyDictionary` widening was attempted and **reverted** (tree clean, build green). It confirmed the refactor is mechanical but genuinely cascading, and pinned the exact edit list for the dedicated session: + +1. **The widening cascades through more helpers than the plan first listed.** Beyond `TryPatchOrSerializeRow` / `TryOverwriteFixedWidthInPlace` / `TryOverwriteFieldsInPlaceActual` / `TryCaptureIndexedOldValues` / `TryDecodeIndexedOldValues` (`Table.Serialization.cs`), it also reaches `TryResolveRuntimeOffsets`, `AllUpdatedColumnsFit` (`Table.Serialization.cs`), and `ValidateBatchKeyChanges`, `ValidateBatchKeyChangesCore`, `UpdateTouchesKeyColumns`, `TryGetUpdateValue` plus the local `changes` list type (`Table.UniqueKeys.cs`). Each widened signature reveals the next. +2. **Variance blocks widening the adapter INPUT signatures.** `IReadOnlyList<(… Dictionary Updates)>` is not `IReadOnlyList<(… IReadOnlyDictionary Updates)>` (value-tuple + generic invariance). So `UpdateMultiple` and `UpdateMultipleStructured` keep `Dictionary` inputs and convert element-wise when building the internal `structured` list. +3. **The public `ITable` surface must stay `Dictionary`.** `Update`, `UpdateAffectedCount`, `UpdateByPrimaryKey` implement `ITable`; widening them breaks the interface. Widen only private/internal helpers (a widened *callee* accepts a `Dictionary` argument). +4. **`BatchClassification.UpdatesByTable` and the `BatchOperationList<…>` element type** and the `TryParseUpdateForBatch` out-tuple must widen together (`Database.Batch.cs`), or the bucket add is a type mismatch. + +The concrete, verified sequence and the `SingleItemUpdate` addition are therefore a focused session, not a drive-by. This is the same conclusion `NET11_C15_PERFORMANCE_PLAN.md` P2 records. + +### Phase 7 — a SAFE lever was found and landed (2026-11-29) + +A deeper read of the full `--pk-profile` (all stages, not just the top two) overturned the "whole-file snapshot" hypothesis and found a real, contained win in the **contiguous fixed-width UPDATE patch** (`TryBulkUpdateContiguousFixedWidth`): + +- **The whole-file snapshot is a dead end for this arm.** `TryLoadWholeFileForUpdatePatch` returns `(null, false)` immediately when `_fixedWidthRecords` is set, so a fixed-width `--pk` update never loads it (the profile's `row-snapshot` is 0,2 %). It only serves the legacy variable-length layout. +- **The `row-locate` 30,7 % stage allocates ~one record per row for nothing.** The patch loop allocated a fresh `new byte[layout.FixedSize]` per row *and* `TryOverwriteFixedWidthInPlace` allocated a second copy. The per-row buffer is required (the storage layer buffers the array **reference** — `BufferOrWriteOverwriteInPlace` stores `record`, and plaintext `EncryptRecord` returns the same instance, so a shared scratch corrupts every row — caught by 3 canaries), but the **second** copy is not. +- **The gate ran an O(columns) linear scan per statement** (`for c … Columns[c].Equals(updateKey, OrdinalIgnoreCase)`), while the shared `GetColumnIndexCache()` already exists — 10.000 × columns string compares per batch. + +**Landed (safe, contained):** a span-in-place `TryOverwriteFixedWidthInPlaceSpan` (patches the caller's per-row buffer, no second `byte[]`) + the O(1) column cache in the gate. + +**Measured:** +- Deterministic: `row-locate` allocation **6,41 MB → 5,05 MB per batch (−21 %)**; one record alloc per row instead of two. +- `--pk` FW plaintext UPDATE **0,73× → 0,83–0,89×** across clean runs (UPDATE 548.970 → 632.755 ops/s on the cleanest run; SQLite reference 710–726K, noisy as always — needs a quiet-machine A/B to certify the exact ratio). +- INSERT 0,9× gap (≈1,1× **ahead**) and READ 0,7–1,0× — **no regression**. +- Correctness: canaries **53/53**, wider suite **3085 / 0 failed / 22 skipped**. + +The bigger remaining levers (per the same profile) are **`parse`/classification 34,5 %** (the deferred-span P2, still predicted-neutral on wall) and **`commit`/`commit-overswrites` ~27 %** (the buffered-overwrite flush — a durability/write-volume trade, not a free win). + +### Phase 8 — quiet-machine A/B (2026-11-29) + +Box quieted with `scripts/quiet-machine.ps1` (`-Apply` stopped the build servers; WSearch is the one standing finding that needs elevation and does not block a verdict). Interleaved A/B, two binaries (fixed vs pre-fix), 3 pairs, `--pk`, FW plaintext UPDATE gap vs same-run SQLite (lower = SharpCoreDB faster): + +| pair | fixed | prefix | +|---|---:|---:| +| 1 | 1,4× | 1,4× | +| 2 | **1,2×** | 1,3× | +| 3 | **1,1×** | 1,5× | +| **median** | **1,2×** | **1,4×** | + +The fixed arm is better in 2 of 3 pairs and tied in the third — a consistent direction on top of the deterministic −21 % allocation. The box still has a 1,1–1,5× per-run spread (WSearch), so the exact ratio wants more reps, but the sign is not in doubt: the plaintext UPDATE gap moved ~1,4× → ~1,2× (≈0,71× → ≈0,83× of SQLite). INSERT (≈1,1× ahead) and READ are structurally untouched by the change and unchanged in the runs. + +### Phase 9 — the `parse` lever investigated to a conclusion (2026-11-29) + +`parse`/classification is 34,5 % of the *profiled* UPDATE pass, so it was the next target. The investigation (this time reading the classifier bodies, not the ratio) ruled it out as a safe contained win: + +- `IsComputedSetValue` **short-circuits for a plain literal** (`IsPlainSetLiteral` → `false` with no column scan), so the value side is not the cost. +- The only per-statement `O(columns)` scan left, `Columns.IndexOf(setCol)`, is ~60 K string compares over 10 K statements (~0,06 ms) — negligible, and not cleanly cacheable without an `ITable` interface change. +- The real per-statement allocation is the 5 strings + a one-entry `Dictionary` + the boxed value (~497 B). The deferred-span idea targets the `Dictionary`. A mechanical `Dictionary` → `IReadOnlyDictionary` widening **compiles** (done and reverted), but a `SingleItemUpdate` only saves ~30–100 B because every `IReadOnlyDictionary` consumer enumerates through the interface (iterator/state-machine allocations) — and NET11 §2 already prices allocation at ~12 % of the per-statement cost, so the wall is neutral. This is exactly the P2 gate ("allocation alone is not enough; ship only on a measured timing win") and it **fails** it. The widening was reverted (neutral type churn is not a win). + +**Conclusion / real lever:** material `parse` improvement needs a **prepared/template DML shape cache** — normalise a statement's literals, classify the *shape* once, and bind literals per row — i.e. the DML half of the compiled-plan cache that session 75's cleanup found had no reader. That is a feature (normalisation rules, cache invalidation, a full statement/parameter/type matrix), not a micro-optimisation, and it is the honest answer for anyone re-opening this item. The larger *modelled* lever remains **`commit`/`commit-overwrites` ~27 %** (buffered-overwrite write-volume, a durability trade). + +### Phase 10 — the `commit`/write-volume lever investigated (2026-11-29) + +Full `--pk-profile`, AppendOnly fixed-width plaintext, 10.000 updates over 100.000 rows (profiled pass +86 ms): + +| stage | total ms | calls | share | B/call | +|---|---:|---:|---:|---:| +| parse | 28,9 | 10.000 | 35,4 % | 497 | +| row-locate (contiguous read/patch) | 24,9 | 1 | 30,5 % | 5,05 M | +| commit | 10,8 | 1 | 13,2 % | 1,86 M | +| commit-ovw-prep | 5,0 | 1 | 6,1 % | 652 K | +| commit-ovw-write | 0,1 | 2 | 0,1 % | 0 | + +- **The I/O syscalls are already refuted as the cost** (the code's own 2026-09-21 note: coalescing 640 page writes into 4 moved nothing). `commit-ovw-write` is 0,1 %. +- **`commit-ovw-prep` is the 10.000-entry iteration itself**, not the page-bucket lookup: a last-page cache in `BucketOverwritesByPage` (reuse the previous page's bucket for adjacent records) was implemented and measured — **5,2 → 5,0 ms, within noise** — and reverted ("the same is not a win"). +- **The real lever is the write VOLUME.** A same-length in-place overwrite rewrites the whole fixed-width record (~620 B) even when a single field (`score`, 8 B) changed: 10.000 × 620 B = **6,2 MB per batch**. A **field-level in-place write** — `OverwriteFieldAt(recordPosition + fieldOffset, 8 bytes)` that patches only the changed field bytes and records the change in the WAL — would cut the touched bytes ~75× and could move the commit dramatically. + +**Why it is not landed:** a field-level write is a **write-path / durability change**. The current model buffers the whole record and fsyncs it at commit; a field-level write must keep WAL replay and crash atomicity identical (a torn 8-byte field write must not be observable). The constitution (§I) makes durability non-negotiable, so this is an **owner decision with new evidence**, not a drive-by — the same class as decision 5/6 in `INSERT_UPDATE_PERFORMANCE_PLAN.md` §0.1. Recorded here as the single largest remaining modelled lever on UPDATE, fully scoped. + diff --git a/specs/003-prepared-dml-shape-cache/spec.md b/specs/003-prepared-dml-shape-cache/spec.md new file mode 100644 index 00000000..96ff5326 --- /dev/null +++ b/specs/003-prepared-dml-shape-cache/spec.md @@ -0,0 +1,160 @@ +# Feature Specification: Prepared DML shape cache (close the UPDATE `parse` cost) + +**Feature Branch**: `[003-prepared-dml-shape-cache]` + +**Created**: 2026-11-29 + +**Status**: Implemented and measured (2026-11-29) — prepared-statement API + `--pk-prepared` arm; **4.69× faster than the raw path**. (The internal shape-cache remains refuted, below.) + +**Refutation (internal shape-cache, 2026-11-29).** The plan above assumed a template cache could skip +the per-statement structural scan. It cannot, and the measurement/analysis says so: + +- To build the template key (`SET score = ? WHERE id = ?`) you must first **scan the statement** to find + the literals — the same `TryScanCanonicalDml` pass the classifier already pays. A cache hit therefore + cannot skip the scan; it can only skip the *structure resolution that follows it* + (`Columns.IndexOf`, `IsComputedSetValue`, `IsBareColumnIdent`, `IsSimpleWhereValueSpan`). +- That structure resolution is **microscopic**: `IsComputedSetValue` short-circuits on a plain literal + (`IsPlainSetLiteral`) with no column scan, `Columns.IndexOf` is ~6 string compares, and the two span + predicates are short. The 497 B/call of `parse` is the **5 string allocations** (each used as a + dictionary key or typed value) + the **`ParseValue`** of each literal + the scan — none of which a + shape cache can remove. +- An **exact-SQL** cache (no normalisation) would skip everything on a hit, but the benchmark's batch is + `UPDATE … SET score = {v} WHERE id = {i}` for 10.000 **distinct** `i`/`v`, so it **misses every time** — + which is exactly why the DML half of the compiled-plan cache reads as "unused" (session 75). + +So an internal shape cache is **structurally neutral on the raw-SQL arm** (the same lesson as Phase 9 and +Phase 10: the safe, contained levers are exhausted on this shape). Do not re-open it as an internal +cache. + +**The real path: a prepared-statement batch API.** The only way to skip the per-statement scan is for the +**caller** to supply the template once and the parameters per row — +`ExecuteBatchPrepared(string template, IReadOnlyList> parameters)` — so the +engine classifies the template **once** (keyed by its exact text, which now repeats) and binds parameters +per row. That is a real, buildable feature, but it measures a **different (prepared) workload**, not the +raw-SQL arm the SQLite comparison uses — so it belongs in its own benchmark arm (`--pk-prepared`), never +as a replacement for the raw arm. Its acceptance is "prepared beats raw by a measured margin", measured +against the same-run raw arm, not against SQLite's raw arm as if it were the same shape. + +--- + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Classify the statement shape once per batch (Priority: P1) + +A caller that sends a batch of statements with the same shape and different literals — the SWE +benchmark's `UPDATE docs SET score = {v} WHERE id = {i}` for 10.000 distinct `i` — pays the full +structural scan (`TryScanCanonicalDml`, keyword/quote skipping, column lookups) on every statement, +because the existing compiled-plan cache is keyed by the exact SQL text (literals included) and +therefore misses every time. + +**Why this priority**: it is the only lever that moves `parse` *time*; the deferred-span (allocation) +route is proven wall-neutral. + +**Independent Test**: a batch of N distinct-literal canonical UPDATE statements, profiled with +`SHARPCOREDB_WRITE_PROFILE`: the `parse` stage's µs/call and B/call both fall, and the `--pk` UPDATE +ratio improves — against the same-run SQLite arm, INSERT and READ unregressed. + +**Acceptance Scenarios**: + +1. **Given** 10.000 `UPDATE t SET c = WHERE k = ` statements with distinct literals, **When** dispatched as one batch, **Then** the structural classification runs once (per shape) and each subsequent statement only extracts + binds its literals. +2. **Given** a DDL change that alters the table's columns, **When** the next UPDATE of that shape arrives, **Then** the cached shape is invalidated and re-classified (no stale column index is used). +3. **Given** the flag is off, **Then** behaviour is byte-for-byte the current path. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: The classifier MUST recognise a canonical DML **shape** — literal values replaced by placeholders — and cache the resolved `(table, SET column index, WHERE column index, parameter positions)` keyed by that template. +- **FR-002**: On a template hit, the literal values MUST be extracted from the current statement and parsed exactly as `SqlParser.ParseValue` does today; the shape's column indices MUST be reused, not recomputed. +- **FR-003**: A shape entry MUST be invalidated when the table's schema changes (columns added/dropped/renamed) — keyed by a per-table schema version. +- **FR-004**: A statement that is not canonical (multi-column SET, expressions, non-`=` operators, quoted/qualified different shapes) MUST keep the current path — the cache is an accelerator, never a behaviour fork. +- **FR-005**: The feature MUST be default-off behind a `DatabaseConfig` flag, with a full statement/parameter/type matrix, and MUST ship only on a measured timing win (NET11 §2/§4 P2 rail). +- **FR-006**: No storage-format, encryption, durability or WAL change. + +### Key Entities + +- **Shape key**: the statement with every literal replaced by `?` (quotes/whitespace-normalised) — the cache key. +- **Shape plan**: `(Table, SetColumnIndex, WhereColumnIndex, [literal spans/positions])` — what a hit reuses. +- **Schema version**: bumps on any DDL that changes a table's column set; part of the invalidation key. + +## Success Criteria *(measurable)* + +- **SC-001**: `--pk` FW plaintext UPDATE `parse` µs/call and B/call fall measurably on the distinct-literal batch. +- **SC-002**: UPDATE ratio ≥ the current ~0.83–0.89× (target: close the remaining gap), INSERT/READ not regressed. +- **SC-003**: Full statement/parameter/type matrix green (canonical + every non-canonical fallback), the 8 canaries green, wider suite green, `--gate` PASSED. +- **SC-004**: Default-off; a run that measures "the same" is recorded as **not shipped**. + +## Design sketch + +Reuse the existing plan-cache plumbing (`GetOrAddPlan`, `CachedQueryPlan`, `CompiledPlanCacheCapacity`) +but key DML entries by the **template** (literals → `?`), not the literal-bearing SQL that made the old +DML plan-cache miss every time (and was removed in session 75 because nothing read it — this feature is +the reader). The classifier (`Database.Batch.cs` `TryParseUpdateForBatch`/`TryParseDeleteForBatch`) +checks the template cache first; a hit skips `TryScanCanonicalDml`'s structural scan and reuses the +resolved column indices, then extracts and parses the literals. A normaliser produces the template once +per distinct shape (charge it to the first statement); the cache is bounded by +`CompiledPlanCacheCapacity` with LRU eviction, and keyed additionally by a per-table schema version. + +## Risks / non-goals + +- **Normalisation correctness** is the whole risk: quotes, escapes, whitespace, operators and numeric + formats must fold to the same template without merging statements that resolve differently. The + matrix must include a statement that *looks* like a template but is not (a literal containing `?`). +- **Verdict-grade timing needs a quiet machine** (`scripts/quiet-machine.ps1`; WSearch needs elevation). +- Non-goals: allocation-only wins (wall-neutral, NET11 §2); any change that forks SQL semantics. + +## Assumptions + +- The distinct-literal batch is the shape that matters (the SWE benchmark's UPDATE/DELETE arms). A + caller that reuses exact SQL already hits the existing exact-text path. +- A ~40–60 % cut of `parse` (structural scan skipped) is the realistic ceiling; on a 0.6–0.8 µs real + parse that is ~0.3–0.4 µs/update, which is large enough to move the UPDATE ratio. + +## Result — implemented 2026-11-29 + +`IDatabase.ExecuteBatchPrepared(string template, IReadOnlyList> parameterSets)` +is implemented on directory storage (`Database.Batch.cs`) and measured by the new `--pk-prepared` +benchmark arm. It classifies the template once via `TryScanCanonicalDml`, then builds each operation +directly from the caller's typed parameters and hands the batch to the shared `UpdateMultiplePrepared` +core — no per-statement scan, no `ParseValue`, no 5-string/materialisation. Single-file storage keeps +the raw path (`NotSupportedException`, documented). + +First measurement (`--pk-prepared`, AppendOnly, fixed-width plaintext, 100.000 rows / 10.000 updates, +same data, same run): + +| arm | time | ops/sec | +|---|---:|---:| +| RAW `ExecuteBatchSQL` | 117,4 ms | 85.201 | +| **PREPARED `ExecuteBatchPrepared`** | **25,0 ms** | **399.672** | +| prepared / raw | — | **4,69×** | + +Verification: `SELECT score FROM docs WHERE id = 500` reads **49.950** (= 500 × 99,9) after the prepared +batch, matching the raw path. Correctness pinned by `ExecuteBatchPreparedTests` (2: every parameter set +applied + a non-parameter template throws); wider suite **3087 / 0 failed / 22 skipped**. + +**Scope note (unchanged):** this is the *prepared* workload, not the raw-SQL arm the SQLite comparison +uses. It does not "close" the raw UPDATE gap (~0.83×, the contiguous-patch win) — it proves the engine +serves prepared callers far faster than raw SQL, which is the honest, correct claim. + +## Provider threading (2026-11-29) + +The prepared path is threaded through the **ADO.NET connection** — the base layer that Dapper and +linq2DB sit on: + +- **`SharpCoreDBConnection.ExecuteBatchPrepared(template, parameterSets)`** (`SharpCoreDB.Data.Provider`) + delegates to `IDatabase.ExecuteBatchPrepared`, so an ADO.NET / Dapper / linq2DB caller that holds a + `SharpCoreDBConnection` can use the prepared batch directly (connection must be open; raw path kept + everywhere else). It is a thin, additive delegate — no existing execution path changes. + +**What does *not* auto-fit, and why (recorded so it is not re-attempted blindly):** +- **EF Core**: `SharpCoreDBModificationCommandBatchFactory` creates `SingularModificationCommandBatch` + — one command per batch — so EF's `SaveChanges` executes each modification individually through EF's + own `IRelationalCommand`, never an engine batch call. Using prepared-batch from EF needs a **custom + `ModificationCommandBatch`** that collects canonical parameterised UPDATEs and calls + `ExecuteBatchPrepared`; that changes EF's batching behaviour and needs its own statement/parameter + matrix, so it is a separate feature, not a wire-through. +- **Dapper / linq2DB**: they execute *singular* parameterised commands (Dapper's `Execute(sql, list)` + loops per parameter set; linq2DB issues a set-based `UPDATE`), so there is no same-shaped batch at + that layer to hook automatically. Their callers use the connection helper explicitly. +- **Single-file storage**: `NotSupportedException` — the raw `ExecuteBatchSQL` path only. + diff --git a/specs/004-read-insert-delete-parity/plan.md b/specs/004-read-insert-delete-parity/plan.md new file mode 100644 index 00000000..059d1b27 --- /dev/null +++ b/specs/004-read-insert-delete-parity/plan.md @@ -0,0 +1,122 @@ +# Implementation Plan: READ / INSERT / UPDATE / DELETE parity — what is actually left + +**Branch**: `[004-read-insert-delete-parity]` | **Date**: 2026-11-29 | **Spec**: [spec.md](./spec.md) + +**Input**: Feature specification from `/specs/004-read-insert-delete-parity/spec.md` + +## Summary + +The investigation found that **three of the four arms are already at or beyond SQLite on the fair plaintext +comparison**, and the remaining gaps are (a) the deliberate encryption tax (a security posture, not a +defect), (b) the `Dictionary` materialisation inherent to `ExecuteQuery`'s contract (with `ExecuteQueryStruct` +as the StructRow fast path), and (c) write-volume/fsync, which is a durability decision. The one remaining +**safe, contained** code lever is the **prepared DELETE**: extending `ExecuteBatchPrepared` (UPDATE-only today) +to accept the canonical `DELETE FROM WHERE = @param` template, routing the typed key into the +existing `Table.DeleteBatchStructured` resolver. That is delivered in this session, red→green. + +## Technical Context + +**Language/Version**: C# 15 preview / .NET 11 (`LangVersion=preview`, `net11.0`) + +**Primary Dependencies**: none new — `System.*` only; SIMD stays on `System.Runtime.Intrinsics` + +**Storage**: SharpCoreDB's own append-only / page-based / single-file engines; the change touches no storage +format, no encryption, no WAL semantics + +**Testing**: xUnit v3 4.0.0 via the Microsoft.Testing.Platform executable +(`tests/SharpCoreDB.Tests/bin/Release/net11.0/SharpCoreDB.Tests.exe -filterVSTest …`); `dotnet test` is not +usable in this repository + +**Target Platform**: `net11.0`, Windows/Linux + +**Project Type**: library (embedded database engine + ADO.NET provider) + +**Performance Goals**: prepared DELETE is the same class as the prepared UPDATE (4,69× raw on the benchmark +schema); no regression to the existing UPDATE prepared path + +**Constraints**: no storage/format/encryption/durability change; no public API break; no weakening of +encryption or durability (constitution §I) + +**Scale/Scope**: one method (`Database.ExecuteBatchPrepared`), three doc comments, one test class + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +| Gate | Verdict | +|---|---| +| §I Encrypted by default / no weakening | **PASS** — the DELETE branch encrypts/tombstones exactly as `DeleteBatchStructured` already does; nothing bypasses encryption | +| §I Durability (WAL, crash consistency, reopen round-trip) | **PASS** — the branch runs inside the shared `RunInBatchTransaction` (the same `CommitSync` + `FlushTransactionBuffer` pair every batch path pays) | +| §II SQLite compatibility is a floor | **PASS** — canonical DELETE shape accepted; non-canonical shapes still rejected to the general path | +| §III Ratios, encrypted + plaintext side by side | **PASS** — the spec records both arms; this change's proof is correctness + red→green, not an absolute ops/s claim | +| §VI No package/version changes | **PASS** — none | +| §11 SIMD standards | **N/A** — no SIMD added | + +**Result: PASS. No complexity violation to justify.** + +## Project Structure + +### Documentation (this feature) + +```text +specs/004-read-insert-delete-parity/ +├── spec.md # this feature's requirements + corrected findings +├── plan.md # this file +└── tasks.md # task list + delivery status +``` + +### Source Code (repository root) + +```text +src/ +├── SharpCoreDB/ +│ ├── Database/Execution/Database.Batch.cs # ExecuteBatchPrepared: UPDATE + DELETE branch (CHANGED) +│ ├── Interfaces/IDatabase.cs # contract doc (CHANGED, doc only) +│ └── DataStructures/Table.StructuredDml.cs # DeleteBatchStructured (unchanged, reused) +└── SharpCoreDB.Data.Provider/ + └── SharpCoreDBConnection.cs # passthrough doc (CHANGED, doc only) + +tests/SharpCoreDB.Tests/ +└── ExecuteBatchPreparedTests.cs # +3 tests (2 positive DELETE, 1 rejection) +``` + +**Structure Decision**: single project, partial-class layout unchanged. The DELETE branch is an additive +branch inside the existing `ExecuteBatchPrepared`, not a new class — it reuses `TryScanCanonicalDml` +(which already returned the DELETE halves) and `DeleteBatchStructured` (which the SQL batch DELETE path and +the SQL-free `DeleteBatch` already share). + +## Phase 0 — Research (conclusions, not open questions) + +1. **Where does the SQL READ time go?** Not the parse: `SimpleSelectPlan.TryCreate` + + `TrySelectIndexedPointLookup` already skip it for `WHERE indexed_col = @param`. The residual is the + `Dictionary` materialisation (`DeserializeRowWithSimd` / `DeserializeRowFixedWidth` box one + `object` per column), which is the `ExecuteQuery` contract. `ExecuteQueryStruct` is the StructRow fast path. +2. **Why is INSERT "behind" in the default arm?** It is not behind on plaintext (1,07–1,35× ahead). The + at-rest arm pays the encryption tax (~1,34×, already reduced from 1,90× by cipher pooling / the nonce + counter). SQLite's arm is plaintext, so the comparison is not like-for-like. +3. **What is left on UPDATE?** The contiguous patch (Phase 7 of `specs/002`) and the prepared API (PR #534) + closed the safe levers. The remainder is write-volume (`commit`/`commit-ovw-*`): a same-length in-place + UPDATE rewrites the whole ~620 B record for one 8 B field. That is a durability/write-path change (owner). +4. **What is the safe DELETE lever?** `ExecuteBatchPrepared` accepted only UPDATE; the canonical DELETE + halves were already produced by `TryScanCanonicalDml` but discarded. Bind them into `DeleteBatchStructured`. + +## Phase 1 — Design (delivered) + +**`Database.ExecuteBatchPrepared` new shape** (one classification per batch, both verbs): + +1. `TryScanCanonicalDml` succeeds → `setCol` empty means DELETE, non-empty means UPDATE. +2. `whereValRaw` must be `@param` (both verbs); `setValRaw` must be `@param` for UPDATE. +3. Table must resolve to a `DataStructures.Table`. +4. DELETE: build `List<(string KeyColumn, object? KeyValue)>` from the parameter sets, then + `RunInBatchTransaction(() => concrete.DeleteBatchStructured(keys))`. +5. UPDATE: unchanged — build the single-assignment ops and call `UpdateMultiplePrepared`. + +**Why this ordering**: the parameter validation stays ahead of the table lookup, so +`ExecuteBatchPrepared_NonParameterTemplate_Throws` keeps throwing `ArgumentException` (not +`InvalidOperationException`) for a non-parameter UPDATE template — verified by the existing test staying green. + +## Complexity Tracking + +> No violations. The change is +~30 lines in one method, an additive branch with no new type, no new file, +> no interface change (the signature is unchanged), and no storage/durability surface. + diff --git a/specs/004-read-insert-delete-parity/spec.md b/specs/004-read-insert-delete-parity/spec.md new file mode 100644 index 00000000..4bf4d3a3 --- /dev/null +++ b/specs/004-read-insert-delete-parity/spec.md @@ -0,0 +1,174 @@ +# Feature Specification: READ / INSERT / UPDATE / DELETE parity with SQLite — what is actually left + +**Feature Branch**: `[004-read-insert-delete-parity]` + +**Created**: 2026-11-29 + +**Status**: Investigation complete; US1 (prepared DELETE) delivered this session; US2–US4 are measured findings, not open code tasks + +**Input**: Owner request: "I thought we were only still behind on UPDATE and INSERT — give that extra +attention besides the READ finding, and write a good spec-kit plan." Grounded in +`docs/performance/INSERT_UPDATE_PERFORMANCE_PLAN.md` (§4/§6/§7/§9/§11), +`docs/performance/NET11_C15_PERFORMANCE_PLAN.md` (§2/§4 P2), `specs/002-sqlite-update-delete-parity/` +(Phases 7–10), and `docs/performance/WORKLOG.md` sessions 62–87. + +## Why this spec exists — the premise corrected by reading the code + +The owner's premise was "only UPDATE and INSERT are still behind". Reading the actual execution paths +overturned two of the four assumptions, and this spec records the corrected picture so the next session +does not re-litigate it. + +| arm | measured (same-run SQLite, `--pk`) | verdict | where the cost actually is | +|---|---|---|---| +| **INSERT plaintext** | 199.364–230.983 vs 185.766 | **1,07–1,35× ahead** | nothing — the inline-capacity + no-overflow work (session 62/64) holds | +| **INSERT at-rest (default)** | 167.421 vs 185.766 | ~0,90× | the deliberate **encryption tax** (~1,34×, down from 1,90×) — SQLite's arm is plaintext | +| **READ Direct (`FindByIndex`)** | ~1,3× | **ahead** | `StructRow`, no `Dictionary` materialisation | +| **READ SQL (`ExecuteQuery`)** | 107.380 vs 138.795 ops/s in the 0,73× run | 0,7–1,0× | the `List>` **materialisation** (boxing), *not* parsing | +| **UPDATE raw** | 632.755 vs 710–726K | ~0,83–0,89× | contiguous fix landed (Phase 7); remainder = write-volume + fsync (Phase 10) | +| **UPDATE prepared** | — | **4,69×** raw | `ExecuteBatchPrepared` (PR #534) | +| **DELETE raw** | 636.395 vs 780.019 | 0,82× | per-statement classification (same lever as UPDATE) | +| **DELETE prepared** | — | **delivered this session** | `ExecuteBatchPrepared` now accepts the canonical DELETE template | + +**The READ finding, corrected.** The earlier hypothesis was "the SQL READ re-parses every call, so a +compiled SELECT plan is the lever". Reading `Database.Execution.ExecuteQuery` → +`SqlParser.ExecuteQuery(CachedQueryPlan)` shows the point-lookup shape **already skips the parse**: +`SimpleSelectPlan.TryCreate` + `TrySelectIndexedPointLookup` resolve `WHERE indexed_col = @param` straight +through the hash index with no WHERE-string rebuild and no SQL re-parse. The benchmark's READ arm is exactly +that shape (`SELECT * FROM docs WHERE name = @name`). The residual gap is the `Dictionary` +materialisation (`DeserializeRowWithSimd`/`DeserializeRowFixedWidth` box one `object` per column) — which is +**inherent to the `ExecuteQuery` contract**, and the StructRow fast path for SQL already exists: +`ExecuteQueryStruct`. So there is no "compiled SELECT" to build; the honest lever for a caller that wants +Direct-READ speed through SQL is `ExecuteQueryStruct`. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Prepared DELETE (Priority: P1) — DELIVERED + +A caller issuing one canonical `DELETE FROM WHERE = @param` shape thousands of times can classify +the template **once** and bind the typed key per row, instead of re-scanning/re-parsing every raw statement — +the DELETE twin of the prepared UPDATE API that landed in PR #534. + +**Why this priority**: it is the only remaining **safe, contained** lever (no durability, no format, no +encryption change) and it is the DELETE half of the shape the `--pk` arm already measures for UPDATE. + +**Independent Test**: `ExecuteBatchPreparedTests` — a 100-row PK batch and a 100-row indexed-column batch +both delete every targeted row and return the count; a non-parameter DELETE template throws +`ArgumentException`. Proven red→green (2 failures before the change, 0 after). + +**Acceptance Scenarios**: + +1. **Given** `DELETE FROM docs WHERE id = @id` and 100 parameter sets, **When** `ExecuteBatchPrepared` runs, **Then** all 100 rows are deleted and 100 is returned. +2. **Given** `DELETE FROM docs WHERE name = @name` on an explicitly indexed non-PK column, **When** the prepared batch runs, **Then** the hash-index resolver deletes every target. +3. **Given** `DELETE FROM t WHERE id = 0` (literal, not a parameter), **When** the prepared batch runs, **Then** `ArgumentException` is thrown. + +--- + +### User Story 2 - READ: use the StructRow path instead of "building a compiled SELECT" (Priority: P1) — FINDING + +A caller that needs Direct-READ throughput through SQL should call `ExecuteQueryStruct` (StructRow) rather +than `ExecuteQuery` (`List>`). The point-lookup parse is already skipped; the +remaining `ExecuteQuery` gap is the per-row `Dictionary` + boxing. + +**Why this priority**: it corrects the earlier "compiled SELECT" premise and prevents a wasted build. + +**Independent Test**: `ExecuteQueryStruct` exists and is already exercised by the comparative benchmark's +Direct/StructRow arm; the point-lookup fast path is pinned by the existing `SimpleSelectPlan` tests. + +**Acceptance Scenarios**: + +1. **Given** `SELECT * FROM docs WHERE name = @name` on an explicitly indexed column, **When** executed repeatedly, **Then** it resolves through `TrySelectIndexedPointLookup` with no WHERE-string rebuild and no SQL re-parse (already true — pinned by the fast-path tests). +2. **Given** a caller mapping rows by ordinal that needs StructRow, **When** it switches from `ExecuteQuery` to `ExecuteQueryStruct`, **Then** it gets the Direct-READ shape without changing storage or format. + +--- + +### User Story 3 - INSERT: separate "ahead on plaintext" from "the deliberate encryption tax" (Priority: P2) — FINDING + +INSERT is **ahead** of SQLite on the plaintext arm. The default (at-rest) arm trails by the encryption tax, +which is the price of the constitution's encrypted-by-default posture, not a code inefficiency. The only +remaining knob is `EnableBatchEncryption` (opt-in, already implemented), and the honest floor is the GCM +framing (28 B/record) plus the AES work. + +**Why this priority**: it stops a hunt for a "code win" that is actually a security posture. + +**Independent Test**: the comparative benchmark already reports the plaintext and at-rest arms side by side; +`DatabaseConfigDefaultsTests` pins the encryption default. + +**Acceptance Scenarios**: + +1. **Given** the plaintext arm, **When** INSERT is measured against same-run SQLite, **Then** it is ≥ 1,0× (measured 1,07–1,35×). +2. **Given** the at-rest arm, **When** INSERT is measured, **Then** the gap is documented as the encryption tax, with `EnableBatchEncryption` named as the opt-in lever. + +--- + +### User Story 4 - UPDATE/DELETE raw: the remaining lever is write-volume, which is durability (Priority: P2) — FINDING, OWNER-GATED + +> **Settled 2026-11-29 by measurement (`specs/005-commit-full-page-write`).** Both halves of this item were +> built and measured, and both are **refuted** as levers: the flush is page-granular read-modify-write, so a +> field-level patch changes neither the page count, the reads nor the writes (its only saving is transient +> buffer memory — wall-neutral); and the comparator's SharpCoreDB arm already runs `WalDurabilityMode = Async` +> with OS-buffered overwrite writes and an empty transaction-buffer flush, so the measured `commit` contains +> **no fsync** — SQLite's `synchronous=NORMAL` posture is already matched, and `FullSync` stays the durable +> default. The surviving candidate (write a fully covered page without reading it) measured `commit` +> **10,6 → 32,0 ms** and was reverted. This story is kept as the record of that decision, not as open work. + +The raw UPDATE/DELETE gap that remains after the contiguous patch (Phase 7) and the prepared API is the +**write volume**: a same-length in-place UPDATE rewrites the whole ~620 B fixed-width record even when one +8 B field changed (10.000 × 620 B = 6,2 MB per batch), and the commit fsyncs it. A field-level write and a +WAL-fsync policy change are **durability/write-path changes** — owner decisions, not drive-bys. + +**Why this priority**: it is the single largest remaining modelled lever and must be recorded as +owner-gated, not silently attempted. + +**Independent Test**: `--pk-profile` pins the stage split (`parse` 35,4 %, `row-locate` 30,5 %, `commit` + +`commit-ovw-*` ~19 %); the profile is already in `specs/002` Phase 10. + +**Acceptance Scenarios**: + +1. **Given** a full `--pk-profile`, **When** the stages are read, **Then** `commit`/`commit-ovw-*` is the write-volume artifact, not I/O syscalls (already refuted: `commit-ovw-write` 0,1 %). +2. **Given** a proposed field-level write or fsync-policy change, **When** it is raised, **Then** it is recorded as an owner-gated durability decision with evidence, never landed opportunistically. + +--- + +### Edge Cases + +- A prepared DELETE template whose key column is the primary key: routed through the PK search / contiguous fixed-width resolver. +- A prepared DELETE template whose key column carries an explicit hash index: routed through the hash-index resolver (the benchmark's fair shape). +- A prepared DELETE template whose key column is unindexed: the structured fallback builds the predicate text per key — correct, just not text-free. +- A null key value in a parameter set: `DeleteBatchStructured` rejects it (`ArgumentException`) rather than silently no-op deleting. +- A DELETE template with a literal key (`WHERE id = 0`): rejected with `ArgumentException` — the prepared path requires parameters. +- A non-canonical UPDATE/DELETE (multi-column SET, ranges, `IN`, missing WHERE): rejected with `ArgumentException`; the caller falls back to `ExecuteBatchSQL`. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: `IDatabase.ExecuteBatchPrepared` MUST accept the canonical DELETE template `DELETE FROM WHERE = @whereParam` in addition to the canonical UPDATE template, with the same one-classification-per-batch contract. +- **FR-002**: The DELETE branch MUST route the already-typed key into `Table.DeleteBatchStructured`, so it shares the primary-key / hash-index / contiguous resolvers the SQL batch DELETE path uses. +- **FR-003**: A prepared DELETE template whose WHERE value is not an `@parameter` MUST throw `ArgumentException`; a parameter set missing the WHERE parameter MUST throw `ArgumentException`. +- **FR-004**: The change MUST NOT alter storage format, encryption, durability or WAL semantics (constitution §I; NET11 non-goals §6). The prepared DELETE takes the exact `RunInBatchTransaction` durability point every other batch path takes. +- **FR-005**: The change MUST NOT regress the canonical UPDATE prepared path (`ExecuteBatchPrepared_Update_AppliesEveryParameterSet`) or the non-parameter rejection (`ExecuteBatchPrepared_NonParameterTemplate_Throws`). +- **FR-006**: The READ/INSERT/UPDATE findings (US2–US4) MUST be recorded as measured conclusions, so no future session re-opens "build a compiled SELECT" or "find an INSERT code win". + +### Key Entities + +- **Canonical DELETE template**: `DELETE FROM WHERE = @param` — the shape a prepared caller issues. +- **Prepared DELETE batch**: the template classified once by `TryScanCanonicalDml` (which already returned the DELETE halves) + one typed `(KeyColumn, KeyValue)` per parameter set. +- **Encryption tax**: the measured at-rest overhead (~1,34× INSERT, ~2× UPDATE/DELETE) SQLite never pays because its benchmark arm is plaintext. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: `ExecuteBatchPrepared` deletes every targeted row for the PK shape and the indexed-column shape (100/100 both), and returns the deleted count. +- **SC-002**: The two new positive tests fail before the change (2 failures) and pass after (0 failures) — proven by reverting only `Database.Batch.cs`. +- **SC-003**: The canonical UPDATE prepared path and the existing non-parameter rejection still pass unchanged (5/5 in `ExecuteBatchPreparedTests`). +- **SC-004**: Build green; wider core suite green; the standing canaries (`ReopenRoundTripMatrixTests`, `FormatCompatPolicyTests`, `FixedWidthBulkUpdateTests`, `FixedWidthBulkDeleteTests`, `FixedWidthPatchTests`, `WritePathProfilerTests`, `FixedWidthInlineValueTests`, `SingleFileDirectoryParityTests`) stay green. +- **SC-005**: The READ/INSERT/UPDATE findings are recorded with their measured ratios, encrypted and plaintext side by side, never one alone (constitution §III). + +## Assumptions + +- The wall-clock win of the prepared DELETE is the same class as the prepared UPDATE (4,69× on the benchmark schema): it removes the per-statement `TryScanCanonicalDml` scan and literal-to-typed conversion. The deterministic claim proven here is correctness + the one-classification-per-batch contract; the wall number is measured by the `--pk-prepared`-style arm when a DELETE arm is added. +- The INSERT at-rest gap is not a defect: the constitution mandates encryption by default, and SQLite's reference arm is plaintext. The honest comparison is plaintext-vs-plaintext (INSERT is ahead) plus the documented tax. +- `ExecuteQueryStruct` is the supported StructRow SQL read; changing `ExecuteQuery`'s return type would be a breaking API change and is out of scope. +- Field-level write and fsync-policy work stay owner-gated durability decisions (constitution §I; `INSERT_UPDATE_PERFORMANCE_PLAN.md` §0.1 decisions 5/6). + diff --git a/specs/004-read-insert-delete-parity/tasks.md b/specs/004-read-insert-delete-parity/tasks.md new file mode 100644 index 00000000..9088ba0d --- /dev/null +++ b/specs/004-read-insert-delete-parity/tasks.md @@ -0,0 +1,87 @@ +# Tasks: READ / INSERT / UPDATE / DELETE parity — what is actually left + +**Input**: `/specs/004-read-insert-delete-parity/{spec,plan}.md` + +**Tests**: The red→green DELETE tests are required (correctness + the one-classification-per-batch contract). +The wall-clock numbers are measured by the comparative benchmark's existing arms; the deterministic claim +proven here is correctness, not an absolute ops/s figure (constitution §III: ratios only). + +## Phase 1: Setup / measurement (done in earlier sessions) + +- [x] T001 Capture the same-run `--pk` baseline: INSERT 199.364–230.983 (plaintext) / 167.421 (at-rest) / READ 107.380 / UPDATE 632.755 / DELETE 636.395 vs SQLite 185.766 / 138.795 / 710–726K / 780.019. +- [x] T002 Record the `--pk-profile` stage shares on the UPDATE arm (`parse` 35,4 %, `row-locate` 30,5 %, `commit`+`commit-ovw-*` ~19 %) in `specs/002` Phase 10. + +## Phase 2: Foundational (done in earlier sessions) + +- [x] T003 `specs/002` Phase 7 — contiguous fixed-width UPDATE patch (`TryOverwriteFixedWidthInPlaceSpan` + O(1) column cache): `row-locate` alloc −21 %, UPDATE gap ~1,4× → ~1,2×. +- [x] T004 PR #534 — `IDatabase.ExecuteBatchPrepared` + `--pk-prepared` arm: 4,69× raw UPDATE (25,0 vs 117,4 ms). +- [x] T005 PR #534 — ADO.NET provider passthrough (`SharpCoreDBConnection.ExecuteBatchPrepared`). + +## Phase 3: US1 — Prepared DELETE (P1) 🎯 DELIVERED + +**Goal**: `ExecuteBatchPrepared` accepts the canonical DELETE template and routes the typed key into the same +resolvers the SQL batch DELETE path uses, with one classification for the whole batch. + +**Independent Test**: `ExecuteBatchPreparedTests` — 5/5 green; the two positive DELETE tests were 2 failures +before the change. + +### Tests (written first, proven red) ⚠️ + +- [x] T006 [P] [US1] `ExecuteBatchPrepared_Delete_RemovesEveryParameterSet` — PK shape, 100 rows, asserts 100 deleted and the table empty. +- [x] T007 [P] [US1] `ExecuteBatchPrepared_Delete_OnIndexedColumn_ResolvesThroughHashIndex` — explicit `CREATE INDEX` on the non-PK `name` column (the benchmark's fair shape), 100 rows. +- [x] T008 [P] [US1] `ExecuteBatchPrepared_DeleteNonParameterTemplate_Throws` — `DELETE FROM t WHERE id = 0` throws `ArgumentException`. +- [x] T009 [US1] Prove red: revert only `Database.Batch.cs` (stash), rebuild, run → **Failed: 2**; restore → **Failed: 0**. + +### Implementation + +- [x] T010 [US1] `Database.Batch.cs` `ExecuteBatchPrepared`: accept the DELETE verb (`setCol` empty), validate `whereValRaw` is `@param`, build `(KeyColumn, KeyValue)` list, call `RunInBatchTransaction(() => concrete.DeleteBatchStructured(keys))`. +- [x] T011 [US1] Keep the UPDATE branch byte-for-byte in behaviour: parameter validation before the table lookup so `NonParameterTemplate_Throws` still throws `ArgumentException`. +- [x] T012 [P] [US1] `IDatabase.cs` contract doc — UPDATE or DELETE template, return "matched, updated or deleted". +- [x] T013 [P] [US1] `SharpCoreDBConnection.cs` passthrough doc — UPDATE or DELETE shape. + +**Checkpoint**: 5/5 in `ExecuteBatchPreparedTests`; build 0 errors. + +--- + +## Phase 4: US2 — READ finding (P1, no code task) + +- [x] T014 [US2] Confirm the point-lookup parse is already skipped (`SimpleSelectPlan.TryCreate` + `TrySelectIndexedPointLookup`) and that `ExecuteQueryStruct` is the StructRow SQL read. **Conclusion**: there is no "compiled SELECT" to build; the residual `ExecuteQuery` gap is the `Dictionary` materialisation (API contract). +- [ ] T015 [US2] (Optional, future) Add a `--pk` read arm that compares `ExecuteQueryStruct` against `FindByIndex` on the same run, so the StructRow SQL parity is a measured column rather than an inference. Not a code change to the engine. + +## Phase 5: US3 — INSERT finding (P2, no code task) + +- [x] T016 [US3] Separate "plaintext ahead" (1,07–1,35×) from "at-rest encryption tax" (~1,34×, down from 1,90×). **Conclusion**: the at-rest gap is the constitution's encrypted-by-default posture; the only knob is the existing opt-in `EnableBatchEncryption`. No defect to fix. + +## Phase 6: US4 — UPDATE/DELETE write-volume (P2, settled by measurement) + +- [x] T017 [US4] Record the write-volume lever with evidence (10.000 × 620 B = 6,2 MB per batch for one 8 B field; `commit-ovw-write` 0,1 % so it is not I/O syscalls). **Settled 2026-11-29:** the flush is page-granular read-modify-write, so a field-level patch changes neither the page count, the reads nor the writes — its only saving is transient buffer memory. Not a lever; see `specs/005-commit-full-page-write`. +- [x] T018 [US4] (Refuted) Field-level in-place write. **Verdict: wall-neutral** for the reason above (the page is rewritten whole either way); no implementation shipped. +- [x] T019 [US4] (Refuted) WAL fsync policy vs SQLite `synchronous=NORMAL`. **Verdict: already matched** — the comparator's SharpCoreDB arm runs `WalDurabilityMode = Async`, the overwrite writes are OS-buffered (`RandomAccess.Write`, `FileOptions.None`) and the transaction-buffer flush is empty for a pure UPDATE batch, so the measured `commit` has no fsync. `FullSync` stays the library default. +- [x] T019a [US4] (Refuted) Full-page write without a read — the surviving candidate, built and measured in `specs/005`: `commit` **10,6 → 32,0 ms** (2 coalesced cache-warm 1 MB reads replaced by 284 coverage passes + 284 per-page writes). Reverted in the same session. + +--- + +## Phase 7: Polish & validation + +- [x] T020 Build green: `dotnet build tests/SharpCoreDB.Tests/SharpCoreDB.Tests.csproj -c Release -f net11.0` → 0 errors. +- [ ] T021 Wider core suite green (MTP executable, `Category!=Debug&Category!=Manual&Category!=Performance`). +- [ ] T022 Standing canaries green: `ReopenRoundTripMatrixTests`, `FormatCompatPolicyTests`, `FixedWidthBulkUpdateTests`, `FixedWidthBulkDeleteTests`, `FixedWidthPatchTests`, `WritePathProfilerTests`, `FixedWidthInlineValueTests`, `SingleFileDirectoryParityTests`. +- [ ] T023 Worklog entry with `Session:`/`Verdict:`/`NEXT:` (append-only), and `docs/CHANGELOG.md` line for the user-visible API extension. + +--- + +## Dependencies & Execution Order + +- Phase 1–2 are the earlier sessions' inputs; T003/T004 gate the "safe levers exhausted" conclusion. +- T006–T008 (tests) → T009 (red proof) → T010–T013 (implementation/docs) → T020 (build). +- T014–T017 are findings, not code; T018/T019 are owner-gated and cannot start without an owner decision. +- T021–T023 close the session. + +## Notes + +- The prepared DELETE is additive: the signature is unchanged, so no caller or interface breaks. +- The DELETE branch takes the exact `RunInBatchTransaction` durability point the SQL batch path takes — no + new fsync, no new transaction boundary, no format change. +- "The same is not a win": no wall-clock claim is made for this change beyond the class of the prepared + UPDATE; the delivered proof is correctness + red→green + the wider suite. + diff --git a/specs/005-commit-full-page-write/spec.md b/specs/005-commit-full-page-write/spec.md new file mode 100644 index 00000000..1a87bcbd --- /dev/null +++ b/specs/005-commit-full-page-write/spec.md @@ -0,0 +1,81 @@ +# Feature Specification: Commit flush — full-page write without a read (REJECTED) + +**Feature Branch**: `[005-commit-full-page-write]` + +**Created**: 2026-11-29 + +**Status**: **REJECTED — implemented, measured, reverted in the same session. Not shipped.** + +**Input**: The investigation in `specs/004-read-insert-delete-parity` (US4) named the buffered-overwrite +flush's page READ as the largest remaining safe lever on the UPDATE commit. `Storage.Append.cs`'s own +2026-09-21 note measures **~17.5 ms of page READS** in a 29.8 ms flush (~55 µs per 4 KB page, "the shape of +real disk reads, not of the page cache"), and the read is avoidable for a page whose complete new content is +its own overwritten records — the interior pages of a contiguous fixed-width batch. + +## What was built (and then reverted) + +1. `FlushOverwritePages` classifies each patched page once: a page is **assembled from the buffered payloads + without reading the file** when the page-local patches plus the overlapping portions of cross-page records + cover every byte of it (`CanAssemblePage`, coverage-checked so a gap or an overlap falls back to the read). + Length prefixes are written from the payload lengths (the same-length overwrite invariant makes them + derivable), so an assembled page is byte-identical to a read-modify-write. +2. `IndexCrossPageRecords` indexes a record that spans a page boundary by both pages it touches, so its bytes + are available to the assembly. +3. `WritePathProfiler` gained `commit-ovw-read` (the read half's timing) plus the deterministic counters + `CommitOverwritePagesRead` / `CommitOverwritePagesAssembled`, printed in the stage report. +4. `CommitOverwritePageAssemblyTests` pinned the lever (red→green by disabling the assembly branch) and a + full-scan-after-reopen integrity check over every row. + +**Correctness**: the wider suite caught a real defect in the first cut — a length prefix that straddles a +page END (not just a page start) threw `ArgumentOutOfRangeException` from a 2-byte `WriteInt32LittleEndian`. +Fixed by disqualifying pages whose prefix straddles either boundary; the catcher +(`FixedWidthBulkDeleteTests.AscendingUpdateBatch_BatchedPageFlush_AppliesEveryRow_AcrossReopen`) and the new +test then passed, and the wider suite went **2986 / 0 failed / 6 skipped**. + +## Why it was rejected — the measurement + +`--pk-profile` (AppendOnly, fixed-width plaintext, 10.000 UPDATE … WHERE id = ? in one transaction over +100.000 rows), pre-change vs post-change binary on the same box: + +| stage | PRE (ms) | POST (ms) | +|---|---:|---:| +| `commit` | **10,6** | **32,0** | +| `commit-ovw-prep` | 5,1 | 5,1 | +| `commit-ovw-write` | 0,1 (2 calls) | 0,6 (284 calls) | +| `commit-ovw-read` | — | 0 (absent: every page assembled) | +| pages | 2 coalesced runs read | **1 read · 283 assembled** | +| UPDATE ops/s | 105.652 | 85.538 | + +Instrumented split of the post-change flush: `sort 1,28 ms · index 0,60 ms · precheck 5,20 ms · loop 16,04 ms`. + +**The premise was wrong for this workload.** The pre-change flush coalesces consecutive pages into ONE read ++ ONE write (up to 1 MB per range) — 2 reads and 2 writes for the whole batch. Those reads are **page-cache +hits**, because the row-locate phase has just read the same span (`raw` in +`TryBulkUpdateContiguousFixedWidth`). The ~17.5 ms figure came from a **cold page set**; the benchmark's data +file is 11,6 MB, so after the insert phase it is resident. Eliminating cache-hit reads saves almost nothing, +while the replacement costs: +- 284 `CanAssemblePage` coverage passes (~5,2 ms), and +- 284 per-page writes instead of 2 coalesced 1 MB writes (`loop` 16,0 ms). + +## Conclusion and what stays + +- **REJECTED:** the full-page assembly is byte-correct but a **3× regression in `commit`** on the measured + arm. Reverted with the instrumentation, the profiler stage/counters and the test. +- The deterministic idea is right for a **cold, larger-than-cache** data set; it is not this benchmark's + shape, and the repo's rail is to ship only on a measured win. +- **Field-level write** and **WAL-fsync policy** from US4 are likewise settled by evidence, not left open: + the flush is page-granular (smaller patches do not change page count/reads/writes), and the comparator's + SharpCoreDB arm already runs `WalDurabilityMode = Async` (`Program.cs`), so the measured `commit` contains + **no fsync** — SQLite's `synchronous=NORMAL` posture is already matched. +- Remaining honest levers on the raw UPDATE arm: the **`parse` stage (20-34 %)** — solved for prepared callers + by `ExecuteBatchPrepared` (4,69× raw), with the internal shape cache refuted in `specs/003` — and the + **row-locate span read**, which is the data movement the patch needs. + +## Success criteria that applied + +- **SC-001**: The change MUST be byte-correct on every documented shape. **Met** (wider suite 2986/0/6; the + straddling-prefix defect was found by the suite and fixed before the perf verdict). +- **SC-002**: Ship only on a measured timing win; "the same" is recorded as not shipped, never as a silent + micro-change. **Met by rejecting**: the measured direction was negative (10,6 → 32,0 ms `commit`). +- **SC-003**: No storage format, encryption or durability change. **Met** (the flush's write set is identical; + only the read is skipped). diff --git a/specs/006-parallel-record-encryption/spec.md b/specs/006-parallel-record-encryption/spec.md new file mode 100644 index 00000000..af0ae2dc --- /dev/null +++ b/specs/006-parallel-record-encryption/spec.md @@ -0,0 +1,122 @@ +# Feature Specification: Parallel record encryption for the fixed-width batch (at-rest tax) + +**Feature Branch**: `[006-parallel-record-encryption]` + +**Created**: 2026-11-30 + +**Status**: Plan approved; US1 (parallel decrypt) is the first cut. + +**Input**: Benchmark 2026-11-29 (`--pk`, same-run SQLite, median of the harness's paired reps): + +| | plaintext | at-rest | tax | +|---|---:|---:|---:| +| INSERT | 248.930 (1,25× ahead) | 215.972 (1,11× ahead) | 1,15× | +| READ | 178.155 (1,43× ahead) | 130.481 (parity) | 1,37× | +| UPDATE | 742.853 (0,91×) | **353.933 (0,47×)** | **2,10×** | +| DELETE | 833.423 (0,77×) | 585.161 (0,54×) | 1,42× | + +The at-rest UPDATE tax is the largest remaining gap on the engine's own arms. It is **per-record AES-GCM +work, executed sequentially on one thread**: `TryReadContiguousFixedWidthRecords` opens 10.000 AEAD records +one after another, and the overwrite path re-encrypts 10.000 records one after another. The cipher instances +are already **thread-affine** (`AesGcmEncryption._ciphersByThread`, the Linux-safety fix in 2.1.0) and the +nonce counter is `Interlocked`-incremented, so the crypto is safe to run concurrently — nothing in the engine +does. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Parallel decryption of the contiguous span (Priority: P1) + +A batch UPDATE or DELETE on an encrypted fixed-width table reads its target records as one contiguous +ciphertext range and then decrypts each record. That decrypt loop is embarrassingly parallel — each record +reads a disjoint slice of the range and writes a disjoint slice of the plaintext-laid-out buffer. + +**Why this priority**: it is the contained half of the tax (no storage-interface change) and the row-locate +stage is where the encrypted arm diverges first. + +**Independent Test**: an encrypted fixed-width table with ≥ 1000 rows gets a 1000-statement contiguous +UPDATE; every row must read back byte-identically (and after reopen), and the new diagnostic counter must +show the parallel branch engaged. Proven by flipping the parallel guard (counter stays 0, test fails). + +**Acceptance Scenarios**: + +1. **Given** an encrypted fixed-width table and a contiguous `pk = literal` UPDATE batch, **When** the span is decrypted, **Then** the result is byte-identical to the sequential loop's (every field of every row, after reopen). +2. **Given** a batch smaller than the parallel threshold (64 records), **When** it runs, **Then** the sequential loop is used (no `Parallel.For` overhead on small batches). +3. **Given** a span that contains a tombstoned or layout-mismatched slot, **When** it is decrypted, **Then** the whole batch still falls back to the generic per-row path (nothing is modified). + +--- + +### User Story 2 - Parallel re-encryption of the overwrite batch (Priority: P2) + +The overwrite path re-encrypts every patched record. Batch the encryption across cores (encrypt the payload +set in parallel, then buffer/write the results serially), the mirror of US1 on the write side. + +**Why this priority**: the second half of the 2,10× tax, but it needs a storage-overwrite batch entry point; +it ships only if US1 measures a win and the interface addition stays contained. + +**Independent Test**: the same encrypted batch UPDATE; the deterministic column is the at-rest UPDATE ratio +against the plaintext arm (tax), pre/post binaries, plus the counter showing how many records were encrypted +in the parallel phase. + +**Acceptance Scenarios**: + +1. **Given** an encrypted contiguous UPDATE batch above the threshold, **When** the patched payloads are encrypted, **Then** the ciphertext written equals what the per-row `EncryptRecord` produces (a reopen + read-back of every row proves it). +2. **Given** a small batch, **When** it runs, **Then** the per-row path is used unchanged. + +--- + +### Edge Cases + +- A single record (or any batch under the threshold): sequential, unchanged. +- A decrypt failure or a prefix mismatch inside the parallel loop: the batch rejects as a whole (the existing contract) — the parallel loop must not return early from a worker. +- `Parallel.For` inside the table write lock: the workers touch only their own slices plus the shared, thread-safe cipher cache and nonce counter — no table state. +- Encrypted and plaintext arms must be measured side by side, never one alone (§III). + +## Requirements *(mandatory)* + +- **FR-001**: `TryReadContiguousFixedWidthRecords` MUST decrypt the span's records in parallel when `count >= 64`, producing a byte-identical plaintext buffer to the sequential loop. +- **FR-002**: The nonce discipline MUST be unchanged: every nonce still comes from `AesGcmEncryption.BuildNonce`'s `Interlocked` counter, and every cipher stays thread-affine. +- **FR-003**: The failure contract MUST be unchanged: any failed decrypt or layout mismatch rejects the whole batch (`null`), before anything is modified. +- **FR-004**: No storage format, encryption strength or durability change (§I). +- **FR-005**: A diagnostic counter MUST show the parallel branch engaged, so the test can pin it (red→green). +- **FR-006**: US2 (parallel re-encrypt) MUST NOT land unless US1 shows a measured at-rest win; otherwise it is recorded as refuted. + +## Success Criteria *(mandatory)* + +- **SC-001**: The at-rest UPDATE tax drops (2,10× → measured lower) on the `--pk` arm, pre/post binaries, encrypted and plaintext side by side; or the change is reverted and recorded as refuted. +- **SC-002**: `ReopenRoundTripMatrixTests`, `FormatCompatPolicyTests`, `FixedWidthBulkUpdateTests`, `FixedWidthBulkDeleteTests`, `FixedWidthPatchTests` and `FixedWidthInlineValueTests` stay green; the wider core suite stays green. +- **SC-003**: `--gate` PASSED (or a documented re-run). +- **SC-004**: The parallel path is byte-identical (full-scan after reopen over every row of the batch). + +## Assumptions + +- The crypto share of the at-rest UPDATE arm is `(2,10 − 1) / 2,10 ≈ 52 %`; with ~10 cores the theoretical bound is `0,48 + 0,52/N`, so the realistic expectation is a tax of ~1,4–1,7× rather than parity. +- `Parallel.For`'s per-batch overhead is ~10–50 µs; the threshold (64 records) keeps it off small batches and off the per-statement paths. +- The box's core count and the cipher's memory-bandwidth behaviour decide the actual scaling; the ratio, not the absolute, is the deliverable. + +## Delivery record (2026-11-30) + +**US1 + US2 shipped.** `TryReadContiguousFixedWidthRecords` decrypts the span on `Parallel.For` when +`count >= 64`, and `TryBulkUpdateContiguousFixedWidth` seals the patched payloads the same way when the file +is encrypted; both latch a failure instead of returning from a worker, and both are observable through +`BulkContiguousParallelDecryptBatches` / `BulkContiguousParallelEncryptBatches`. `BufferOrWriteOverwriteInPlace` +resolves its base-length cache INSIDE `appendLock` — it was outside, a latent race once the batch path calls +it from parallel workers. `ParallelRecordEncryptionTests` (2 cases) pins the engagement and the byte-identical +result after reopen; both counters were proven red (`Expected: 1, Actual: 0`) by disabling each guard. + +**Same-session A/B** (`--pk`, PRE binary vs POST, 4 pairs; the at-rest tax = at-rest ÷ plaintext **within the +run**, which is the self-normalising column): + +| pair | POST UPDATE tax | PRE UPDATE tax | POST DELETE tax | PRE DELETE tax | +|---|---:|---:|---:|---:| +| 1 (US1) | 1,61 | 1,81 | 1,55 | 1,86 | +| 2 (US1) | 2,16 | 2,07 | 1,61 | 1,68 | +| 3 (US1+US2) | **1,56** | **2,05** | **1,16** | **1,40** | +| 4 (US1+US2) | **1,61** | **1,84** | 1,44 | 1,30 | + +Median UPDATE tax **1,945 → 1,585 (−19 %)** on the US1+US2 pairs; US1 alone was neutral on UPDATE (the write +side dominates) and consistently better on DELETE (2/2 pairs), which is exactly why US2 was needed. READ is +untouched by the change (point-read decrypt path) — its movement in the table is box noise and is recorded as +such. Verification: build 0 errors, focused 38/38, wider suite **2987 / 0 / 6**, canaries **59 / 0**, +`--gate` PASSED on the documented re-run (first run `default UPDATE` 1,61× on a NOISY box, re-run 1,10×). + + diff --git a/specs/007-native-aot-cleanup/spec.md b/specs/007-native-aot-cleanup/spec.md new file mode 100644 index 00000000..9303db7e --- /dev/null +++ b/specs/007-native-aot-cleanup/spec.md @@ -0,0 +1,70 @@ +# Feature Specification: Native AOT warning cleanup + +**Feature Branch**: `[007-native-aot-cleanup]` + +**Created**: 2026-11-30 + +**Status**: **VERIFIED DONE — the roadmap item was stale.** Both halves were already implemented; this session +verified them end to end instead of re-implementing them. + +## Verification record (2026-11-30) + +- **US1 is already in place**: `BTreeIndexManager.CreateBTreeIndex` is a closed-generic `switch` (one arm per + `DataType`) that the compiler and trimmer can see, with the comment naming it the replacement for the + `GetBTreeIndexType` + `Activator.CreateInstance` pair (IL3050); `ITypeErasedIndex` replaces + `GetType().GetMethod("Add")` / `("FindRange")`. No reflection remains on that path. +- **US2 is already in place**: `AotJsonSerializer` builds the one `JsonSerializerOptions` with a resolver + chosen by the runtime — the framework reflection resolver where + `JsonSerializer.IsReflectionEnabledByDefault` is true (the JIT path, byte-identical JSON) and the + source-generated `SharpCoreDBJsonContext` + `SharpCoreDBAotJsonContext` where it is false (Native AOT / + trimming). Every call site resolves `GetTypeInfo()` instead of the reflection overloads + (`SingleFileTable`'s row blocks, `Database.Core`'s metadata, `StorageMigrator`, `OptInRowParser`, + `UserService`, `DatabaseMigrator`). +- **Measured (the DoD)**: `dotnet publish tools/SharpCoreDB.AotSmoke -c Release -r win-x64 -p:PublishAot=true` + → **0 errors, 0 IL/AOT warnings** across the whole `SharpCoreDB` assembly; the published native exe reports + `JsonSerializer.IsReflectionEnabledByDefault = False` and **PASS, exit 0** — 1000 inserts, point lookup, + StructRow point + full scan, reopen, full vacuum, full-at-rest encryption + password/key rotation. +- **Consequence**: no code change this session; the item is recorded as verified so the next session does not + re-open it. The evidence is reproducible with the two commands above. + +## Why + + +`tools/SharpCoreDB.AotSmoke` publishes and runs (exit 0), but the trim/AOT analyzers still warn on +reflection that a Native AOT publish cannot see: the B-tree factory resolves its implementation with +`GetMethod`/`Activator.CreateInstance`, and `.scdb`/`ParseVectorValue` JSON goes through reflection-based +`System.Text.Json`. Those warnings are the roadmap item; removing them removes the runtime dependency on +reflection metadata (smaller AOT binary, no trimming surprises). + +## User Stories + +### US1 - Interface-based B-tree factory (P1) + +Replace the reflection lookup with a typed factory (an interface with a static/registered implementation), +so the B-tree type is resolved without `GetMethod`/`Activator.CreateInstance`. + +**Independent test**: the AOT smoke still publishes and runs; the B-tree tests stay green; the reflection +sites are gone (grep-provable). + +### US2 - Source-generated JSON (P2) + +Add `JsonSerializerContext` source generation for the `.scdb` metadata DTOs and `ParseVectorValue`, and +route serialization through it. + +**Independent test**: a round-trip test per DTO; the AOT smoke green. + +## Requirements + +- **FR-001**: No behaviour change: the same B-tree implementation is resolved, and the same JSON shape is produced. +- **FR-002**: The AOT smoke keeps publishing (exit 0) and the warning set for the changed types shrinks. +- **FR-003**: Core suite + canaries green. + +## Success Criteria + +- **SC-001**: AOT smoke publish+run exit 0; the touched types emit no IL2xxx/IL3xxx warnings. +- **SC-002**: Round-trip tests for every source-generated DTO; wider core suite green. +- **SC-003**: No package/version change (§VI). + +## Assumptions + +- This is a quality/AOT-readiness item, not a wall-clock one: no perf ratio is claimed. diff --git a/specs/008-single-file-metadata-parity/spec.md b/specs/008-single-file-metadata-parity/spec.md new file mode 100644 index 00000000..914a1cf9 --- /dev/null +++ b/specs/008-single-file-metadata-parity/spec.md @@ -0,0 +1,53 @@ +# Feature Specification: Single-file metadata parity + +**Feature Branch**: `[008-single-file-metadata-parity]` + +**Created**: 2026-11-30 + +**Status**: **DELIVERED (2026-11-30).** `SingleFileDatabase` now declares `IMetadataProvider`; the parity test +pins the probe and the metadata. + +## Delivery record (2026-11-30) + +`SingleFileDatabase` (`DatabaseExtensions.cs`) already had `GetTables()` / `GetColumns(string)` — `IDatabase` +declares them — but the class did not list `IMetadataProvider`, so `db is IMetadataProvider` was **true for a +directory database and false for a `.scdb` file**. One interface was added to the class declaration (implicit +implementation, the same shape `Database` uses in `Database.Metadata.cs`); the two methods already answered +from the single-file catalog. + +Pinned by `SingleFileMetadataParityTests.MetadataProvider_ProbeAndMetadata_AgreeAcrossStorageModes`: both modes +must answer the probe, both must list the table, and the column metadata (table, name, data type, ordinal, +nullability, collation) must be equal column for column. Proven red by removing the interface again — the test +then fails on `single-file database must be an IMetadataProvider` — and green with it. Verification: build +0 errors, wider suite **2988 / 0 / 6**, canaries **60 / 0**, `--gate` **PASSED**. No storage-format, encryption +or durability change. + +## Why + + +Some consumers probe metadata with `db is IMetadataProvider`. Directory-mode `Database` implements it; +`SingleFileDatabase` does not, so the same probe answers differently for the two storage modes — the +roadmap's explicit acceptance is that probing works consistently for both. + +## User Story - `SingleFileDatabase` implements `IMetadataProvider` explicitly (P1) + +Expose the metadata surface (table names/schemas/column types as the interface defines them) from the +single-file database, explicitly implementing `IMetadataProvider`. + +**Independent test**: the same probe (`db is IMetadataProvider`) and the same metadata assertions run against +a directory database and a single-file database and agree. + +## Requirements + +- **FR-001**: `SingleFileDatabase` MUST implement `IMetadataProvider` explicitly, answering from its own catalog. +- **FR-002**: The directory-mode behaviour MUST be unchanged. +- **FR-003**: No storage format, encryption or durability change. + +## Success Criteria + +- **SC-001**: A parity test asserts the interface probe and the same metadata for both modes. +- **SC-002**: Core suite + provider suites green. + +## Assumptions + +- The metadata contract is already defined; this is a parity/exposure item, not a new capability. diff --git a/specs/009-owner-decisions/spec.md b/specs/009-owner-decisions/spec.md new file mode 100644 index 00000000..4a0adf4c --- /dev/null +++ b/specs/009-owner-decisions/spec.md @@ -0,0 +1,76 @@ +# Feature Specification: Owner decisions (single-file format extensions and compatibility defaults) + +**Feature Branch**: `[009-owner-decisions]` + +**Created**: 2026-11-30 + +**Status**: **Decisions taken 2026-11-30 — D1=A, D2=A, D3=B delivered; D4=C delivered (the engine already had it; the record's earlier BLOCKED verdict was corrected).** Evidence source: `docs/sharpcoredb-known-issues.md` (§6, §10, §11) and `docs/PROJECT_STATUS.md` › Roadmap. + +## Decision record (2026-11-30) + +| Decision | Answer | Outcome | +|---|---|---| +| D1 — single-file PK uniqueness + composite keys | **A** | **Delivered.** Every key column is parsed and persisted (`ColumnFlags.PrimaryKey` on each), a free bit (`ColumnDefinitionEntry.KeyModelledFlag`, bit 6) marks the file as key-modelled, and `SingleFileTable` enforces the key tuple's uniqueness on INSERT / multi-row INSERT / every UPDATE path. A file written before the marker carries zero there and stays unenforced — its key columns were never recorded. `PrimaryKeyIndex` (the storage key) is still the last key column, so existing behaviour is unchanged. The four previously-skipped `PrimaryKeyUniquenessTests` single-file cases now run and pass (duplicate insert, multi-row against existing, duplicate within the statement, after reopen). | +| D2 — single-file `COLLATE` | **A** | **Delivered.** `COLLATE NOCASE` / `RTRIM` is parsed by the single-file DDL, persisted in the free bits 8-11 of the column flags (`ColumnDefinitionEntry.GetCollation`/`SetCollation`), reloaded on reopen, and honoured by the WHERE evaluator (with the compiled ordinal fast path bypassed for such a column) and by ORDER BY (single-file comparer and `SqlOrderBy`). `Locale(…)` stays out of scope (needs a name field). The previously-skipped `SingleTableOrderByTests.OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively` now runs and passes; `SingleFileCollationTests` adds WHERE equality/range and reopen coverage. | +| D3 — `INTEGER` affinity | **B** | **Delivered as the no-decision half, plus two fixes the message depended on.** Int32 stays the default. The batch INSERT literal path used to store a too-large number as **0** — it now throws the same actionable message as the single-statement path; and the single-file DDL used to hardcode `UseSqliteIntegerAffinity: false`, so the opt-in the message names had no effect there — it now reads the config. `IntegerAffinityTests` (3 cases, red→green). | +| D4 — optional Zstandard | **C** (implement now) | **DELIVERED — the engine already had it.** .NET 11 ships in-box Zstandard (`System.IO.Compression.ZstandardStream`; verified in the `11.0.0` ref pack and runtime), and the engine already implements it: `BlockCompressor` has a `BlockCompressionMode.Zstd` path (thread-static `ZstandardEncoder`, pooled destination, stream-based decode) selected by `DatabaseOptions.BlockCompression`, the SCDB **header records the mode** (`ScdbFileHeader.CompressionMode`) and `ValidateHeader` refuses a mismatched open with an actionable message, and `Storage/CompressionLevelTests` pins the round-trip and stream-compatibility. This session fixed two **stale doc claims** — `BlockCompressionMode.Zstd` said "on this runtime, using this mode will throw NotSupportedException" and `BlockFlags.Compressed` said "reserved, always 0 for .scdb" — and added the missing **end-to-end database test** (`SingleFileCompressionTests`: Zstd write → 200-row round-trip after reopen → update → opening with the wrong mode throws the actionable message; plus an encrypted compress-then-encrypt round-trip). **Correction to the record:** an earlier pass marked this BLOCKED on the package rail; that was wrong twice — the availability scan searched for `ZStandard` (the API is `Zstandard`) and the existing compression layer was not checked. No package is needed and no code was blocked. | + +## Why + + +Four remaining items are not engineering tasks but **decisions**: each changes an on-disk format extension +or a compatibility default. The evidence and the exact trade-offs are written down here so a decision can be +made once, without re-deriving it. + +## D1 — Single-file PRIMARY KEY uniqueness and composite keys (§11, 🔴) + +- **State**: directory storage enforces composite keys (a table-level `PRIMARY KEY (a, b)` is a UNIQUE over + its columns, the row id stays the storage key) for new tables. Single-file storage enforces **no** PK + uniqueness, because its format persists `ColumnFlags.PrimaryKey` on one column only, so a file cannot tell + a single-column key from a composite key that lost its other columns. +- **Decision needed**: model composite keys (persist `PrimaryKey` on every key column; enforce the tuple's + uniqueness), then switch on single-column uniqueness for single-file. Files written before cannot recover + the lost key columns and would stay unenforced. +- **Hazard**: enforcing single-column uniqueness before composite keys are modelled makes existing EF Core + single-file databases with composite keys reject legitimate inserts after an upgrade + (`CompleteExampleIntegrationTests.CompositeKey_*` showed exactly this when it was tried). +- **Evidence rails**: skipped single-file cases in `PrimaryKeyUniquenessTests`. + +## D2 — Single-file ignores a column's declared `COLLATE` (§10, 🟡) + +- **State**: `CREATE TABLE t (name TEXT COLLATE NOCASE)` behaves as BINARY on single-file storage; directory + storage honours it. Three gaps: the single-file DDL parser does not read `COLLATE`; `ColumnDefinitionEntry` + (48 bytes) has no collation field; `SingleFileTable.EvaluateSingleCondition` has no collation support. +- **Decision needed**: claim bits 8–11 of `ColumnDefinitionEntry.Flags` for `CollationType` (a file written + before reads 0 = BINARY, i.e. today's behaviour) — an on-disk format extension that + `docs/manual/upgrade-and-downgrade.md` permits (old files keep working; downgrade is already unsupported). + A `Locale(…)` collation would still need a name field. +- **Evidence rails**: skipped `SingleTableOrderByTests.OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively`. + +## D3 — `INTEGER` column affinity (§6, 🟡) + +- **State**: `INTEGER` maps to `DataType.Integer` (Int32), not SQLite's 64-bit `INTEGER`, so + `DateTime.UtcNow.Ticks` (~6.4e17) overflows. The SQLite behaviour is available opt-in via + `DatabaseConfig.UseSqliteIntegerAffinity` for newly created/added columns. +- **Decision needed**: flip the default (SQLite compatibility — the constitution makes SQLite a floor) or keep + Int32 for backward compatibility. A default flip changes the CLR type consumers read back; existing columns + keep the type recorded in their metadata either way. +- **Low-risk intermediate (no decision needed)**: improve the overflow error message to name the column, the + value and `BIGINT` / `UseSqliteIntegerAffinity` as the fixes. + +## D4 — Optional Zstandard compression (roadmap, C# 15 item) + +- **Decision needed**: an opt-in, per-file compression layer. It is a **format change** (magic-header versioned + upgrade, `PersistenceConstants`/`PageHeader` version bump, migration path, downgrade story) and must stay + optional (new features stay optional, §VI). No code before the format/upgrade plan is accepted. + +## Requirements for all four + +- **FR-001**: No implementation lands without an explicit owner decision recorded in the worklog. +- **FR-002**: Each decision, when made, ships with the magic-header/skipped-test rails its note names. +- **FR-003**: D3's error-message improvement may ship without a decision (it changes no default). + +## Success Criteria + +- **SC-001**: Each decision is recorded with its evidence and outcome; the skipped tests are either enabled or + stay skipped with the recorded reason. diff --git a/src/SharpCoreDB.Analytics/Aggregation/SimdAggregates.cs b/src/SharpCoreDB.Analytics/Aggregation/SimdAggregates.cs index 1f4a6593..882d1acd 100644 --- a/src/SharpCoreDB.Analytics/Aggregation/SimdAggregates.cs +++ b/src/SharpCoreDB.Analytics/Aggregation/SimdAggregates.cs @@ -82,11 +82,23 @@ public enum SimdTier /// This reports capability, not the tier a specific call takes — a call on a 4-element span runs the /// scalar tail even on an AVX-512 host. Read it together with the length of the input. /// - public static SimdTier MaxTier => - Avx512F.IsSupported ? SimdTier.Avx512 - : Avx2.IsSupported ? SimdTier.Avx2 - : Sse2.IsSupported ? SimdTier.Sse2 - : SimdTier.Scalar; + public static SimdTier MaxTier + { + get + { + if (Avx512F.IsSupported) + { + return SimdTier.Avx512; + } + + if (Avx2.IsSupported) + { + return SimdTier.Avx2; + } + + return Sse2.IsSupported ? SimdTier.Sse2 : SimdTier.Scalar; + } + } /// Gets a value indicating whether any hardware vector tier is available. public static bool IsHardwareAccelerated => MaxTier != SimdTier.Scalar; diff --git a/src/SharpCoreDB.Analytics/SharpCoreDB.Analytics.csproj b/src/SharpCoreDB.Analytics/SharpCoreDB.Analytics.csproj index ed36b1d2..2a822aac 100644 --- a/src/SharpCoreDB.Analytics/SharpCoreDB.Analytics.csproj +++ b/src/SharpCoreDB.Analytics/SharpCoreDB.Analytics.csproj @@ -4,7 +4,7 @@ net11.0 enable enable - 2.2.0 + 2.2.1 SharpCoreDB.Analytics diff --git a/src/SharpCoreDB.Aspire.Hosting/SharpCoreDB.Aspire.Hosting.csproj b/src/SharpCoreDB.Aspire.Hosting/SharpCoreDB.Aspire.Hosting.csproj index 8f0f3a4f..921e065f 100644 --- a/src/SharpCoreDB.Aspire.Hosting/SharpCoreDB.Aspire.Hosting.csproj +++ b/src/SharpCoreDB.Aspire.Hosting/SharpCoreDB.Aspire.Hosting.csproj @@ -16,7 +16,7 @@ SharpCoreDB.Aspire.Hosting - 2.2.0 + 2.2.1 .NET Aspire hosting integration for the SharpCoreDB network server diff --git a/src/SharpCoreDB.CQRS/SharpCoreDB.CQRS.csproj b/src/SharpCoreDB.CQRS/SharpCoreDB.CQRS.csproj index 84fba234..4f5cfa4d 100644 --- a/src/SharpCoreDB.CQRS/SharpCoreDB.CQRS.csproj +++ b/src/SharpCoreDB.CQRS/SharpCoreDB.CQRS.csproj @@ -11,7 +11,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.CQRS - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.CQRS diff --git a/src/SharpCoreDB.Client.Protocol/SharpCoreDB.Client.Protocol.csproj b/src/SharpCoreDB.Client.Protocol/SharpCoreDB.Client.Protocol.csproj index ace0d64a..3bc796de 100644 --- a/src/SharpCoreDB.Client.Protocol/SharpCoreDB.Client.Protocol.csproj +++ b/src/SharpCoreDB.Client.Protocol/SharpCoreDB.Client.Protocol.csproj @@ -9,7 +9,7 @@ SharpCoreDB.Client.Protocol - 2.2.0 + 2.2.1 Client-side protocol implementation for SharpCoreDB (gRPC, binary) diff --git a/src/SharpCoreDB.Client/SharpCoreDB.Client.csproj b/src/SharpCoreDB.Client/SharpCoreDB.Client.csproj index 5c6dcc23..9923b726 100644 --- a/src/SharpCoreDB.Client/SharpCoreDB.Client.csproj +++ b/src/SharpCoreDB.Client/SharpCoreDB.Client.csproj @@ -9,7 +9,7 @@ SharpCoreDB.Client - 2.2.0 + 2.2.1 .NET client library for SharpCoreDB network server (ADO.NET-like API) diff --git a/src/SharpCoreDB.Data.Provider/SharpCoreDB.Data.Provider.csproj b/src/SharpCoreDB.Data.Provider/SharpCoreDB.Data.Provider.csproj index 81405af7..856de616 100644 --- a/src/SharpCoreDB.Data.Provider/SharpCoreDB.Data.Provider.csproj +++ b/src/SharpCoreDB.Data.Provider/SharpCoreDB.Data.Provider.csproj @@ -16,7 +16,7 @@ https://github.com/MPCoreDeveloper/SharpCoreDB https://github.com/MPCoreDeveloper/SharpCoreDB ado.net;database;data-provider;sharpcoredb - 2.2.0 + 2.2.1 git NuGet.README.md SharpCoreDB.jpg diff --git a/src/SharpCoreDB.Data.Provider/SharpCoreDBConnection.cs b/src/SharpCoreDB.Data.Provider/SharpCoreDBConnection.cs index 70dbba37..2d4d800a 100644 --- a/src/SharpCoreDB.Data.Provider/SharpCoreDBConnection.cs +++ b/src/SharpCoreDB.Data.Provider/SharpCoreDBConnection.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; @@ -81,6 +82,27 @@ public override string ConnectionString /// public IDatabase? DbInstance => _database; + /// + /// Executes a parameterised batch of one canonical UPDATE or DELETE shape through the + /// prepared-statement path: the database classifies the SQL template once and binds each row's + /// parameters, instead of re-parsing a raw statement per row (measured ~4,7× the raw + /// ExecuteBatchSQL path on the benchmark schema). Delegates to + /// , so ADO.NET, Dapper and linq2DB callers can use the + /// prepared path through the connection. + /// + /// The parameterised canonical UPDATE or DELETE template. + /// One parameter dictionary (keyed by @name) per row. + /// The number of rows matched, updated or deleted. + public int ExecuteBatchPrepared(string sqlTemplate, IReadOnlyList> parameterSets) + { + if (_state != ConnectionState.Open || _database is null) + { + throw new InvalidOperationException("The connection must be open to execute a prepared batch."); + } + + return _database.ExecuteBatchPrepared(sqlTemplate, parameterSets); + } + /// /// Changes the current database. Not supported by SharpCoreDB. /// diff --git a/src/SharpCoreDB.Distributed/SharpCoreDB.Distributed.csproj b/src/SharpCoreDB.Distributed/SharpCoreDB.Distributed.csproj index d8732c1c..d675be7f 100644 --- a/src/SharpCoreDB.Distributed/SharpCoreDB.Distributed.csproj +++ b/src/SharpCoreDB.Distributed/SharpCoreDB.Distributed.csproj @@ -15,7 +15,7 @@ SharpCoreDB.Distributed - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Distributed diff --git a/src/SharpCoreDB.EntityFrameworkCore/SharpCoreDB.EntityFrameworkCore.csproj b/src/SharpCoreDB.EntityFrameworkCore/SharpCoreDB.EntityFrameworkCore.csproj index 63e9f527..0a47e32f 100644 --- a/src/SharpCoreDB.EntityFrameworkCore/SharpCoreDB.EntityFrameworkCore.csproj +++ b/src/SharpCoreDB.EntityFrameworkCore/SharpCoreDB.EntityFrameworkCore.csproj @@ -8,7 +8,7 @@ SharpCoreDB.EntityFrameworkCore - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.EntityFrameworkCore diff --git a/src/SharpCoreDB.EventSourcing/SharpCoreDB.EventSourcing.csproj b/src/SharpCoreDB.EventSourcing/SharpCoreDB.EventSourcing.csproj index 56be3bd5..ebd908a8 100644 --- a/src/SharpCoreDB.EventSourcing/SharpCoreDB.EventSourcing.csproj +++ b/src/SharpCoreDB.EventSourcing/SharpCoreDB.EventSourcing.csproj @@ -15,7 +15,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.EventSourcing - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.EventSourcing diff --git a/src/SharpCoreDB.Extensions/SharpCoreDB.Extensions.csproj b/src/SharpCoreDB.Extensions/SharpCoreDB.Extensions.csproj index e1e06812..70c8c2de 100644 --- a/src/SharpCoreDB.Extensions/SharpCoreDB.Extensions.csproj +++ b/src/SharpCoreDB.Extensions/SharpCoreDB.Extensions.csproj @@ -8,7 +8,7 @@ SharpCoreDB.Extensions - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Extensions diff --git a/src/SharpCoreDB.Functional.Dapper/SharpCoreDB.Functional.Dapper.csproj b/src/SharpCoreDB.Functional.Dapper/SharpCoreDB.Functional.Dapper.csproj index 8290206f..6a02b2b1 100644 --- a/src/SharpCoreDB.Functional.Dapper/SharpCoreDB.Functional.Dapper.csproj +++ b/src/SharpCoreDB.Functional.Dapper/SharpCoreDB.Functional.Dapper.csproj @@ -7,7 +7,7 @@ enable SharpCoreDB.Functional.Dapper - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Functional.Dapper diff --git a/src/SharpCoreDB.Functional.EntityFrameworkCore/SharpCoreDB.Functional.EntityFrameworkCore.csproj b/src/SharpCoreDB.Functional.EntityFrameworkCore/SharpCoreDB.Functional.EntityFrameworkCore.csproj index 73f40cfd..e0d155cb 100644 --- a/src/SharpCoreDB.Functional.EntityFrameworkCore/SharpCoreDB.Functional.EntityFrameworkCore.csproj +++ b/src/SharpCoreDB.Functional.EntityFrameworkCore/SharpCoreDB.Functional.EntityFrameworkCore.csproj @@ -7,7 +7,7 @@ enable SharpCoreDB.Functional.EntityFrameworkCore - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Functional.EntityFrameworkCore diff --git a/src/SharpCoreDB.Functional.Linq2DB/SharpCoreDB.Functional.Linq2DB.csproj b/src/SharpCoreDB.Functional.Linq2DB/SharpCoreDB.Functional.Linq2DB.csproj index 9d4ca40e..66a3a201 100644 --- a/src/SharpCoreDB.Functional.Linq2DB/SharpCoreDB.Functional.Linq2DB.csproj +++ b/src/SharpCoreDB.Functional.Linq2DB/SharpCoreDB.Functional.Linq2DB.csproj @@ -7,7 +7,7 @@ enable SharpCoreDB.Functional.Linq2DB - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Functional.Linq2DB diff --git a/src/SharpCoreDB.Functional/SharpCoreDB.Functional.csproj b/src/SharpCoreDB.Functional/SharpCoreDB.Functional.csproj index 85a8117a..6ef921b2 100644 --- a/src/SharpCoreDB.Functional/SharpCoreDB.Functional.csproj +++ b/src/SharpCoreDB.Functional/SharpCoreDB.Functional.csproj @@ -7,7 +7,7 @@ enable SharpCoreDB.Functional - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Functional diff --git a/src/SharpCoreDB.Graph.Advanced/SharpCoreDB.Graph.Advanced.csproj b/src/SharpCoreDB.Graph.Advanced/SharpCoreDB.Graph.Advanced.csproj index 91915bbf..2443416f 100644 --- a/src/SharpCoreDB.Graph.Advanced/SharpCoreDB.Graph.Advanced.csproj +++ b/src/SharpCoreDB.Graph.Advanced/SharpCoreDB.Graph.Advanced.csproj @@ -6,7 +6,7 @@ preview SharpCoreDB.Graph.Advanced SharpCoreDB.Graph.Advanced - 2.2.0 + 2.2.1 SharpCoreDB.Graph.Advanced MPCoreDeveloper MPCoreDeveloper diff --git a/src/SharpCoreDB.Graph/SharpCoreDB.Graph.csproj b/src/SharpCoreDB.Graph/SharpCoreDB.Graph.csproj index ef435561..2297f8c0 100644 --- a/src/SharpCoreDB.Graph/SharpCoreDB.Graph.csproj +++ b/src/SharpCoreDB.Graph/SharpCoreDB.Graph.csproj @@ -13,7 +13,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.Graph - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Graph diff --git a/src/SharpCoreDB.HybridSearch/SharpCoreDB.HybridSearch.csproj b/src/SharpCoreDB.HybridSearch/SharpCoreDB.HybridSearch.csproj index 8586c16d..16f472a5 100644 --- a/src/SharpCoreDB.HybridSearch/SharpCoreDB.HybridSearch.csproj +++ b/src/SharpCoreDB.HybridSearch/SharpCoreDB.HybridSearch.csproj @@ -12,7 +12,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.HybridSearch - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.HybridSearch diff --git a/src/SharpCoreDB.Identity/SharpCoreDB.Identity.csproj b/src/SharpCoreDB.Identity/SharpCoreDB.Identity.csproj index c5033c07..5bbbc17b 100644 --- a/src/SharpCoreDB.Identity/SharpCoreDB.Identity.csproj +++ b/src/SharpCoreDB.Identity/SharpCoreDB.Identity.csproj @@ -8,7 +8,7 @@ true SharpCoreDB.Identity - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Identity diff --git a/src/SharpCoreDB.Projections/SharpCoreDB.Projections.csproj b/src/SharpCoreDB.Projections/SharpCoreDB.Projections.csproj index 4b2da3d8..5425ceff 100644 --- a/src/SharpCoreDB.Projections/SharpCoreDB.Projections.csproj +++ b/src/SharpCoreDB.Projections/SharpCoreDB.Projections.csproj @@ -11,7 +11,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.Projections - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Projections diff --git a/src/SharpCoreDB.Provider.Sync/SharpCoreDB.Provider.Sync.csproj b/src/SharpCoreDB.Provider.Sync/SharpCoreDB.Provider.Sync.csproj index 2220a893..bb1c2f3b 100644 --- a/src/SharpCoreDB.Provider.Sync/SharpCoreDB.Provider.Sync.csproj +++ b/src/SharpCoreDB.Provider.Sync/SharpCoreDB.Provider.Sync.csproj @@ -9,7 +9,7 @@ SharpCoreDB.Provider.Sync - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Provider.Sync diff --git a/src/SharpCoreDB.Provider.YesSql/SharpCoreDB.Provider.YesSql.csproj b/src/SharpCoreDB.Provider.YesSql/SharpCoreDB.Provider.YesSql.csproj index e1b133eb..6adc2af3 100644 --- a/src/SharpCoreDB.Provider.YesSql/SharpCoreDB.Provider.YesSql.csproj +++ b/src/SharpCoreDB.Provider.YesSql/SharpCoreDB.Provider.YesSql.csproj @@ -8,7 +8,7 @@ SharpCoreDB.Provider.YesSql - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Provider.YesSql diff --git a/src/SharpCoreDB.Search/SharpCoreDB.Search.csproj b/src/SharpCoreDB.Search/SharpCoreDB.Search.csproj index 2ee85480..c1259b87 100644 --- a/src/SharpCoreDB.Search/SharpCoreDB.Search.csproj +++ b/src/SharpCoreDB.Search/SharpCoreDB.Search.csproj @@ -12,7 +12,7 @@ $(NoWarn);1591;SA1101;SA1633;SA1309 SharpCoreDB.Search - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Search diff --git a/src/SharpCoreDB.Serilog.Sinks/SharpCoreDB.Serilog.Sinks.csproj b/src/SharpCoreDB.Serilog.Sinks/SharpCoreDB.Serilog.Sinks.csproj index 85fb6240..602697d3 100644 --- a/src/SharpCoreDB.Serilog.Sinks/SharpCoreDB.Serilog.Sinks.csproj +++ b/src/SharpCoreDB.Serilog.Sinks/SharpCoreDB.Serilog.Sinks.csproj @@ -7,7 +7,7 @@ SharpCoreDB.Serilog.Sinks - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.Serilog.Sinks diff --git a/src/SharpCoreDB.Server.Core/SharpCoreDB.Server.Core.csproj b/src/SharpCoreDB.Server.Core/SharpCoreDB.Server.Core.csproj index 53f2e02e..560449db 100644 --- a/src/SharpCoreDB.Server.Core/SharpCoreDB.Server.Core.csproj +++ b/src/SharpCoreDB.Server.Core/SharpCoreDB.Server.Core.csproj @@ -9,7 +9,7 @@ SharpCoreDB.Server.Core - 2.2.0 + 2.2.1 Core server infrastructure for SharpCoreDB network server diff --git a/src/SharpCoreDB.Server.Protocol/SharpCoreDB.Server.Protocol.csproj b/src/SharpCoreDB.Server.Protocol/SharpCoreDB.Server.Protocol.csproj index 0dd09a83..0689f413 100644 --- a/src/SharpCoreDB.Server.Protocol/SharpCoreDB.Server.Protocol.csproj +++ b/src/SharpCoreDB.Server.Protocol/SharpCoreDB.Server.Protocol.csproj @@ -9,7 +9,7 @@ SharpCoreDB.Server.Protocol - 2.2.0 + 2.2.1 Network protocol definitions for SharpCoreDB server (gRPC, binary, HTTP) diff --git a/src/SharpCoreDB.Server/SharpCoreDB.Server.csproj b/src/SharpCoreDB.Server/SharpCoreDB.Server.csproj index 8836ec54..64ea737f 100644 --- a/src/SharpCoreDB.Server/SharpCoreDB.Server.csproj +++ b/src/SharpCoreDB.Server/SharpCoreDB.Server.csproj @@ -19,7 +19,7 @@ sharpcoredb-server SharpCoreDB Network Server SharpCoreDB network database server with gRPC and HTTP support - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB Copyright (c) 2026 MPCoreDeveloper diff --git a/src/SharpCoreDB.VectorSearch/SharpCoreDB.VectorSearch.csproj b/src/SharpCoreDB.VectorSearch/SharpCoreDB.VectorSearch.csproj index d1bf00bb..31f69494 100644 --- a/src/SharpCoreDB.VectorSearch/SharpCoreDB.VectorSearch.csproj +++ b/src/SharpCoreDB.VectorSearch/SharpCoreDB.VectorSearch.csproj @@ -15,7 +15,7 @@ SharpCoreDB.VectorSearch - 2.2.0 + 2.2.1 MPCoreDeveloper SharpCoreDB SharpCoreDB.VectorSearch diff --git a/src/SharpCoreDB/DataStructures/Table.CRUD.cs b/src/SharpCoreDB/DataStructures/Table.CRUD.cs index c4e3889f..4ab90830 100644 --- a/src/SharpCoreDB/DataStructures/Table.CRUD.cs +++ b/src/SharpCoreDB/DataStructures/Table.CRUD.cs @@ -1916,9 +1916,15 @@ private void ValidateRowAfterUpdate(Dictionary row, Dictionary 0 || keyColumn is null - ? where - : structuredKeyLiteral is not null - ? keyColumn + " = " + structuredKeyLiteral - : BuildStructuredWhereText(keyColumn, keyValue); + string fallbackWhere; + if (where.Length > 0 || keyColumn is null) + { + fallbackWhere = where; + } + else if (structuredKeyLiteral is not null) + { + fallbackWhere = keyColumn + " = " + structuredKeyLiteral; + } + else + { + fallbackWhere = BuildStructuredWhereText(keyColumn, keyValue); + } long locateStart = Diagnostics.WritePathProfiler.Stamp(); foreach (var row in SelectInternal(fallbackWhere, orderBy: null, asc: true, noEncrypt: false)) { @@ -3156,6 +3170,33 @@ oldHashValues is not null && private long _structuredUpdateOperations; + /// + /// Batches whose contiguous fixed-width span had its per-record AEAD opens run on + /// . Diagnostics only: the parallel branch is a + /// performance change with identical bytes, so a test pins that it engaged on an encrypted batch rather + /// than inferring it from a timing (the same reason is public). + /// + public long BulkContiguousParallelDecryptBatches => Interlocked.Read(ref _bulkContiguousParallelDecrypts); + + private long _bulkContiguousParallelDecrypts; + + /// + /// Batches whose contiguous fixed-width overwrite sealed its records on + /// — the write-side half of the at-rest tax. + /// Diagnostics only, for the same reason as : the + /// branch is a performance change with identical bytes, so a test pins that it engaged. + /// + public long BulkContiguousParallelEncryptBatches => Interlocked.Read(ref _bulkContiguousParallelEncrypts); + + private long _bulkContiguousParallelEncrypts; + + /// + /// Record count from which the contiguous span's per-record AEAD opens run in parallel. The + /// overhead is ~10-50 µs per batch, so a small batch + /// keeps the sequential loop (and the single-statement paths never reach this span at all). + /// + private const int ParallelDecryptRecordThreshold = 64; + /// /// B8: single-pass contiguous UPDATE fast path for plaintext fixed-width tables. Requires every /// operation to be a simple pk = <numeric literal> match on the primary key, with keys @@ -3204,6 +3245,7 @@ this.storage is null || var keys = new string[count]; var repointColumns = new List?[count]; long parsedPrev = 0; + var columnIndexCache = GetColumnIndexCache(); for (int i = 0; i < count; i++) { @@ -3243,18 +3285,10 @@ this.storage is null || foreach (var updateKey in updates.Keys) { - // Resolve the column; unknown columns must fall back so the generic loop surfaces the error. - int colIdx = -1; - for (int c = 0; c < this.Columns.Count; c++) - { - if (this.Columns[c].Equals(updateKey, StringComparison.OrdinalIgnoreCase)) - { - colIdx = c; - break; - } - } - - if (colIdx < 0) + // Resolve the column via the shared O(1) cache instead of an O(columns) scan per + // statement (the --pk batch sends 10.000 statements, so the scan was 10.000 × columns + // string compares). Unknown columns still fall back so the generic loop surfaces the error. + if (!columnIndexCache.TryGetValue(updateKey, out int colIdx)) { return false; } @@ -3304,16 +3338,55 @@ this.storage is null || } // Patch and write each record in place (buffered by the storage layer; flushed at commit). - for (int i = 0; i < count; i++) + // A distinct record buffer per row is required: the storage layer buffers the array REFERENCE + // (BufferOrWriteOverwriteInPlace stores `record`, and for plaintext EncryptRecord hands the same + // instance back), so a shared scratch would leave every buffered overwrite holding the last + // row's bytes. Patching THAT per-row buffer in place (the span overload) still removes the + // second allocation the array overload made (its own `new byte[]` copy) — ~one record per row. + bool PatchAndWriteRow(int i) { var payload = new byte[layout.FixedSize]; raw.AsSpan((int)(i * stride) + 4, layout.FixedSize).CopyTo(payload); - var patched = TryOverwriteFixedWidthInPlace(payload, operations[i].Updates); - if (patched is null || !engine.TryUpdateInPlaceSameLength(Name, positions[i], patched)) + return TryOverwriteFixedWidthInPlaceSpan(payload, operations[i].Updates) && + engine.TryUpdateInPlaceSameLength(Name, positions[i], payload); + } + + if (encrypted && count >= ParallelDecryptRecordThreshold) + { + // The write-side half of the at-rest tax: each row owns its payload buffer and its storage + // offset, the AEAD seal runs before the storage buffer lock, and the buffer's base-length + // cache is resolved inside that lock (Storage.Append.cs), so the seals run across cores. + int failed = 0; + System.Threading.Tasks.Parallel.For(0, count, i => + { + if (Volatile.Read(ref failed) != 0) + { + return; + } + + if (!PatchAndWriteRow(i)) + { + Volatile.Write(ref failed, 1); + } + }); + + if (Volatile.Read(ref failed) != 0) { return false; } + + Interlocked.Increment(ref _bulkContiguousParallelEncrypts); + } + else + { + for (int i = 0; i < count; i++) + { + if (!PatchAndWriteRow(i)) + { + return false; + } + } } // Re-point hash-index entries for every fixed-size indexed SET column with ONE lock @@ -4772,13 +4845,18 @@ private static byte[] SliceCipher(byte[] physical, int index, long physicalStrid // layout (tombstone, mixed legacy file) or a payload that fails to decrypt rejects the // whole batch — nothing has been modified yet. raw = new byte[totalBytes]; - for (int i = 0; i < count; i++) + + // Each record reads a DISJOINT ciphertext slice and writes a DISJOINT plaintext slice, and the + // storage's AesGcmEncryption keeps one cipher per thread with an Interlocked-derived nonce, so + // the loop is safe to run concurrently. The crypto share was measured at ~52 % of the at-rest + // UPDATE arm (tax 2,10×, --pk 2026-11-29), which is what this parallel branch exists for. + bool DecryptRecordAt(int i) { int prefix = BinaryPrimitives.ReadInt32LittleEndian( physical.AsSpan((int)(i * physicalStride), 4)); if (prefix != layout.FixedSize + AesGcmEncryption.OverheadSize) { - return null; // tombstoned slot or layout mismatch -> generic per-row path + return false; // tombstoned slot or layout mismatch -> generic per-row path } // §5.3 tail (2026-09-22): the frame is decrypted where it lies in the range read, so the per-record @@ -4788,12 +4866,49 @@ private static byte[] SliceCipher(byte[] physical, int index, long physicalStrid ?? this.storage.DecryptRecordPayload(SliceCipher(physical, i, physicalStride, prefix)); if (plain is null || plain.Length != layout.FixedSize) { - return null; + return false; } var target = raw.AsSpan((int)(i * stride)); BinaryPrimitives.WriteInt32LittleEndian(target, layout.FixedSize); plain.CopyTo(target[4..]); + return true; + } + + if (count >= ParallelDecryptRecordThreshold) + { + int failed = 0; + System.Threading.Tasks.Parallel.For(0, count, i => + { + // Latch a rejection instead of returning from a worker: the whole batch must reject as + // one (the sequential contract), and an early worker exit would leave half-written work. + if (Volatile.Read(ref failed) != 0) + { + return; + } + + if (!DecryptRecordAt(i)) + { + Volatile.Write(ref failed, 1); + } + }); + + if (Volatile.Read(ref failed) != 0) + { + return null; + } + + Interlocked.Increment(ref _bulkContiguousParallelDecrypts); + } + else + { + for (int i = 0; i < count; i++) + { + if (!DecryptRecordAt(i)) + { + return null; + } + } } } else diff --git a/src/SharpCoreDB/DataStructures/Table.Serialization.cs b/src/SharpCoreDB/DataStructures/Table.Serialization.cs index 7dbcbc4e..d2746a04 100644 --- a/src/SharpCoreDB/DataStructures/Table.Serialization.cs +++ b/src/SharpCoreDB/DataStructures/Table.Serialization.cs @@ -726,6 +726,46 @@ private Dictionary DeserializeRowFixedWidth(ReadOnlySpan d return result; } + /// + /// Span-in-place sibling of : patches the updated slots + /// of a fixed-width record inside the caller's buffer instead of allocating a copy, so the + /// contiguous fixed-width UPDATE/DELETE fast path can reuse one scratch buffer for the whole batch. + /// The array overload allocated a fresh byte[] result per row (plus the caller's own copy), + /// which is ~one record per row on the batch-DML hot path. Returns false when an updated column is + /// unknown or the record length does not match the layout, exactly as the array overload returns null. + /// + private bool TryOverwriteFixedWidthInPlaceSpan(Span record, Dictionary updates) + { + var layout = GetFixedWidthLayout(); + if (record.Length != layout.FixedSize) + { + return false; + } + + var arena = GetOverflowArena(); + var columnIndexCache = GetColumnIndexCache(); + + foreach (var (column, value) in updates) + { + if (!columnIndexCache.TryGetValue(column, out int colIdx) || colIdx < 0 || colIdx >= layout.ColumnCount) + { + return false; + } + + var slot = record.Slice(layout.Offsets[colIdx], layout.SlotSizes[colIdx]); + if (layout.IsVariable[colIdx]) + { + WriteVariableSlotInPlace(arena, slot, value, ColumnTypes[colIdx]); + } + else + { + _ = WriteTypedValueToSpan(slot, value, ColumnTypes[colIdx]); + } + } + + return true; + } + /// /// Patches one variable-length slot of a fixed-width record in place, growing into a new /// overflow block (or reusing a freed same-length block) and freeing the previous one. diff --git a/src/SharpCoreDB/DataStructures/Table.UniqueKeys.cs b/src/SharpCoreDB/DataStructures/Table.UniqueKeys.cs index 01eaee86..bfff47d9 100644 --- a/src/SharpCoreDB/DataStructures/Table.UniqueKeys.cs +++ b/src/SharpCoreDB/DataStructures/Table.UniqueKeys.cs @@ -414,11 +414,19 @@ private void ValidateBatchKeyChangesCore( } // The same WHERE text UpdateMultipleCore falls back to for a structured operation. - var whereText = where.Length > 0 || keyColumn is null - ? where - : keyLiteral is not null - ? keyColumn + " = " + keyLiteral - : BuildStructuredWhereText(keyColumn, keyValue); + string whereText; + if (where.Length > 0 || keyColumn is null) + { + whereText = where; + } + else if (keyLiteral is not null) + { + whereText = keyColumn + " = " + keyLiteral; + } + else + { + whereText = BuildStructuredWhereText(keyColumn, keyValue); + } changes.Add((ResolveUpdateRows(whereText).ConvertAll(r => r.Row), updates)); } diff --git a/src/SharpCoreDB/Database/Execution/Database.Batch.cs b/src/SharpCoreDB/Database/Execution/Database.Batch.cs index 1a0f044c..24b70444 100644 --- a/src/SharpCoreDB/Database/Execution/Database.Batch.cs +++ b/src/SharpCoreDB/Database/Execution/Database.Batch.cs @@ -319,8 +319,12 @@ private static bool ParseBooleanFast(ReadOnlySpan value) return type switch { - DataType.Integer => int.TryParse(value, out var i) ? i : 0, - DataType.Long => long.TryParse(value, out var l) ? l : 0L, + // A value that is a NUMBER but does not fit the column must not silently become 0: the + // single-statement path (SqlParser.ParseValue -> ParseInt32Checked) already throws the + // actionable message, and the batch path must agree — a silent 0 stores a value the + // caller never wrote. Text that is not a number keeps the historical lenient 0. + DataType.Integer => ParseIntegerForBatch(value, DataType.Integer), + DataType.Long => ParseIntegerForBatch(value, DataType.Long), DataType.Real => double.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0.0, DataType.Decimal => decimal.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out var m) ? m : 0m, DataType.Boolean => ParseBooleanFast(value), @@ -330,6 +334,56 @@ private static bool ParseBooleanFast(ReadOnlySpan value) }; } + /// + /// Parses an INTEGER / BIGINT literal for the batch INSERT path. A value that is a number but + /// does not fit the column's type throws the same actionable message the single-statement path + /// (SqlParser.ParseValue → ParseInt32Checked) throws; text that is not a number keeps + /// the historical lenient 0. Before this, a too-large value was stored as 0 — silent corruption. + /// + /// The literal text (quotes already removed). + /// The target column type (Integer or Long). + /// The parsed value, or 0 for non-numeric text. + private static object ParseIntegerForBatch(ReadOnlySpan value, DataType type) + { + if (type == DataType.Integer) + { + if (int.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var intValue)) + { + return intValue; + } + + if (IsNumericText(value)) + { + throw new InvalidOperationException( + $"Value '{value}' exceeds the Int32 range for an INTEGER column. " + + "Declare the column as BIGINT or LONG, or set " + + "DatabaseConfig.UseSqliteIntegerAffinity = true to map INTEGER to Int64 (SQLite behavior)."); + } + + return 0; + } + + if (long.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var longValue)) + { + return longValue; + } + + if (IsNumericText(value)) + { + throw new InvalidOperationException( + $"Value '{value}' exceeds the Int64 range for a BIGINT column. " + + "Declare the column as DECIMAL to keep integral values beyond Int64."); + } + + return 0L; + } + + /// True when the text is a number of any numeric type (used to tell "too big" from "not a number"). + private static bool IsNumericText(ReadOnlySpan value) => + long.TryParse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out _) || + decimal.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out _) || + double.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out _); + /// /// Reads one VALUES element as SQLite does under option 2 of issue #525: a computed expression (constant /// arithmetic, a function of literals, a comparison) is evaluated, and a date/time column keeps an unquoted @@ -1290,6 +1344,94 @@ private bool TryParseDeleteForBatch(string sql, out string tableName, out string return tables.ContainsKey(tableName) && !string.IsNullOrWhiteSpace(where); } + /// + /// Executes a parameterised batch of ONE canonical statement shape (a prepared statement): the + /// template is classified once by , then each row binds its + /// parameters into the shared UpdateMultiplePrepared core — no per-statement scan, no + /// ParseValue (the values are already typed), no per-row predicate string. This is the + /// prepared path the raw-SQL batch cannot take; it is measured separately (the --pk-prepared + /// benchmark arm). The template must be a canonical + /// UPDATE <t> SET <col> = @setParam WHERE <key> = @whereParam or + /// DELETE FROM <t> WHERE <key> = @whereParam; for a DELETE the typed key goes + /// straight into DeleteBatchStructured, the same resolver the SQL batch DELETE path runs. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + public int ExecuteBatchPrepared(string sqlTemplate, IReadOnlyList> parameterSets) + { + ArgumentException.ThrowIfNullOrWhiteSpace(sqlTemplate); + ArgumentNullException.ThrowIfNull(parameterSets); + if (parameterSets.Count == 0) + { + return 0; + } + + // Classify the SHAPE once — TryScanCanonicalDml reads `@score` / `@id` as the value halves. + // Both canonical verbs are accepted: UPDATE leaves a SET half, DELETE leaves it empty. + if (!TryScanCanonicalDml(sqlTemplate, out var tableName, out var setCol, out var setValRaw, out var whereCol, out var whereValRaw)) + { + throw new ArgumentException( + "The template must be a canonical UPDATE SET = WHERE = " + + "or DELETE FROM WHERE = .", nameof(sqlTemplate)); + } + + var whereParam = whereValRaw; // e.g. "@id" + if (whereParam.Length < 2 || whereParam[0] != '@') + { + throw new ArgumentException("The WHERE value must be a parameter (@name).", nameof(sqlTemplate)); + } + + bool isDelete = setCol.Length == 0; + if (!isDelete && (setValRaw.Length < 2 || setValRaw[0] != '@')) + { + throw new ArgumentException("The SET value must be a parameter (@name).", nameof(sqlTemplate)); + } + + if (!tables.TryGetValue(tableName, out var table) || table is not DataStructures.Table concrete) + { + throw new InvalidOperationException($"Table '{tableName}' does not exist."); + } + + // DELETE FROM WHERE = @whereParam — the DELETE twin of the UPDATE prepared path. The + // canonical scanner leaves setCol/setValRaw empty for a DELETE, so the verb is unambiguous here. + // The typed key goes straight into DeleteBatchStructured, whose PK / hash-index / contiguous + // resolvers are exactly the ones the SQL batch DELETE path runs — the classification is paid once + // for the whole batch instead of once per statement. + if (isDelete) + { + var keys = new List<(string KeyColumn, object? KeyValue)>(parameterSets.Count); + foreach (var parameters in parameterSets) + { + ArgumentNullException.ThrowIfNull(parameters); + if (!parameters.TryGetValue(whereParam, out var whereValue)) + { + throw new ArgumentException($"A parameter set is missing '{whereParam}'.", nameof(parameterSets)); + } + + keys.Add((whereCol, whereValue)); + } + + return RunInBatchTransaction(() => concrete.DeleteBatchStructured(keys)); + } + + var setParam = setValRaw; // e.g. "@score" + + var ops = new List<(string Where, string? KeyColumn, object? KeyValue, string? KeyLiteral, Dictionary Updates)>(parameterSets.Count); + foreach (var parameters in parameterSets) + { + ArgumentNullException.ThrowIfNull(parameters); + if (!parameters.TryGetValue(setParam, out var setValue) || + !parameters.TryGetValue(whereParam, out var whereValue)) + { + throw new ArgumentException($"A parameter set is missing '{setParam}' or '{whereParam}'.", nameof(parameterSets)); + } + + var updates = new Dictionary(1) { [setCol] = setValue ?? DBNull.Value }; + ops.Add((string.Empty, whereCol, whereValue, null, updates)); + } + + return RunInBatchTransaction(() => concrete.UpdateMultiplePrepared(ops)); + } + /// /// ✅ PHASE 3: Optimized batch SQL execution with prepared statement caching. /// Uses cached parsers for repeated INSERT schemas, reducing parsing overhead by ~40%. diff --git a/src/SharpCoreDB/DatabaseExtensions.cs b/src/SharpCoreDB/DatabaseExtensions.cs index ca1618b7..852c5a6f 100644 --- a/src/SharpCoreDB/DatabaseExtensions.cs +++ b/src/SharpCoreDB/DatabaseExtensions.cs @@ -143,7 +143,7 @@ private static DatabaseOptions DetectStorageMode(string dbPath, DatabaseConfig? /// docs/storage/SINGLE_FILE_SQL_LIMITATIONS.md for the complete support matrix. /// /// -internal sealed class SingleFileDatabase : IDatabase, IDisposable, IAsyncDisposable +internal sealed class SingleFileDatabase : IDatabase, IMetadataProvider, IDisposable, IAsyncDisposable { private readonly IStorageProvider _storageProvider; private readonly string _dbPath; @@ -335,6 +335,14 @@ public Task ExecuteBatchSQLAsync(IEnumerable sqlStatements, Cancellation return Task.CompletedTask; } + /// + /// The prepared-batch path is a multi-file (directory) storage optimisation; single-file storage + /// keeps the raw path. + /// + public int ExecuteBatchPrepared(string sqlTemplate, IReadOnlyList> parameterSets) => + throw new NotSupportedException( + "ExecuteBatchPrepared is supported on multi-file (directory) storage; in single-file mode use ExecuteBatchSQL with raw SQL."); + public void CreateUser(string username, string password) => throw new NotSupportedException("User management is not supported in single-file mode"); public bool Login(string username, string password) => false; @@ -980,7 +988,9 @@ private void ExecuteCreateTableInternal(string sql) var isAuto = new List(); var isNotNull = new List(); var isUnique = new List(); + var columnCollations = new List(); var primaryKeyIndex = -1; + var primaryKeyIndexes = new List(2); var foreignKeys = new List(); var uniqueConstraints = new List>(); @@ -1025,15 +1035,18 @@ private void ExecuteCreateTableInternal(string sql) { var pkColsStr = pkMatch.Groups[1].Value; var pkCols = pkColsStr.Split(',').Select(c => c.Trim().Trim('"', '`', '[', ']', '\'')).ToArray(); - if (pkCols.Length > 1) - { - throw new NotSupportedException("Composite primary keys are not supported in single-file mode."); - } - var pkColName = pkCols[0]; - var idx = columns.FindIndex(c => c.Equals(pkColName, StringComparison.OrdinalIgnoreCase)); - if (idx >= 0) + + // Plan 009 D1: every key column is recorded — a composite key is a UNIQUE over its columns, + // as SQLite enforces it — and the last key column stays the storage key (PrimaryKeyIndex), + // which is exactly what this form did before composite keys were modelled. + foreach (var pkColName in pkCols) { - primaryKeyIndex = idx; + var idx = columns.FindIndex(c => c.Equals(pkColName, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) + { + primaryKeyIndexes.Add(idx); + primaryKeyIndex = idx; + } } } continue; @@ -1064,9 +1077,15 @@ private void ExecuteCreateTableInternal(string sql) // ✅ One shared affinity resolver (see SqlTypeAffinity) instead of a local copy: DOUBLE and // FLOAT resolve to REAL and INT/SMALLINT to INTEGER, as SQLite's affinity rules require. - // This legacy path never read the UseSqliteIntegerAffinity opt-in, so integer affinity - // keeps its historical Int32 mapping here. - columnTypes.Add(SqlTypeAffinity.Resolve(typeStr, useSqliteIntegerAffinity: false)); + // The opt-in is honoured here: this legacy path used to hardcode `false`, so + // `UseSqliteIntegerAffinity = true` had no effect in single-file mode while the overflow + // message told the caller to set it. + columnTypes.Add(SqlTypeAffinity.Resolve(typeStr, useSqliteIntegerAffinity: _options.DatabaseConfig?.UseSqliteIntegerAffinity ?? false)); + + // `name TEXT COLLATE NOCASE` is parsed and persisted (plan 009 D2): the collation travels in the + // free bits 8-11 of the column flags, and a file written before this keeps zero there, which + // decodes to BINARY — the behaviour those files had. + columnCollations.Add(ParseDeclaredCollation(upper)); // Parse column constraints from the full definition string var isPrimary = upper.Contains("PRIMARY") && upper.Contains("KEY"); @@ -1118,16 +1137,23 @@ private void ExecuteCreateTableInternal(string sql) if (isPrimary) { primaryKeyIndex = colIndex; + primaryKeyIndexes.Add(colIndex); } colIndex++; } var table = new SingleFileTable(tableName, columns, columnTypes, primaryKeyIndex, isNotNull, isAuto, _storageProvider); + // Plan 009 D1: record every key column and mark the file as key-modelled, so a reopen enforces the + // same uniqueness it enforced on the session that created it. A file written before the marker keeps + // zero there and stays unenforced — its key columns were never recorded. + table.PrimaryKeyColumnIndexes = primaryKeyIndexes; + table.KeysModelled = primaryKeyIndexes.Count > 0; table.ForeignKeys = foreignKeys; table.ColumnCheckExpressions = columnCheckExpressions; table.TableCheckConstraints = tableCheckConstraints; table.UniqueConstraints = uniqueConstraints; + table.ColumnCollations = columnCollations; // B6: forward the database config's fixed-width flag so new single-file tables store // binary fixed-width records (with the overflow block) instead of JSON rows. table.SetFixedWidthRecords(_options.DatabaseConfig?.FixedWidthRecordLayout ?? false); @@ -1144,7 +1170,7 @@ private void ExecuteCreateTableInternal(string sql) for (int i = 0; i < columns.Count; i++) { var flags = ColumnFlags.None; - if (i == primaryKeyIndex) flags |= ColumnFlags.PrimaryKey; + if (primaryKeyIndexes.Contains(i)) flags |= ColumnFlags.PrimaryKey; if (i < isAuto.Count && isAuto[i]) flags |= ColumnFlags.AutoIncrement; if (i < isNotNull.Count && isNotNull[i]) flags |= ColumnFlags.NotNull; if (i < isUnique.Count && isUnique[i]) flags |= ColumnFlags.Unique; @@ -1157,6 +1183,12 @@ private void ExecuteCreateTableInternal(string sql) CheckLength = 0 }; SetColumnName(ref entry, columns[i]); + ColumnDefinitionEntry.SetCollation(ref entry, i < columnCollations.Count ? columnCollations[i] : CollationType.Binary); + if (primaryKeyIndexes.Contains(i)) + { + ColumnDefinitionEntry.MarkKeyModelled(ref entry); + } + columnEntries.Add(entry); } @@ -1164,6 +1196,33 @@ private void ExecuteCreateTableInternal(string sql) _tableDirectoryManager.Flush(); } + /// + /// Reads a column definition's declared collation (`… COLLATE NOCASE`) for the single-file DDL. Only the + /// names SharpCoreDB defines are recognised; anything else — including an absent clause — is BINARY, which + /// is also what a file written before the collation was persisted decodes to. + /// + /// The column definition, upper-cased. + /// The declared collation. + private static CollationType ParseDeclaredCollation(string upperColumnDefinition) + { + int at = upperColumnDefinition.IndexOf("COLLATE", StringComparison.Ordinal); + if (at < 0) + { + return CollationType.Binary; + } + + var rest = upperColumnDefinition[(at + "COLLATE".Length)..].TrimStart(); + int end = rest.IndexOfAny([' ', '\n', '\r', '\t', ',', ')']); + var name = (end < 0 ? rest : rest[..end]).Trim(); + + return name switch + { + "NOCASE" => CollationType.NoCase, + "RTRIM" => CollationType.RTrim, + _ => CollationType.Binary, + }; + } + /// /// Splits a SQL column definition string by commas, respecting quoted strings, brackets, and parentheses. /// Handles DEFAULT values containing commas inside string literals correctly. diff --git a/src/SharpCoreDB/Execution/SubqueryExecutor.cs b/src/SharpCoreDB/Execution/SubqueryExecutor.cs index 8aceacf9..41746212 100644 --- a/src/SharpCoreDB/Execution/SubqueryExecutor.cs +++ b/src/SharpCoreDB/Execution/SubqueryExecutor.cs @@ -459,9 +459,18 @@ private List> ApplyOrderBy( foreach (var item in orderBy.Items) { var key = AstExecutor.OrderKeySelector(item); - ordered = ordered is null - ? item.IsAscending ? rows.OrderBy(key, SqlOrderBy.KeyComparer.Instance) : rows.OrderByDescending(key, SqlOrderBy.KeyComparer.Instance) - : item.IsAscending ? ordered.ThenBy(key, SqlOrderBy.KeyComparer.Instance) : ordered.ThenByDescending(key, SqlOrderBy.KeyComparer.Instance); + if (ordered is null) + { + ordered = item.IsAscending + ? rows.OrderBy(key, SqlOrderBy.KeyComparer.Instance) + : rows.OrderByDescending(key, SqlOrderBy.KeyComparer.Instance); + } + else + { + ordered = item.IsAscending + ? ordered.ThenBy(key, SqlOrderBy.KeyComparer.Instance) + : ordered.ThenByDescending(key, SqlOrderBy.KeyComparer.Instance); + } } return [.. ordered!]; diff --git a/src/SharpCoreDB/Interfaces/IDatabase.cs b/src/SharpCoreDB/Interfaces/IDatabase.cs index cd7dd7d0..2bef6b19 100644 --- a/src/SharpCoreDB/Interfaces/IDatabase.cs +++ b/src/SharpCoreDB/Interfaces/IDatabase.cs @@ -59,6 +59,20 @@ public interface IDatabase : IAsyncDisposable /// Collection of SQL statements to execute. void ExecuteBatchSQL(IEnumerable sqlStatements); + /// + /// Executes a parameterised batch of ONE canonical statement shape (a prepared statement): the SQL + /// template is classified once and each row binds its parameters, so no statement is scanned or + /// parsed per row. The template must be a canonical + /// UPDATE <t> SET <col> = @setParam WHERE <key> = @whereParam or + /// DELETE FROM <t> WHERE <key> = @whereParam; parameter keys include the leading + /// @. This is the prepared path the raw-SQL batch cannot take (measured by the + /// --pk-prepared benchmark arm). + /// + /// The parameterised canonical UPDATE or DELETE template. + /// One parameter dictionary (keyed by @name) per row. + /// The number of rows matched, updated or deleted. + int ExecuteBatchPrepared(string sqlTemplate, IReadOnlyList> parameterSets); + /// /// Executes multiple SQL commands in a batch asynchronously. /// diff --git a/src/SharpCoreDB/Platform/PlatformOptimizations.cs b/src/SharpCoreDB/Platform/PlatformOptimizations.cs index 38ea54a2..8c93a0c7 100644 --- a/src/SharpCoreDB/Platform/PlatformOptimizations.cs +++ b/src/SharpCoreDB/Platform/PlatformOptimizations.cs @@ -182,12 +182,29 @@ private static unsafe bool FastMemoryEqualsStandard(byte* ptr1, byte* ptr2, int /// Gets the widest SIMD register width this machine can actually run, in bytes /// (64 = AVX-512, 32 = AVX2, 16 = SSE2/NEON, 1 = scalar fallback). /// - public static int SimdRegisterWidthBytes => - System.Runtime.Intrinsics.X86.Avx512F.IsSupported ? Vector512.Count - : System.Runtime.Intrinsics.X86.Avx2.IsSupported ? Vector256.Count - : System.Runtime.Intrinsics.Arm.AdvSimd.IsSupported ? Vector128.Count - : System.Runtime.Intrinsics.X86.Sse2.IsSupported ? Vector128.Count - : 1; + public static int SimdRegisterWidthBytes + { + get + { + if (System.Runtime.Intrinsics.X86.Avx512F.IsSupported) + { + return Vector512.Count; + } + + if (System.Runtime.Intrinsics.X86.Avx2.IsSupported) + { + return Vector256.Count; + } + + if (System.Runtime.Intrinsics.Arm.AdvSimd.IsSupported || + System.Runtime.Intrinsics.X86.Sse2.IsSupported) + { + return Vector128.Count; + } + + return 1; + } + } /// /// Gets platform optimization information for diagnostics diff --git a/src/SharpCoreDB/Query/SimdFilter.cs b/src/SharpCoreDB/Query/SimdFilter.cs index c05a2cd4..85feab80 100644 --- a/src/SharpCoreDB/Query/SimdFilter.cs +++ b/src/SharpCoreDB/Query/SimdFilter.cs @@ -52,10 +52,19 @@ private enum MaskOp /// Element count of the widest supported vector, or 1 when only the scalar path is available. public static int VectorSize() where T : struct - => Avx512F.IsSupported ? Vector512.Count - : Avx2.IsSupported ? Vector256.Count - : Sse2.IsSupported ? Vector128.Count - : 1; + { + if (Avx512F.IsSupported) + { + return Vector512.Count; + } + + if (Avx2.IsSupported) + { + return Vector256.Count; + } + + return Sse2.IsSupported ? Vector128.Count : 1; + } // ======================================== // Integer Filters diff --git a/src/SharpCoreDB/Services/SimdHelper.Deserialization.cs b/src/SharpCoreDB/Services/SimdHelper.Deserialization.cs index 87e9acb9..e7b3ac3a 100644 --- a/src/SharpCoreDB/Services/SimdHelper.Deserialization.cs +++ b/src/SharpCoreDB/Services/SimdHelper.Deserialization.cs @@ -259,13 +259,20 @@ public static unsafe int DeserializeBatchDouble(ReadOnlySpan data, Span data, Span data) var v = Vector128.LoadUnsafe(ref *(ptr + i)); if (Sse41.IsSupported) { - var converted = Sse41.ConvertToVector128Int64(v); - accumulator = Sse2.Add(accumulator, converted); + // ConvertToVector128Int64 widens only the LOW two int32s of the lane, so the upper + // half is shifted into place and accumulated too — up to 2.1.4 it was skipped, and a + // five-element span summed as 8 instead of 15. + var low = Sse41.ConvertToVector128Int64(v); + var high = Sse41.ConvertToVector128Int64(Sse2.ShiftRightLogical128BitLane(v, 8)); + accumulator = Sse2.Add(accumulator, Sse2.Add(low, high)); + } + else + { + sum += data[i] + (long)data[i + 1] + data[i + 2] + data[i + 3]; } } // Horizontal sum - sum = accumulator.GetElement(0) + accumulator.GetElement(1); + sum += accumulator.GetElement(0) + accumulator.GetElement(1); } } diff --git a/src/SharpCoreDB/Services/SqlOrderBy.cs b/src/SharpCoreDB/Services/SqlOrderBy.cs index 988157f9..e04fdc67 100644 --- a/src/SharpCoreDB/Services/SqlOrderBy.cs +++ b/src/SharpCoreDB/Services/SqlOrderBy.cs @@ -37,12 +37,20 @@ public int Compare(object? x, object? y) bool yNull = y is null or DBNull; if (xNull || yNull) { - return xNull == yNull ? 0 : xNull ? -1 : 1; + if (xNull == yNull) + { + return 0; + } + + return xNull ? -1 : 1; + } + + if (x is string xs && y is string ys) + { + return string.CompareOrdinal(xs, ys); } - return x is string xs && y is string ys - ? string.CompareOrdinal(xs, ys) - : SqlScalarExpression.TryCompare(x, y, out var c) ? c : 0; + return SqlScalarExpression.TryCompare(x, y, out var comparison) ? comparison : 0; } } diff --git a/src/SharpCoreDB/Services/SqlParser.DML.cs b/src/SharpCoreDB/Services/SqlParser.DML.cs index 6fc021b7..d74137a8 100644 --- a/src/SharpCoreDB/Services/SqlParser.DML.cs +++ b/src/SharpCoreDB/Services/SqlParser.DML.cs @@ -1082,11 +1082,10 @@ private List> ExecuteSelectQuery(string sql, string[] // COLLATE and NULLS FIRST/LAST. The token-based `orderBy` above sees only the first key, so `ORDER BY grp, name` // came back unsorted. A list SqlOrderBy cannot read (vec_distance_* keeps its vector-index route below) leaves // the previous handling in place. + var orderTermCount = (limitIdx > orderIdx ? limitIdx : parts.Length) - orderIdx - 2; var orderTerms = orderIdx > 0 && parts.Length > orderIdx + 2 && parts[orderIdx + 1].Equals(SqlConstants.BY, StringComparison.OrdinalIgnoreCase) - ? SqlOrderBy.TryParse( - string.Join(" ", parts.Skip(orderIdx + 2).Take((limitIdx > orderIdx ? limitIdx : parts.Length) - orderIdx - 2)), - selectClause) + ? SqlOrderBy.TryParse(string.Join(" ", parts.Skip(orderIdx + 2).Take(orderTermCount)), selectClause) : null; if (!this.tables.ContainsKey(tableName)) @@ -1234,10 +1233,18 @@ private bool TryExecuteExistsProjection(string sql, bool noEncrypt, out List(StringComparer.OrdinalIgnoreCase) { [columnName] = exists ? 1L : 0L }]; return true; diff --git a/src/SharpCoreDB/Services/SqlParser.InformationSchema.cs b/src/SharpCoreDB/Services/SqlParser.InformationSchema.cs index 956617c8..226a492a 100644 --- a/src/SharpCoreDB/Services/SqlParser.InformationSchema.cs +++ b/src/SharpCoreDB/Services/SqlParser.InformationSchema.cs @@ -800,13 +800,18 @@ private static List> ApplyInformationSchemaOrdering( var column = ResolveInformationSchemaOrderColumn(spec, projection, declaredColumns); object? KeySelector(Dictionary row) => row.TryGetValue(column, out var value) ? value : null; - ordered = ordered is null - ? descending + if (ordered is null) + { + ordered = descending ? rows.OrderByDescending(KeySelector, InformationSchemaValueComparer.Instance) - : rows.OrderBy(KeySelector, InformationSchemaValueComparer.Instance) - : descending + : rows.OrderBy(KeySelector, InformationSchemaValueComparer.Instance); + } + else + { + ordered = descending ? ordered.ThenByDescending(KeySelector, InformationSchemaValueComparer.Instance) : ordered.ThenBy(KeySelector, InformationSchemaValueComparer.Instance); + } } return ordered?.ToList() ?? rows; diff --git a/src/SharpCoreDB/Services/SqlScalarExpression.cs b/src/SharpCoreDB/Services/SqlScalarExpression.cs index 5fd90a2f..fea81ec8 100644 --- a/src/SharpCoreDB/Services/SqlScalarExpression.cs +++ b/src/SharpCoreDB/Services/SqlScalarExpression.cs @@ -279,9 +279,12 @@ private Node ParseUnary() { _pos++; var operand = ParseUnary(); - return operand is Literal { Value: long l } ? new Literal(-l) - : operand is Literal { Value: double d } ? new Literal(-d) - : new Negate(operand); + if (operand is Literal { Value: long l }) + { + return new Literal(-l); + } + + return operand is Literal { Value: double d } ? new Literal(-d) : new Negate(operand); } if (_pos < text.Length && text[_pos] == '+') @@ -376,7 +379,12 @@ private Node ReadCall(string word) int depth = 0; while (_pos < text.Length && (text[_pos] != ')' || depth > 0)) { - depth += text[_pos] == '(' ? 1 : text[_pos] == ')' ? -1 : 0; + depth += text[_pos] switch + { + '(' => 1, + ')' => -1, + _ => 0, + }; _pos++; } @@ -667,9 +675,12 @@ internal static bool TryInvokeScalarFunction(string upperName, object?[] args, o var v => (long)ToText(v).Length, }; case "SUBSTR" or "SUBSTRING": - return a.Length is < 2 or > 3 || Arg(0) is null || Arg(1) is null || (a.Length == 3 && Arg(2) is null) - ? null - : Substr(ToText(Arg(0)), ToInteger(Arg(1)), a.Length == 3 ? ToInteger(Arg(2)) : null); + if (a.Length is < 2 or > 3 || Arg(0) is null || Arg(1) is null || (a.Length == 3 && Arg(2) is null)) + { + return null; + } + + return Substr(ToText(Arg(0)), ToInteger(Arg(1)), a.Length == 3 ? ToInteger(Arg(2)) : null); case "TRIM" or "LTRIM" or "RTRIM": { if (Arg(0) is null || (a.Length > 1 && Arg(1) is null)) @@ -714,7 +725,12 @@ internal static bool TryInvokeScalarFunction(string upperName, object?[] args, o case "NULLIF": return a.Length == 2 && TryCompare(Arg(0), Arg(1), out var cmp) && cmp == 0 ? null : Arg(0); case "IIF": - return a.Length == 3 ? (IsTrue(Arg(0)) == true ? Arg(1) : Arg(2)) : null; + if (a.Length != 3) + { + return null; + } + + return IsTrue(Arg(0)) == true ? Arg(1) : Arg(2); case "TYPEOF": return Arg(0) switch { @@ -962,10 +978,23 @@ double d when double.IsInteger(d) && Math.Abs(d) < 9.2e18 => (long)d, private static long ToInteger(object? value) => ToNumber(value) switch { long l => l, - double d when !double.IsNaN(d) => d >= 9.2e18 ? long.MaxValue : d <= -9.2e18 ? long.MinValue : (long)Math.Truncate(d), + double d when !double.IsNaN(d) => ClampToLong(d), _ => 0L, }; + /// Truncates a finite double to a long, saturating outside the representable range. + /// The number to truncate. + /// The truncated value, or the saturated bound. + private static long ClampToLong(double value) + { + if (value >= 9.2e18) + { + return long.MaxValue; + } + + return value <= -9.2e18 ? long.MinValue : (long)Math.Truncate(value); + } + private static double ToReal(object? value) => ToNumber(value) switch { long l => l, @@ -1047,7 +1076,15 @@ internal static bool TryCompare(object? left, object? right, out int comparison) return true; } - private static int ClassOf(object value, bool numeric) => numeric ? 0 : value is byte[] ? 2 : 1; + private static int ClassOf(object value, bool numeric) + { + if (numeric) + { + return 0; + } + + return value is byte[] ? 2 : 1; + } private static bool IsWholeNumber(string text) { diff --git a/src/SharpCoreDB/Services/Storage.Append.cs b/src/SharpCoreDB/Services/Storage.Append.cs index 1acfece3..41d8f5ff 100644 --- a/src/SharpCoreDB/Services/Storage.Append.cs +++ b/src/SharpCoreDB/Services/Storage.Append.cs @@ -702,21 +702,24 @@ private bool BufferOrWriteOverwriteInPlace(string path, long offset, byte[] reco { if (inTransaction) { - // Only records already flushed to disk (offset below the buffered-appends boundary) - // can be overwritten in place; still-buffered records fall back to append. - if (!bufferedFileBaseLengths.TryGetValue(path, out long baseLength)) + lock (appendLock) { - baseLength = File.Exists(path) ? new FileInfo(path).Length : 0; - bufferedFileBaseLengths[path] = baseLength; - } + // Only records already flushed to disk (offset below the buffered-appends boundary) + // can be overwritten in place; still-buffered records fall back to append. + // The base-length cache is a plain Dictionary and is therefore resolved INSIDE this + // lock: the contiguous fast-patch batch calls this method from parallel workers + // (plan 006 US2), and an outside-the-lock read/write would race on it. + if (!bufferedFileBaseLengths.TryGetValue(path, out long baseLength)) + { + baseLength = File.Exists(path) ? new FileInfo(path).Length : 0; + bufferedFileBaseLengths[path] = baseLength; + } - if (offset + 4 + recordLength > baseLength) - { - return false; - } + if (offset + 4 + recordLength > baseLength) + { + return false; + } - lock (appendLock) - { if (!bufferedOverwrites.TryGetValue(path, out var overwrites)) { overwrites = new Dictionary(); diff --git a/src/SharpCoreDB/SharpCoreDB.csproj b/src/SharpCoreDB/SharpCoreDB.csproj index 929f6e3e..c3ffe7a5 100644 --- a/src/SharpCoreDB/SharpCoreDB.csproj +++ b/src/SharpCoreDB/SharpCoreDB.csproj @@ -36,9 +36,9 @@ SharpCoreDB - 2.2.0 + 2.2.1 2.2.0.0 - 2.2.0.0 + 2.2.1.0 MPCoreDeveloper SharpCoreDB SharpCoreDB diff --git a/src/SharpCoreDB/SingleFileTable.cs b/src/SharpCoreDB/SingleFileTable.cs index 38204ea1..095ae3fd 100644 --- a/src/SharpCoreDB/SingleFileTable.cs +++ b/src/SharpCoreDB/SingleFileTable.cs @@ -92,6 +92,12 @@ internal void SetFixedWidthInlineValueBytes(int inlineValueBytes) // Maintained incrementally on every row mutation and rebuilt on cache load / rollback. private readonly Dictionary>> _pkIndex = new(StringComparer.Ordinal); + /// + /// The tuple form of every row's modelled primary-key columns (see ), for the + /// single-file uniqueness check. Empty while the file predates the key-modelled marker. + /// + private readonly HashSet _pkTupleKeys = new(StringComparer.Ordinal); + // Comparison operators in precedence order for simple-condition fast-path parsing // (must match EvaluateSingleCondition's ordering: >= before >, etc.). private static readonly string[] SingleFileConditionOperators = [">=", "<=", "!=", "<>", "=", ">", "<"]; @@ -196,6 +202,22 @@ public SingleFileTable(string tableName, List columns, List co public string DataFile { get; set; } = storageProvider.RootPath; /// + /// + /// Gets or sets the column indexes of the table's primary key — every key column, in declaration order. + /// Single-file storage records all of them (plan 009 D1): a composite key is a UNIQUE constraint over + /// the tuple, and keeps the last key column as the storage key, exactly as + /// it behaved before composite keys were modelled. + /// + public List PrimaryKeyColumnIndexes { get; set; } = []; + + /// + /// Gets or sets a value indicating whether this table's key columns were written by a version that + /// models them (the marker). Only then is single-file + /// PRIMARY KEY uniqueness enforced: an old file's key columns were never recorded, so enforcing there + /// could reject legitimate rows. + /// + public bool KeysModelled { get; set; } + public int PrimaryKeyIndex { get; set; } = -1; /// @@ -256,6 +278,7 @@ public void Insert(Dictionary row) { ApplyDefaults(row); ValidateNotNull(row, rowIndex: null); + EnforceTupleUniqueness(row); _rowCache.Add(row); IndexRow(row); _isDirty = true; @@ -279,11 +302,26 @@ public long[] InsertBatch(List> rows) lock (_tableLock) { - // Every row is checked before any is cached, so a NOT NULL violation leaves no part of the batch behind. + // Every row is checked before any is cached, so a NOT NULL or duplicate-key violation leaves no + // part of the batch behind. The duplicate check covers both the rows already held and the rows + // of this statement (a key repeated inside it must fail too). + HashSet? batchKeys = KeysModelled && PrimaryKeyColumnIndexes.Count > 0 + ? new HashSet(StringComparer.Ordinal) + : null; for (int i = 0; i < rows.Count; i++) { ApplyDefaults(rows[i]); ValidateNotNull(rows[i], rowIndex: i); + + if (batchKeys is not null) + { + var tupleKey = GetTupleKey(rows[i]); + if (tupleKey is not null && (_pkTupleKeys.Contains(tupleKey) || !batchKeys.Add(tupleKey))) + { + var columns = string.Join(", ", PrimaryKeyColumnIndexes.Select(c => $"{Name}.{Columns[c]}")); + throw new InvalidOperationException($"UNIQUE constraint failed: {columns}"); + } + } } for (int i = 0; i < rows.Count; i++) @@ -369,9 +407,10 @@ private bool TryGetPkLookupResults(string? where, string? orderBy, bool asc, out if (!string.IsNullOrWhiteSpace(orderBy)) { + var comparer = GetOrderComparer(orderBy); results = asc - ? [.. results.OrderBy(row => GetOrderKey(row, orderBy))] - : [.. results.OrderByDescending(row => GetOrderKey(row, orderBy))]; + ? [.. results.OrderBy(row => GetOrderKey(row, orderBy), comparer)] + : [.. results.OrderByDescending(row => GetOrderKey(row, orderBy), comparer)]; } return true; @@ -389,7 +428,7 @@ private bool TryGetPkLookupResults(string? where, string? orderBy, bool asc, out return condition; } - private static IEnumerable> ApplyCondition( + private IEnumerable> ApplyCondition( IEnumerable> rows, string? where) { var condition = NormalizeWhereCondition(where); @@ -399,22 +438,51 @@ private static IEnumerable> ApplyCondition( } // Fast path: a simple "col op value" condition is parsed ONCE and - // evaluated per row without per-row regex/IN/AND/OR parsing. - var fastPredicate = TryCreateSimpleConditionPredicate(condition); + // evaluated per row without per-row regex/IN/AND/OR parsing. A column that declares a non-binary + // collation keeps the condition off it: the compiled predicate compares ordinally, so a NOCASE + // column would miss the case-insensitive matches the declared collation promises. + var fastPredicate = ConditionTouchesNonBinaryCollation(condition) + ? null + : TryCreateSimpleConditionPredicate(condition); return fastPredicate is not null ? rows.Where(fastPredicate) : rows.Where(row => EvaluateCondition(row, condition)); } - private static IEnumerable> ApplyOrderBy( + private IEnumerable> ApplyOrderBy( IEnumerable> rows, string orderBy, bool asc) { - if (asc) + var comparer = GetOrderComparer(orderBy); + return asc + ? rows.OrderBy(row => GetOrderKey(row, orderBy), comparer) + : rows.OrderByDescending(row => GetOrderKey(row, orderBy), comparer); + } + + /// + /// The comparer an ORDER BY on uses: the column's declared collation for text + /// (single-file mode now persists it), NULLs first — the order SQLite sorts them in for both directions. + /// + /// The ORDER BY column. + /// The comparer for the row keys. + private IComparer GetOrderComparer(string column) => + Comparer.Create((a, b) => CompareOrderKeys(a, b, column)); + + /// Compares two ORDER BY keys, honouring the column's collation for text and NULLs-first. + private int CompareOrderKeys(object? a, object? b, string column) + { + bool aNull = a is null or DBNull; + bool bNull = b is null or DBNull; + if (aNull || bNull) + { + return aNull == bNull ? 0 : (aNull ? -1 : 1); + } + + if (a is string first && b is string second) { - return rows.OrderBy(row => GetOrderKey(row, orderBy)); + return CompareText(first, second, CollationForColumn(column)); } - return rows.OrderByDescending(row => GetOrderKey(row, orderBy)); + return Comparer.Default.Compare(a, b); } private static object? GetOrderKey(Dictionary row, string orderBy) @@ -423,6 +491,41 @@ private static IEnumerable> ApplyOrderBy( /// public void Update(string? where, Dictionary updates) => UpdateAffectedCount(where, updates); + /// + /// True when an UPDATE sets a key column: the storage key (always) or — when the file models its keys — + /// any composite key column. Both the PK index and the tuple set have to follow such an update. + /// + private bool UpdatesTouchKeyColumn(Dictionary updates) => + UpdatesTouchKeyColumn((IEnumerable)updates.Keys); + + /// + /// True when any of the update's column names is a key column: the storage key always, and — when the + /// file models its keys — any composite key column. Both the PK index and the tuple set have to follow. + /// + private bool UpdatesTouchKeyColumn(IEnumerable columnNames) + { + if (PrimaryKeyIndex < 0) + { + return false; + } + + foreach (var column in columnNames) + { + if (string.Equals(column, Columns[PrimaryKeyIndex], StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (KeysModelled && + PrimaryKeyColumnIndexes.Any(i => string.Equals(column, Columns[i], StringComparison.OrdinalIgnoreCase))) + { + return true; + } + } + + return false; + } + /// public int UpdateAffectedCount(string? where, Dictionary updates) // NOSONAR:S3776 - single-pass single-file UPDATE with PK/hash/scan resolution + change bookkeeping; the SQL row store shares this path { @@ -436,16 +539,18 @@ private static IEnumerable> ApplyOrderBy( condition = condition[6..].Trim(); } - bool updatesTouchPk = PrimaryKeyIndex >= 0 && - updates.Keys.Any(k => string.Equals(k, Columns[PrimaryKeyIndex], StringComparison.OrdinalIgnoreCase)); + bool updatesTouchPk = UpdatesTouchKeyColumn(updates); // SQLite raises NOT NULL only for a row the UPDATE actually changes, so it is checked at the first match, // before anything is written. var notNullViolation = FindNotNullViolation(updates); - int affected = 0; + int affected; lock (_tableLock) { + // Two phases, as SQLite's statement atomicity requires: every NOT NULL and key-move check runs + // before the first row is written, so a rejected UPDATE leaves the table exactly as it was. + var matched = new List<(Dictionary Row, Dictionary Values)>(); foreach (var row in _rowCache) { if (string.IsNullOrWhiteSpace(condition) || EvaluateCondition(row, condition)) @@ -455,27 +560,11 @@ private static IEnumerable> ApplyOrderBy( throw new InvalidOperationException($"Column '{notNullViolation}' cannot be NULL"); } - string? oldPkKey = updatesTouchPk ? GetPkKey(row) : null; - - foreach (var update in updates) - { - row[update.Key] = update.Value; - } - - if (oldPkKey is not null) - { - var newPkKey = GetPkKey(row); - if (!string.Equals(oldPkKey, newPkKey, StringComparison.Ordinal)) - { - UnindexRow(row, oldPkKey); - IndexRow(row); - } - } - - _isDirty = true; - affected++; + matched.Add((row, updates)); } } + + affected = ApplyMatchedUpdates(matched, updatesTouchPk); } // ✅ CRITICAL FIX: Only flush if not in transaction @@ -508,11 +597,9 @@ public int UpdateAffectedCount( condition = condition[6..].Trim(); } - bool updatesTouchPk = PrimaryKeyIndex >= 0 && - updates.Keys.Concat(computed.Select(c => c.Key)) - .Any(k => string.Equals(k, Columns[PrimaryKeyIndex], StringComparison.OrdinalIgnoreCase)); + bool updatesTouchPk = UpdatesTouchKeyColumn(updates.Keys.Concat(computed.Select(c => c.Key))); - int affected = 0; + int affected; lock (_tableLock) { // Every value is computed from the row as it was before the statement, and checked, before any row changes. @@ -538,28 +625,7 @@ public int UpdateAffectedCount( matched.Add((row, values)); } - foreach (var (row, values) in matched) - { - string? oldPkKey = updatesTouchPk ? GetPkKey(row) : null; - - foreach (var update in values) - { - row[update.Key] = update.Value; - } - - if (oldPkKey is not null) - { - var newPkKey = GetPkKey(row); - if (!string.Equals(oldPkKey, newPkKey, StringComparison.Ordinal)) - { - UnindexRow(row, oldPkKey); - IndexRow(row); - } - } - - _isDirty = true; - affected++; - } + affected = ApplyMatchedUpdates(matched, updatesTouchPk); } if (AutoFlush && _isDirty && !_isInTransaction) @@ -582,7 +648,7 @@ public void UpdateBatch(Dictionary> updates) if (PrimaryKeyIndex < 0) return; var pkColumn = Columns[PrimaryKeyIndex]; - bool updatesTouchPk = updates.Keys.Any(k => string.Equals(k?.ToString(), pkColumn, StringComparison.OrdinalIgnoreCase)); + bool updatesTouchPk = updates.Values.Any(UpdatesTouchKeyColumn); lock (_tableLock) { @@ -598,24 +664,21 @@ public void UpdateBatch(Dictionary> updates) continue; } - string? oldPkKey = updatesTouchPk ? GetPkKey(row) : null; - - foreach (var update in rowUpdates) + if (updatesTouchPk) { - row[update.Key] = update.Value; + // A moved key must not land on another row (plan 009 D1); the shared applier checks the + // prospective key set before writing and re-indexes afterwards. + ApplyMatchedUpdates([(row, rowUpdates)], true); } - - if (oldPkKey is not null) + else { - var newPkKey = GetPkKey(row); - if (!string.Equals(oldPkKey, newPkKey, StringComparison.Ordinal)) + foreach (var update in rowUpdates) { - UnindexRow(row, oldPkKey); - IndexRow(row); + row[update.Key] = update.Value; } - } - _isDirty = true; + _isDirty = true; + } } } @@ -644,6 +707,7 @@ public void Delete(string? where) { _rowCache.Clear(); _pkIndex.Clear(); + _pkTupleKeys.Clear(); } else { @@ -749,8 +813,8 @@ public List> DeleteAffectedRows(string? where) /// /// /// ✅ FIX (Known Issue 3): Update by primary key now works in single-file mode. - /// The primary key value itself is not re-validated after update; if the caller changes - /// the PK column, the row becomes addressable only by the new value. + /// A key-column change is validated like every other UPDATE path (plan 009 D1): the prospective key must + /// not land on another row, and the row becomes addressable only by its new value. /// public bool UpdateByPrimaryKey(object key, Dictionary updates) { @@ -770,24 +834,7 @@ public bool UpdateByPrimaryKey(object key, Dictionary updates) if (keyStr is not null && _pkIndex.TryGetValue(keyStr, out var rows) && rows.Count > 0) { var row = rows[0]; - string? oldPkKey = GetPkKey(row); - - foreach (var update in updates) - { - row[update.Key] = update.Value; - } - - if (oldPkKey is not null) - { - var newPkKey = GetPkKey(row); - if (!string.Equals(oldPkKey, newPkKey, StringComparison.Ordinal)) - { - UnindexRow(row, oldPkKey); - IndexRow(row); - } - } - - _isDirty = true; + ApplyMatchedUpdates([(row, updates)], UpdatesTouchKeyColumn(updates)); found = true; } } @@ -1214,6 +1261,8 @@ private void LoadSchemaFromProvider(string tableName) var types = new List(columnDefs.Count); var isAuto = new List(columnDefs.Count); var isNotNull = new List(columnDefs.Count); + var collations = new List(columnDefs.Count); + var primaryKeyColumns = new List(2); foreach (var entry in columnDefs) { @@ -1221,17 +1270,23 @@ private void LoadSchemaFromProvider(string tableName) types.Add((DataType)entry.DataType); isAuto.Add((entry.Flags & (uint)ColumnFlags.AutoIncrement) != 0); isNotNull.Add((entry.Flags & (uint)ColumnFlags.NotNull) != 0); + collations.Add(ColumnDefinitionEntry.GetCollation(entry)); if ((entry.Flags & (uint)ColumnFlags.PrimaryKey) != 0) { + primaryKeyColumns.Add(columns.Count - 1); PrimaryKeyIndex = columns.Count - 1; } + + KeysModelled |= ColumnDefinitionEntry.IsKeyModelled(entry); } Columns = columns; ColumnTypes = types; IsAuto = isAuto; IsNotNull = isNotNull; + ColumnCollations = collations; + PrimaryKeyColumnIndexes = primaryKeyColumns; } private void InitializeColumnMetadata() @@ -1335,20 +1390,181 @@ internal void RollbackTransaction() return null; } + /// + /// The composite primary-key form of a row — its key columns' canonical string forms joined by U+001F, + /// or null when any key column is NULL (SQLite treats NULLs as distinct, so such a row cannot + /// collide) or the table models no key. + /// + private string? GetTupleKey(Dictionary row) + { + if (PrimaryKeyColumnIndexes.Count == 0) + { + return null; + } + + var parts = new string[PrimaryKeyColumnIndexes.Count]; + for (int i = 0; i < parts.Length; i++) + { + int columnIndex = PrimaryKeyColumnIndexes[i]; + if (columnIndex < 0 || columnIndex >= Columns.Count || + !row.TryGetValue(Columns[columnIndex], out var value) || value is null or DBNull) + { + return null; + } + + parts[i] = CanonicalKeyPart(columnIndex, value); + } + + return string.Join('\u001F', parts); + } + + /// + /// The canonical form of one key-column value for the tuple key, under the column's declared collation + /// (plan 009 D2): upper-invariant for COLLATE NOCASE, culture-upper for + /// COLLATE UNICODE, trailing whitespace trimmed for COLLATE RTRIM, invariant text otherwise. + /// Canonicalising here keeps the uniqueness set consistent with the collation-aware WHERE and ORDER BY + /// evaluators — a NOCASE key rejects 'bb' after 'BB' just as WHERE k = 'BB' finds both. + /// + /// Index of the key column. + /// The row's value for that column. + /// The canonical key part. + private string CanonicalKeyPart(int columnIndex, object value) + { + var text = Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty; + var collation = columnIndex < ColumnCollations.Count ? ColumnCollations[columnIndex] : CollationType.Binary; + return collation switch + { + CollationType.NoCase => text.ToUpperInvariant(), + CollationType.UnicodeCaseInsensitive => text.ToUpper(System.Globalization.CultureInfo.CurrentCulture), + CollationType.RTrim => text.TrimEnd(), + _ => text, + }; + } + + /// + /// Applies a fully validated multi-row UPDATE. The prospective primary-key tuple set is built first and + /// every moved key is checked against it — a key move must not land on another row, including two matched + /// rows moving onto the same key (plan 009 D1) — so a rejected statement writes nothing. The caller holds + /// and has already applied the NOT NULL checks. + /// + /// Each matched row with the values the statement applies to it. + /// Whether any applied column participates in the key. + /// The number of rows changed. + private int ApplyMatchedUpdates( + List<(Dictionary Row, Dictionary Values)> matched, + bool updatesTouchKey) + { + HashSet? reserved = null; + if (updatesTouchKey && KeysModelled && PrimaryKeyColumnIndexes.Count > 0) + { + reserved = new HashSet(_pkTupleKeys, StringComparer.Ordinal); + foreach (var (row, _) in matched) + { + if (GetTupleKey(row) is { } oldKey) + { + reserved.Remove(oldKey); + } + } + + foreach (var (row, values) in matched) + { + var prospective = new Dictionary(row); + foreach (var update in values) + { + if (prospective.ContainsKey(update.Key)) + { + prospective[update.Key] = update.Value; + } + } + + // Add returns false when the key already belongs to an untouched row or an earlier move. + if (GetTupleKey(prospective) is { } newKey && !reserved.Add(newKey)) + { + ThrowUniqueViolation(); + } + } + } + + foreach (var (row, values) in matched) + { + string? oldPkKey = updatesTouchKey ? GetPkKey(row) : null; + foreach (var update in values) + { + row[update.Key] = update.Value; + } + + if (oldPkKey is not null) + { + var newPkKey = GetPkKey(row); + if (!string.Equals(oldPkKey, newPkKey, StringComparison.Ordinal)) + { + UnindexRow(row, oldPkKey); + IndexRow(row); + } + } + + _isDirty = true; + } + + // The prospective set replaces the old one: it carries every untouched row's key plus each moved key. + if (reserved is not null) + { + _pkTupleKeys.Clear(); + _pkTupleKeys.UnionWith(reserved); + } + + return matched.Count; + } + + /// Throws SQLite's UNIQUE error for the table's modelled key columns. + private void ThrowUniqueViolation() => + throw new InvalidOperationException( + $"UNIQUE constraint failed: {string.Join(", ", PrimaryKeyColumnIndexes.Select(i => $"{Name}.{Columns[i]}"))}"); + + /// + /// Enforces the modelled primary key (plan 009 D1): with the marker present, the key tuple must be + /// unique — a composite key is a UNIQUE constraint over its columns, as SQLite enforces it in a rowid + /// table. A file written before the marker carries no modelled key, so nothing is enforced there (its + /// key columns were never recorded, and enforcing could reject legitimate rows). + /// + /// The row about to be added, or the updated row. + /// The tuple this row already occupied (an UPDATE that keeps its key), or null. + private void EnforceTupleUniqueness(Dictionary row, string? replacing = null) + { + if (!KeysModelled || PrimaryKeyColumnIndexes.Count == 0) + { + return; + } + + var key = GetTupleKey(row); + if (key is null || string.Equals(key, replacing, StringComparison.Ordinal) || !_pkTupleKeys.Contains(key)) + { + return; + } + + ThrowUniqueViolation(); + } + /// Adds a row to the primary-key index (no-op without a PK or null PK). private void IndexRow(Dictionary row) { var key = GetPkKey(row); - if (key is null) - return; - - if (!_pkIndex.TryGetValue(key, out var list)) + if (key is not null) { - list = new List>(1); - _pkIndex[key] = list; + if (!_pkIndex.TryGetValue(key, out var list)) + { + list = new List>(1); + _pkIndex[key] = list; + } + + list.Add(row); } - list.Add(row); + var tupleKey = GetTupleKey(row); + if (tupleKey is not null) + { + _pkTupleKeys.Add(tupleKey); + } } /// Removes a row from the primary-key index. is the key to @@ -1357,10 +1573,7 @@ private void IndexRow(Dictionary row) private void UnindexRow(Dictionary row, string? key = null) { key ??= GetPkKey(row); - if (key is null) - return; - - if (_pkIndex.TryGetValue(key, out var list)) + if (key is not null && _pkIndex.TryGetValue(key, out var list)) { list.Remove(row); if (list.Count == 0) @@ -1368,12 +1581,19 @@ private void UnindexRow(Dictionary row, string? key = null) _pkIndex.Remove(key); } } + + var tupleKey = GetTupleKey(row); + if (tupleKey is not null) + { + _pkTupleKeys.Remove(tupleKey); + } } /// Rebuilds the primary-key index from the current row cache (cache load / rollback). private void RebuildPkIndex() { _pkIndex.Clear(); + _pkTupleKeys.Clear(); foreach (var row in _rowCache) { IndexRow(row); @@ -1894,7 +2114,66 @@ private static bool CompareNumeric(string op, T left, T right) } - private static bool EvaluateCondition(Dictionary row, string condition) + /// + /// The collation a condition/ORDER BY on uses: the column's declared collation + /// (single-file mode persists it), binary when the column declares none. + /// + /// The column name as written in the statement. + /// The column's collation. + private CollationType CollationForColumn(string column) + { + for (int i = 0; i < Columns.Count; i++) + { + if (!string.Equals(Columns[i], column, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + return i < ColumnCollations.Count ? ColumnCollations[i] : CollationType.Binary; + } + + return CollationType.Binary; + } + + /// + /// Compares two text values under a collation: ordinal for Binary (and Null), ordinal-ignore-case for + /// NoCase, culture-ignore-case for UnicodeCaseInsensitive, and ordinal after trimming trailing whitespace + /// for RTrim — SQLite's RTRIM, where 'abc ' = 'abc'. + /// + /// The row's value. + /// The literal or bound value. + /// The column's collation. + /// The comparison result, as . + private static int CompareText(string a, string b, CollationType collation) => + collation switch + { + CollationType.NoCase => string.Compare(a, b, StringComparison.OrdinalIgnoreCase), + CollationType.UnicodeCaseInsensitive => string.Compare(a, b, StringComparison.CurrentCultureIgnoreCase), + CollationType.RTrim => string.CompareOrdinal(a.TrimEnd(), b.TrimEnd()), + _ => string.CompareOrdinal(a, b), + }; + + /// + /// True when the condition names a column that declares a non-binary collation. Such a condition must not + /// take the compiled ordinal fast path, or a NOCASE column would miss the case-insensitive matches. + /// + /// The WHERE condition text. + /// True when a non-binary column is referenced. + private bool ConditionTouchesNonBinaryCollation(string condition) + { + for (int i = 0; i < Columns.Count && i < ColumnCollations.Count; i++) + { + if (ColumnCollations[i] != CollationType.Binary && + condition.Contains(Columns[i], StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + private bool EvaluateCondition(Dictionary row, string condition) { var trimmedCondition = condition.Trim(); @@ -1978,7 +2257,7 @@ private static bool IsBareColumnReference(string condition) return name.Length > 0 && !char.IsDigit(name[0]); } - private static bool EvaluateSingleCondition(Dictionary row, string condition) + private bool EvaluateSingleCondition(Dictionary row, string condition) { var trimmed = condition.Trim(); @@ -2045,9 +2324,10 @@ private static bool EvaluateSingleCondition(Dictionary row, stri return valD >= lowD && valD <= highD; } - // Fallback: string comparison - return string.CompareOrdinal(rowVal.ToString(), lowStr) >= 0 && - string.CompareOrdinal(rowVal.ToString(), highStr) <= 0; + // Fallback: string comparison, honouring the column's declared collation (plan 009 D2). + var textCollation = CollationForColumn(col); + return CompareText(rowVal.ToString() ?? string.Empty, lowStr, textCollation) >= 0 && + CompareText(rowVal.ToString() ?? string.Empty, highStr, textCollation) <= 0; } // ✅ Issue #339/#340: support IN / NOT IN lists, SQLite VALUES forms and tuple @@ -2145,7 +2425,7 @@ private static bool EvaluateSingleCondition(Dictionary row, stri }; } - var comparison = string.Compare(rowValue.ToString(), valueStr, StringComparison.Ordinal); + var comparison = CompareText(rowValue.ToString() ?? string.Empty, valueStr, CollationForColumn(columnName)); return op switch { "=" => comparison == 0, diff --git a/src/SharpCoreDB/Storage/BlockCompressionMode.cs b/src/SharpCoreDB/Storage/BlockCompressionMode.cs index 680aae6d..493d3515 100644 --- a/src/SharpCoreDB/Storage/BlockCompressionMode.cs +++ b/src/SharpCoreDB/Storage/BlockCompressionMode.cs @@ -30,8 +30,8 @@ public enum BlockCompressionMode /// /// Zstandard compression (excellent speed/ratio balance). /// Best for: general-purpose database blocks, telemetry, mixed workloads. - /// Requires .NET 11+ (System.IO.Compression.ZstandardStream). - /// On this runtime, using this mode will throw NotSupportedException. + /// Uses the .NET 11+ in-box System.IO.Compression.ZstandardStream; on an older target framework the + /// mode throws . /// Zstd = 3 } \ No newline at end of file diff --git a/src/SharpCoreDB/Storage/Scdb/PageBasedAdapter.cs b/src/SharpCoreDB/Storage/Scdb/PageBasedAdapter.cs index 2f82c71d..7f0aa3b4 100644 --- a/src/SharpCoreDB/Storage/Scdb/PageBasedAdapter.cs +++ b/src/SharpCoreDB/Storage/Scdb/PageBasedAdapter.cs @@ -360,6 +360,12 @@ public void Dispose() // Save table metadata before disposing SaveTableMetadata(); + // The provider is shared (see the note below), so it is not disposed here — but everything this + // adapter wrote (page blocks and the table metadata) is still queued in the provider's write-behind + // buffer, registry included. Without this flush a reopen of the same file loses every page written + // through the adapter. FlushAsync drains the queue, flushes the block registry and fsyncs. + _storageProvider.FlushAsync().GetAwaiter().GetResult(); + _disposed = true; } diff --git a/src/SharpCoreDB/Storage/Scdb/ScdbStructures.cs b/src/SharpCoreDB/Storage/Scdb/ScdbStructures.cs index 12b13a45..e677d3d4 100644 --- a/src/SharpCoreDB/Storage/Scdb/ScdbStructures.cs +++ b/src/SharpCoreDB/Storage/Scdb/ScdbStructures.cs @@ -577,7 +577,7 @@ public enum BlockFlags : uint /// Block has uncommitted changes Dirty = 1 << 0, - /// Block is compressed (reserved, always 0 for .scdb) + /// Block is compressed (see ScdbFileHeader.CompressionMode for the algorithm) Compressed = 1 << 1, /// Block is encrypted with AES-256-GCM @@ -985,6 +985,48 @@ public struct ColumnDefinitionEntry /// Maximum column name length public const int MAX_COLUMN_NAME_LENGTH = 31; + + /// + /// First bit of the packed collation code in (bits 8-11). Bits 0-5 are taken by + /// , so the code lives in the free bits above them. + /// + public const int CollationShift = 8; + + /// Mask of the packed collation code in . + public const uint CollationMask = 0xFu << CollationShift; + + /// + /// Reads the column's persisted collation. A file written before collation was persisted has zero in + /// those bits, which decodes to — the behaviour those files had — so + /// old files keep working unchanged. + /// + /// The column entry to read. + /// The column's collation (BINARY when the bits are zero). + public static CollationType GetCollation(ColumnDefinitionEntry entry) => + (CollationType)((entry.Flags & CollationMask) >> CollationShift); + + /// Writes the column's collation into the free bits 8-11 of . + /// The column entry to update. + /// The collation to persist. + public static void SetCollation(ref ColumnDefinitionEntry entry, CollationType collation) => + entry.Flags = (entry.Flags & ~CollationMask) | (((uint)collation & 0xF) << CollationShift); + + /// + /// The "key modelled" marker (bit 6, free between 's bits 0-5 and the collation + /// bits 8-11). A writer that understands composite keys sets it on every key column; a file written + /// before that reads zero, which is how single-file enforcement tells a new, fully modelled key from an + /// old file whose key columns were never recorded. Old readers ignore it (they test named bits only). + /// + public const uint KeyModelledFlag = 1u << 6; + + /// True when the column entry was written by a version that modelled the table's key columns. + /// The column entry to test. + /// True when the marker is set. + public static bool IsKeyModelled(ColumnDefinitionEntry entry) => (entry.Flags & KeyModelledFlag) != 0; + + /// Sets the "key modelled" marker on a key column. + /// The column entry to update. + public static void MarkKeyModelled(ref ColumnDefinitionEntry entry) => entry.Flags |= KeyModelledFlag; } /// diff --git a/src/SharpCoreDB/Storage/Scdb/SingleFileDatabase.Batch.cs b/src/SharpCoreDB/Storage/Scdb/SingleFileDatabase.Batch.cs index 75dc3ade..f660bc8a 100644 --- a/src/SharpCoreDB/Storage/Scdb/SingleFileDatabase.Batch.cs +++ b/src/SharpCoreDB/Storage/Scdb/SingleFileDatabase.Batch.cs @@ -18,10 +18,28 @@ namespace SharpCoreDB; /// internal static class SingleFileDatabaseBatchExtension { - // ✅ NEW: Cache for prepared INSERT statements to avoid repeated parsing + // ✅ NEW: Cache for prepared INSERT statements to avoid repeated parsing. + // The key carries the table's COLUMN SIGNATURE, not just its name: this cache is static, so a + // name-only key let two databases whose tables share a name but not a shape poison each other — + // the second database's rows were mapped through the first's column list, which surfaced as + // "Column 'name' cannot be NULL" on a perfectly valid INSERT (caught by the wider suite when two + // single-file tests used `docs` with different columns). Including the columns and their types makes + // the entry valid for exactly one shape; two databases with the same shape may still share it. private static readonly Dictionary _insertStatementCache = new(); private static readonly object _cacheLock = new object(); + /// Upper bound on cached shapes, so a schema-churning caller cannot grow it without limit. + private const int InsertStatementCacheCapacity = 256; + + /// The cache key for a table's INSERT shape: name + ordered columns + their types. + private static string InsertShapeKey(string tableName, List columns, List columnTypes) => + string.Concat( + tableName, + "\u001F", + string.Join(",", columns), + "\u001F", + string.Join(",", columnTypes)); + /// /// Prepared INSERT statement metadata for fast repeated inserts. /// Caches column definitions to avoid repeated lookups. @@ -264,13 +282,15 @@ private static (string tableName, Dictionary row)? ParseInsertSt return null; } - // Try to get cached metadata for this table - PreparedInsertStatement? cachedStmt = null; + // Try to get cached metadata for this table SHAPE (name + columns + types — see the field's note: + // a name-only key mixed two databases' schemas). + var shapeKey = InsertShapeKey(tableName, table.Columns, table.ColumnTypes); + PreparedInsertStatement? cachedStmt; lock (_cacheLock) { - _insertStatementCache.TryGetValue(tableName, out cachedStmt); + _insertStatementCache.TryGetValue(shapeKey, out cachedStmt); } - + // If not cached, create and cache it if (cachedStmt == null) { @@ -283,10 +303,15 @@ private static (string tableName, Dictionary row)? ParseInsertSt .Select((col, idx) => (col, idx)) .ToDictionary(x => x.col, x => x.idx) }; - + lock (_cacheLock) { - _insertStatementCache[tableName] = cachedStmt; + if (_insertStatementCache.Count >= InsertStatementCacheCapacity) + { + _insertStatementCache.Clear(); + } + + _insertStatementCache[shapeKey] = cachedStmt; } } diff --git a/src/SharpCoreDB/Storage/SingleFileStorageProvider.cs b/src/SharpCoreDB/Storage/SingleFileStorageProvider.cs index d19119d6..bc91ab72 100644 --- a/src/SharpCoreDB/Storage/SingleFileStorageProvider.cs +++ b/src/SharpCoreDB/Storage/SingleFileStorageProvider.cs @@ -900,7 +900,8 @@ public async Task WriteBlockAsync(string blockName, ReadOnlyMemory data, C offset = registryEnd; } - // ✅ Compression: set the Compressed flag if this block was compressed. + // ✅ Compression: set the Compressed flag if this block was compressed (the algorithm lives in + // the file header's CompressionMode, which ValidateHeader enforces on open). var flags = (uint)BlockFlags.Dirty; if (isCompressed) { @@ -1179,6 +1180,16 @@ public async Task UpdateBlockAsync( { ObjectDisposedException.ThrowIf(_disposed, this); + // Read-your-writes: WriteBlockAsync only queues the bytes (the write-behind worker persists them + // later), so a read issued right after a write would otherwise read the zero fill of an unwritten + // region, see a checksum mismatch and "self-heal" the registry to match the zeros — losing the + // block. Draining the queue first (outside _ioGate, which this method takes below) makes a read + // observe every write issued before it, which is what PageBasedAdapter and the storage tests rely on. + if (Volatile.Read(ref _hasPendingWrites) != 0) + { + await FlushPendingWritesAsync(cancellationToken, flushToDisk: false).ConfigureAwait(false); + } + await _ioGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { @@ -1242,7 +1253,8 @@ public async Task UpdateBlockAsync( result = _encryption.Decrypt(result); } - // ✅ Compression: decompress after decrypt if the block was compressed. + // ✅ Compression: decompress after decrypt. ValidateHeader has already proved the file's + // recorded mode equals the configured one, so the option IS the block's mode here. if ((entry.Flags & (uint)BlockFlags.Compressed) != 0) { result = BlockCompressor.Decompress(result, _compressionMode); @@ -1552,7 +1564,14 @@ public async Task FlushPendingWritesAsync(CancellationToken cancellationToken = } } - Volatile.Write(ref _hasPendingWrites, 0); + // Clear the flag only when nothing is left in the queue. A write enqueued while this flush ran set the + // flag after its own enqueue, and resetting it here would make HasPendingChanges report clean — a + // following FlushAsync would then early-return and leave that write queued until the background + // worker's next tick: a durability gap if the process closes the file in between. + if (_writeQueue.Reader.Count == 0) + { + Volatile.Write(ref _hasPendingWrites, 0); + } } /// diff --git a/tests/SharpCoreDB.Tests/CorruptionDetectorTests.cs b/tests/SharpCoreDB.Tests/CorruptionDetectorTests.cs new file mode 100644 index 00000000..c8d4cb8e --- /dev/null +++ b/tests/SharpCoreDB.Tests/CorruptionDetectorTests.cs @@ -0,0 +1,82 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace SharpCoreDB.Tests; + +using System; +using System.IO; +using System.Threading.Tasks; +using SharpCoreDB.Storage; +using SharpCoreDB.Storage.Scdb; +using Xunit; + +/// +/// Pins the contract on a healthy database: every validation mode runs its own +/// depth without reporting corruption, the report carries a summary and the scanned volume, and the detector +/// refuses use after disposal. Up to 2.1.4 the detector had no test at all (0% covered). +/// +public sealed class CorruptionDetectorTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"SCDB_Corruption_{Guid.NewGuid():N}.scdb"); + private static readonly DatabaseOptions Options = new() { StorageMode = StorageMode.SingleFile, PageSize = 4096 }; + + public void Dispose() + { + try { if (File.Exists(_path)) File.Delete(_path); } catch { } + } + + [Theory] + [InlineData(ValidationMode.Quick)] + [InlineData(ValidationMode.Standard)] + [InlineData(ValidationMode.Deep)] + [InlineData(ValidationMode.Paranoid)] + public async Task Validate_HealthyDatabase_ReportsNoCorruption(ValidationMode mode) + { + using var provider = SingleFileStorageProvider.Open(_path, Options); + await provider.WriteBlockAsync("alpha", new byte[1024]); + await provider.WriteBlockAsync("beta", new byte[2048]); + + using var detector = new CorruptionDetector(provider, mode); + CorruptionReport report = await detector.ValidateAsync(); + + Assert.False(report.IsCorrupted); + Assert.Equal(CorruptionSeverity.None, report.Severity); + Assert.Empty(report.Issues); + Assert.False(string.IsNullOrWhiteSpace(report.Summary)); + Assert.Same(report.Summary, report.ToString()); + Assert.True(report.BytesScanned > 0); + if (mode != ValidationMode.Quick) + { + Assert.True(report.BlocksValidated > 0); + } + } + + [Fact] + public async Task Validate_EmptyDatabase_ReportsNoCorruption() + { + using var provider = SingleFileStorageProvider.Open(_path, Options); + using var detector = new CorruptionDetector(provider); + + CorruptionReport report = await detector.ValidateAsync(); + + Assert.False(report.IsCorrupted); + Assert.Empty(report.Issues); + } + + [Fact] + public async Task Validate_DisposedDetector_Throws() + { + using var provider = SingleFileStorageProvider.Open(_path, Options); + var detector = new CorruptionDetector(provider); + detector.Dispose(); + detector.Dispose(); // idempotent + + await Assert.ThrowsAsync(() => detector.ValidateAsync()); + } + + [Fact] + public void Constructor_NullProvider_Throws() => + Assert.Throws(() => new CorruptionDetector(null!)); +} diff --git a/tests/SharpCoreDB.Tests/ExecuteBatchPreparedTests.cs b/tests/SharpCoreDB.Tests/ExecuteBatchPreparedTests.cs new file mode 100644 index 00000000..444f52a0 --- /dev/null +++ b/tests/SharpCoreDB.Tests/ExecuteBatchPreparedTests.cs @@ -0,0 +1,156 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using Xunit; + +/// +/// Correctness tests for the prepared-batch API (): the +/// template is classified once and parameters are bound per row, so no statement is scanned/parsed per +/// row. The prepared path must produce exactly what the raw path produces, and must reject a template +/// whose SET/WHERE values are not parameters. +/// +public sealed class ExecuteBatchPreparedTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _dbPath; + + public ExecuteBatchPreparedTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _dbPath = Path.Combine(Path.GetTempPath(), $"SCDB_Prepared_{Guid.NewGuid():N}"); + } + + [Fact] + public void ExecuteBatchPrepared_Update_AppliesEveryParameterSet() + { + var db = _factory.Create(_dbPath, "pwd"); + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL)"); + for (var i = 0; i < 100; i++) + { + db.ExecuteSQL( + "INSERT INTO docs (id, name, score) VALUES (@id, @name, @score)", + new Dictionary { ["@id"] = i, ["@name"] = $"U{i}", ["@score"] = 0.0 }); + } + + var parameterSets = new List>(100); + for (var i = 0; i < 100; i++) + { + parameterSets.Add(new Dictionary { ["@score"] = i * 2.0, ["@id"] = i }); + } + + var affected = db.ExecuteBatchPrepared("UPDATE docs SET score = @score WHERE id = @id", parameterSets); + + Assert.Equal(100, affected); + for (var i = 0; i < 100; i++) + { + var row = db.ExecuteQuery("SELECT score FROM docs WHERE id = @id", new Dictionary { ["@id"] = i }); + Assert.Single(row); + Assert.Equal(i * 2.0, Convert.ToDouble(row[0]["score"])); + } + + (db as IDisposable)?.Dispose(); + } + + [Fact] + public void ExecuteBatchPrepared_Delete_RemovesEveryParameterSet() + { + var db = _factory.Create(_dbPath, "pwd"); + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL)"); + for (var i = 0; i < 100; i++) + { + db.ExecuteSQL( + "INSERT INTO docs (id, name, score) VALUES (@id, @name, @score)", + new Dictionary { ["@id"] = i, ["@name"] = $"U{i}", ["@score"] = 0.0 }); + } + + var parameterSets = new List>(100); + for (var i = 0; i < 100; i++) + { + parameterSets.Add(new Dictionary { ["@id"] = i }); + } + + var affected = db.ExecuteBatchPrepared("DELETE FROM docs WHERE id = @id", parameterSets); + + Assert.Equal(100, affected); + Assert.Empty(db.ExecuteQuery("SELECT id FROM docs")); + + (db as IDisposable)?.Dispose(); + } + + [Fact] + public void ExecuteBatchPrepared_Delete_OnIndexedColumn_ResolvesThroughHashIndex() + { + var db = _factory.Create(_dbPath, "pwd"); + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL)"); + db.ExecuteSQL("CREATE INDEX idx_docs_name ON docs (name)"); + for (var i = 0; i < 100; i++) + { + db.ExecuteSQL( + "INSERT INTO docs (id, name, score) VALUES (@id, @name, @score)", + new Dictionary { ["@id"] = i, ["@name"] = $"U{i}", ["@score"] = 0.0 }); + } + + var parameterSets = new List>(100); + for (var i = 0; i < 100; i++) + { + parameterSets.Add(new Dictionary { ["@name"] = $"U{i}" }); + } + + var affected = db.ExecuteBatchPrepared("DELETE FROM docs WHERE name = @name", parameterSets); + + Assert.Equal(100, affected); + Assert.Empty(db.ExecuteQuery("SELECT id FROM docs")); + + (db as IDisposable)?.Dispose(); + } + + [Fact] + public void ExecuteBatchPrepared_DeleteNonParameterTemplate_Throws() + { + var db = _factory.Create(_dbPath, "pwd"); + db.ExecuteSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, v REAL)"); + db.ExecuteSQL("INSERT INTO t (id, v) VALUES (0, 1.0)"); + var parameterSets = new List> { new() { ["@id"] = 0 } }; + + Assert.Throws(() => db.ExecuteBatchPrepared("DELETE FROM t WHERE id = 0", parameterSets)); + + (db as IDisposable)?.Dispose(); + } + + [Fact] + public void ExecuteBatchPrepared_NonParameterTemplate_Throws() + { + var db = _factory.Create(_dbPath, "pwd"); + db.ExecuteSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, v REAL)"); + var parameterSets = new List> { new() { ["@v"] = 1.0, ["@id"] = 0 } }; + + Assert.Throws(() => db.ExecuteBatchPrepared("UPDATE t SET v = 1.0 WHERE id = @id", parameterSets)); + + (db as IDisposable)?.Dispose(); + } + + public void Dispose() + { + try + { + if (Directory.Exists(_dbPath)) + { + Directory.Delete(_dbPath, true); + } + } + catch + { + // best-effort cleanup + } + } +} diff --git a/tests/SharpCoreDB.Tests/IntegerAffinityTests.cs b/tests/SharpCoreDB.Tests/IntegerAffinityTests.cs new file mode 100644 index 00000000..ecc63a7b --- /dev/null +++ b/tests/SharpCoreDB.Tests/IntegerAffinityTests.cs @@ -0,0 +1,99 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using System; +using System.IO; +using Xunit; + +/// +/// Pins owner decision D3=B (plan 009): `INTEGER` keeps its Int32 default, but a value that does not fit must +/// fail with the actionable message — never be stored as 0 — on both the single-statement and the batch +/// path, and the opt-in that message names (`UseSqliteIntegerAffinity`) must actually work on the single-file +/// path (it was hardcoded off there, so the advice had no effect). +/// +public sealed class IntegerAffinityTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _dirPath; + private readonly string _scdbPath; + + public IntegerAffinityTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _dirPath = Path.Combine(Path.GetTempPath(), $"SCDB_IntAffinity_Dir_{Guid.NewGuid():N}"); + _scdbPath = Path.Combine(Path.GetTempPath(), $"SCDB_IntAffinity_Scdb_{Guid.NewGuid():N}.scdb"); + } + + public void Dispose() + { + try { if (File.Exists(_scdbPath)) File.Delete(_scdbPath); } catch { } + try { if (Directory.Exists(_dirPath)) Directory.Delete(_dirPath, true); } catch { } + } + + private IDatabase CreateDirectoryDb() + { + var db = _factory.Create(_dirPath, "pw"); + db.ExecuteSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER)"); + return db; + } + + private static void AssertActionable(Action insert) + { + var ex = Assert.Throws(insert); + Assert.Contains("exceeds the Int32 range", ex.Message); + Assert.Contains("BIGINT", ex.Message); + Assert.Contains("UseSqliteIntegerAffinity", ex.Message); + } + + [Fact] + public void SingleStatement_IntegerOverflow_ThrowsActionableMessage() + { + var db = CreateDirectoryDb(); + try + { + AssertActionable(() => db.ExecuteSQL("INSERT INTO t VALUES (1, 3000000000)")); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void BatchInsert_IntegerOverflow_ThrowsInsteadOfStoringZero() + { + var db = CreateDirectoryDb(); + try + { + // Red before: the batch literal path stored 0 for a number too large for Int32. + AssertActionable(() => db.ExecuteBatchSQL(new[] { "INSERT INTO t VALUES (1, 3000000000)" })); + var rows = db.ExecuteQuery("SELECT v FROM t"); + Assert.Empty(rows); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void SingleFile_CreateTable_HonoursUseSqliteIntegerAffinity() + { + var options = DatabaseOptions.CreateSingleFileDefault(); + options.DatabaseConfig = new DatabaseConfig { UseSqliteIntegerAffinity = true }; + var db = _factory.CreateWithOptions(_scdbPath, "pw", options); + try + { + db.ExecuteSQL("CREATE TABLE ticks (id INTEGER PRIMARY KEY, v INTEGER)"); + + // Red before: the single-file DDL hardcoded the opt-in off, so INTEGER was Int32 and this threw. + db.ExecuteSQL("INSERT INTO ticks VALUES (1, 3000000000)"); + + var rows = db.ExecuteQuery("SELECT v FROM ticks WHERE id = 1"); + Assert.Single(rows); + Assert.Equal(3000000000L, Convert.ToInt64(rows[0]["v"])); + } + finally { (db as IDisposable)?.Dispose(); } + } +} diff --git a/tests/SharpCoreDB.Tests/PageBasedAdapterTests.cs b/tests/SharpCoreDB.Tests/PageBasedAdapterTests.cs new file mode 100644 index 00000000..e6834fa6 --- /dev/null +++ b/tests/SharpCoreDB.Tests/PageBasedAdapterTests.cs @@ -0,0 +1,194 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace SharpCoreDB.Tests; + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using SharpCoreDB.Interfaces; +using SharpCoreDB.Storage; +using SharpCoreDB.Storage.Scdb; +using Xunit; + +/// +/// Pins the contract — the page-based storage engine's window onto a single-file +/// database: a record inserted through it is readable by its storage reference, an update keeps the reference +/// valid, a delete releases the record, the metrics count what happened, and the table metadata survives a +/// reopen. Up to 2.1.4 this adapter had no test at all (0% covered). +/// +public sealed class PageBasedAdapterTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"SCDB_PageAdapter_{Guid.NewGuid():N}.scdb"); + private static readonly DatabaseOptions Options = new() { StorageMode = StorageMode.SingleFile, PageSize = 4096 }; + + public void Dispose() + { + try { if (File.Exists(_path)) File.Delete(_path); } catch { } + } + + [Fact] + public void Insert_ThenRead_RoundTripsTheRecord() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + byte[] data = [1, 2, 3, 4, 5]; + + long reference = adapter.Insert("t", data); + + Assert.Equal(data, adapter.Read("t", reference)); + } + + [Fact] + public void Read_UnknownTable_ReturnsNull() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + long reference = adapter.Insert("t", [1, 2, 3]); + + Assert.Null(adapter.Read("other", reference)); + } + + [Fact] + public void InsertBatch_ReturnsOneReferencePerBlock_AndAllReadBack() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + byte[] first = [10, 11]; + byte[] second = [20, 21, 22]; + + long[] references = adapter.InsertBatch("t", [first, second]); + + Assert.Equal(2, references.Length); + Assert.Equal(first, adapter.Read("t", references[0])); + Assert.Equal(second, adapter.Read("t", references[1])); + Assert.Empty(adapter.InsertBatch("t", [])); + } + + [Fact] + public void Insert_NullData_Throws() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + Assert.Throws(() => adapter.Insert("t", null!)); + Assert.Throws(() => adapter.InsertBatch("t", null!)); + } + + [Fact] + public void Update_ShorterAndLongerRecord_KeepsTheReferenceAndReadsTheNewValue() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + long reference = adapter.Insert("t", [1, 2, 3, 4, 5, 6, 7, 8]); + + Assert.Equal(reference, adapter.Update("t", reference, [9])); + Assert.Equal(new byte[] { 9 }, adapter.Read("t", reference)); + + byte[] grown = [.. Enumerable.Range(0, 20).Select(i => (byte)i)]; + Assert.Equal(reference, adapter.Update("t", reference, grown)); + Assert.Equal(grown, adapter.Read("t", reference)); + Assert.True(adapter.TryUpdateInPlace("t", reference, [7, 7])); + Assert.Equal(new byte[] { 7, 7 }, adapter.Read("t", reference)); + } + + [Fact] + public void Update_MissingPage_Throws() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + long reference = adapter.Insert("t", [1]); + + Assert.Throws(() => adapter.Update("other", reference, [2])); + } + + [Fact] + public void Delete_ThenRead_ReturnsNull_AndGetAllRecordsSkipsIt() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + long first = adapter.Insert("t", [1]); + long second = adapter.Insert("t", [2]); + + adapter.Delete("t", first); + + Assert.Null(adapter.Read("t", first)); + Assert.Equal(new byte[] { 2 }, adapter.Read("t", second)); + Assert.Single(adapter.GetAllRecords("t")); + } + + [Fact] + public void GetAllRecords_ListsEveryLiveRecordInInsertionOrder() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + adapter.Insert("t", [1]); + adapter.Insert("t", [2]); + adapter.Insert("t", [3]); + + Assert.Equal( + new[] { new byte[] { 1 }, new byte[] { 2 }, new byte[] { 3 } }, + adapter.GetAllRecords("t").Select(r => r.data)); + Assert.Empty(adapter.GetAllRecords("no-such-table")); + } + + [Fact] + public void GetMetrics_CountsEveryOperation() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + long reference = adapter.Insert("t", [1, 2]); + adapter.InsertBatch("t", [[3], [4]]); + adapter.Read("t", reference); + adapter.Update("t", reference, [5]); + adapter.Delete("t", reference); + + StorageEngineMetrics metrics = adapter.GetMetrics(); + Assert.Equal(3, metrics.TotalInserts); + Assert.Equal(1, metrics.TotalReads); + Assert.Equal(1, metrics.TotalUpdates); + Assert.Equal(1, metrics.TotalDeletes); + Assert.True(metrics.BytesWritten > 0); + Assert.True(metrics.BytesRead > 0); + Assert.Equal(StorageEngineType.PageBased, adapter.EngineType); + } + + [Fact] + public async Task Transactions_BeginCommitAndRollback_TrackTheState() + { + using var adapter = PageBasedAdapter.Open(_path, Options); + + Assert.Throws(() => adapter.Rollback()); + Assert.Throws(() => adapter.CommitAsync().GetAwaiter().GetResult()); + + adapter.BeginTransaction(); + Assert.True(adapter.IsInTransaction); + Assert.Throws(() => adapter.BeginTransaction()); + await adapter.CommitAsync(); + Assert.False(adapter.IsInTransaction); + + adapter.BeginTransaction(); + adapter.Rollback(); + Assert.False(adapter.IsInTransaction); + adapter.Flush(); + } + + [Fact] + public void Dispose_ThenInsert_Throws() + { + var adapter = PageBasedAdapter.Open(_path, Options); + adapter.Dispose(); + adapter.Dispose(); // idempotent + + Assert.Throws(() => adapter.Insert("t", [1])); + Assert.Throws(() => adapter.Read("t", 0)); + Assert.Throws(() => adapter.Flush()); + } + + [Fact] + public void Reopen_SeesThePersistedTableAndItsRecords() + { + long reference; + using (var adapter = PageBasedAdapter.Open(_path, Options)) + { + reference = adapter.Insert("t", [42, 43]); + } + + using var reopened = PageBasedAdapter.Open(_path, Options); + Assert.Equal(new byte[] { 42, 43 }, reopened.Read("t", reference)); + Assert.Single(reopened.GetAllRecords("t")); + } +} diff --git a/tests/SharpCoreDB.Tests/ParallelRecordEncryptionTests.cs b/tests/SharpCoreDB.Tests/ParallelRecordEncryptionTests.cs new file mode 100644 index 00000000..aad0ee64 --- /dev/null +++ b/tests/SharpCoreDB.Tests/ParallelRecordEncryptionTests.cs @@ -0,0 +1,138 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.DataStructures; +using SharpCoreDB.Interfaces; +using SharpCoreDB.Storage.Hybrid; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using Xunit; + +/// +/// Pins plan 006 US1: an encrypted fixed-width table's contiguous UPDATE/DELETE span decrypts its records in +/// parallel (≥ 64 records), producing byte-identical plaintext to the sequential loop. The branch is +/// observable through ; a small batch keeps the +/// sequential loop. Proven red by disabling the parallel guard (the counter then stays 0 and the first test +/// fails), which is exactly what the counter exists to make visible. +/// +public sealed class ParallelRecordEncryptionTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _dirPath; + + public ParallelRecordEncryptionTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _dirPath = Path.Combine(Path.GetTempPath(), $"SCDB_ParallelEnc_{Guid.NewGuid():N}"); + } + + public void Dispose() + { + try { if (Directory.Exists(_dirPath)) Directory.Delete(_dirPath, true); } catch { } + } + + private IDatabase CreateEncryptedDb() => _factory.Create(_dirPath, "pw", isReadOnly: false, + config: new DatabaseConfig { NoEncryptMode = false, EnableAtRestRecordEncryption = true }); + + private static Table TableOf(IDatabase db, string tableName) + { + Assert.True(db.TryGetTable(tableName, out var t)); + return Assert.IsType(t); + } + + private static void InsertDocs(IDatabase db, int fromId, int toId) + { + var stmts = new List(toId - fromId + 1); + for (int i = fromId; i <= toId; i++) + { + stmts.Add(string.Format(CultureInfo.InvariantCulture, + "INSERT INTO docs VALUES ({0}, 'user{0}', {1}, {2})", i, i * 0.5, 20 + (i % 60))); + } + + db.ExecuteBatchSQL(stmts); + } + + private static List BuildUpdates(int fromId, int toId, string setExpr) + { + var stmts = new List(Math.Abs(toId - fromId) + 1); + for (int i = fromId; i <= toId; i++) + { + stmts.Add(string.Format(CultureInfo.InvariantCulture, + "UPDATE docs SET {0} WHERE id = {1}", setExpr, i)); + } + + return stmts; + } + + [Fact] + public void EncryptedContiguousUpdate_DecryptsSpanInParallel_AndPersists() + { + IDatabase? db = null; + try + { + db = CreateEncryptedDb(); + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL, age INTEGER)"); + InsertDocs(db, 1, 2000); + db.Flush(); + + var table = TableOf(db, "docs"); + Assert.True(table.IsFixedWidthRecords); + Assert.Equal(0L, table.BulkContiguousParallelDecryptBatches); + + db.ExecuteBatchSQL(BuildUpdates(1, 1000, "score = 99.0")); + db.Flush(); + + // The 1000-record span is above the 64-record threshold: the parallel decrypt and the parallel + // seal each ran exactly once (the two halves of the at-rest tax). + Assert.Equal(1L, table.BulkContiguousParallelDecryptBatches); + Assert.Equal(1L, table.BulkContiguousParallelEncryptBatches); + + // Byte-identical: every row of the batch and every untouched row, after reopen. + (db as IDisposable)?.Dispose(); + db = CreateEncryptedDb(); + var all = db.ExecuteQuery("SELECT id, score FROM docs"); + Assert.Equal(2000, all.Count); + foreach (var row in all) + { + int id = Convert.ToInt32(row["id"]); + Assert.Equal(id <= 1000 ? 99.0 : id * 0.5, Convert.ToDouble(row["score"])); + } + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void EncryptedSmallBatch_KeepsTheSequentialLoop() + { + IDatabase? db = null; + try + { + db = CreateEncryptedDb(); + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL, age INTEGER)"); + InsertDocs(db, 1, 200); + db.Flush(); + + var table = TableOf(db, "docs"); + + // 10 records — below the threshold, so the sequential loop and no Parallel.For overhead. + db.ExecuteBatchSQL(BuildUpdates(1, 10, "score = 42.0")); + db.Flush(); + + Assert.Equal(0L, table.BulkContiguousParallelDecryptBatches); + Assert.Equal(0L, table.BulkContiguousParallelEncryptBatches); + var row = db.ExecuteQuery("SELECT score FROM docs WHERE id = @id", + new Dictionary { ["@id"] = 5 }); + Assert.Single(row); + Assert.Equal(42.0, Convert.ToDouble(row[0]["score"])); + } + finally { (db as IDisposable)?.Dispose(); } + } +} diff --git a/tests/SharpCoreDB.Tests/PrimaryKeyUniquenessTests.cs b/tests/SharpCoreDB.Tests/PrimaryKeyUniquenessTests.cs index 101a3f65..b9aedb75 100644 --- a/tests/SharpCoreDB.Tests/PrimaryKeyUniquenessTests.cs +++ b/tests/SharpCoreDB.Tests/PrimaryKeyUniquenessTests.cs @@ -50,7 +50,7 @@ public void Dispose() [Theory] [InlineData("directory")] - [InlineData("single-file", Skip = "Single-file storage does not enforce PRIMARY KEY uniqueness, and cannot do so safely yet: its format persists the PrimaryKey flag on one column only, so a composite key (EF Core declares one inline PRIMARY KEY per key column) is indistinguishable from a single-column key. See docs/sharpcoredb-known-issues.md, §11.")] + [InlineData("single-file")] public void Insert_DuplicatePrimaryKey_IsRejected(string mode) { var (db, _) = Open(mode); @@ -62,7 +62,7 @@ public void Insert_DuplicatePrimaryKey_IsRejected(string mode) [Theory] [InlineData("directory")] - [InlineData("single-file", Skip = "Single-file storage does not enforce PRIMARY KEY uniqueness, and cannot do so safely yet: its format persists the PrimaryKey flag on one column only, so a composite key (EF Core declares one inline PRIMARY KEY per key column) is indistinguishable from a single-column key. See docs/sharpcoredb-known-issues.md, §11.")] + [InlineData("single-file")] public void MultiRowInsert_RepeatingAnExistingKey_KeepsNoRowOfTheStatement(string mode) { var (db, _) = Open(mode); @@ -74,7 +74,7 @@ public void MultiRowInsert_RepeatingAnExistingKey_KeepsNoRowOfTheStatement(strin [Theory] [InlineData("directory")] - [InlineData("single-file", Skip = "Single-file storage does not enforce PRIMARY KEY uniqueness, and cannot do so safely yet: its format persists the PrimaryKey flag on one column only, so a composite key (EF Core declares one inline PRIMARY KEY per key column) is indistinguishable from a single-column key. See docs/sharpcoredb-known-issues.md, §11.")] + [InlineData("single-file")] public void MultiRowInsert_RepeatingAKeyWithinTheStatement_KeepsNoRow(string mode) { var (db, _) = Open(mode); @@ -94,7 +94,7 @@ public void MultiRowInsert_WithANotNullViolation_KeepsNoRow(string mode) Assert.Empty(db.ExecuteQuery("SELECT id FROM t")); } - [Fact(Skip = "Single-file storage does not enforce PRIMARY KEY uniqueness, and cannot do so safely yet: its format persists the PrimaryKey flag on one column only, so a composite key (EF Core declares one inline PRIMARY KEY per key column) is indistinguishable from a single-column key. See docs/sharpcoredb-known-issues.md, §11.")] + [Fact] public void Insert_DuplicatePrimaryKey_AfterReopen_IsRejectedOnSingleFile() { var (db, path) = Open("single-file"); diff --git a/tests/SharpCoreDB.Tests/SimdHelperTests.cs b/tests/SharpCoreDB.Tests/SimdHelperTests.cs new file mode 100644 index 00000000..b2502430 --- /dev/null +++ b/tests/SharpCoreDB.Tests/SimdHelperTests.cs @@ -0,0 +1,305 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace SharpCoreDB.Tests; + +using System; +using System.Linq; +using System.Text; +using SharpCoreDB.Services; +using Xunit; + +/// +/// Pins the public surface: every operation is asserted on a small span (the scalar +/// path) and on a span longer than a 512-bit vector (the vectorised path plus its scalar tail), because the +/// hardware-dependent branch must give the same answer as the fallback. The deserializers are fed the exact +/// wire layout the storage layer writes: a 1-byte null/present flag followed by the value. +/// +public sealed class SimdHelperTests +{ + [Fact] + public void AddInt32_ScalarAndVectorPaths_AddElementwise() + { + int[] left = [1, 2, 3]; + int[] right = [10, 20, 30]; + int[] small = new int[3]; + SimdHelper.AddInt32(left, right, small); + Assert.Equal([11, 22, 33], small); + + int[] bigLeft = [.. Enumerable.Range(0, 100)]; + int[] bigRight = [.. Enumerable.Repeat(2, 100)]; + int[] big = new int[100]; + SimdHelper.AddInt32(bigLeft, bigRight, big); + Assert.Equal(bigLeft.Zip(bigRight, (a, b) => a + b), big); + } + + [Fact] + public void AddInt32_LengthMismatch_Throws() + { + Assert.Throws(() => SimdHelper.AddInt32(new int[2], new int[3], new int[2])); + Assert.Throws(() => SimdHelper.AddInt32(new int[2], new int[2], new int[3])); + SimdHelper.AddInt32([], [], []); + } + + [Fact] + public void MultiplyDouble_ScalarAndVectorPaths_MultiplyElementwise() + { + double[] left = [1.5, 2.0]; + double[] right = [2.0, 3.0]; + double[] small = new double[2]; + SimdHelper.MultiplyDouble(left, right, small); + Assert.Equal([3.0, 6.0], small); + + double[] bigLeft = [.. Enumerable.Range(1, 40).Select(i => (double)i)]; + double[] bigRight = [.. Enumerable.Repeat(0.5, 40)]; + double[] big = new double[40]; + SimdHelper.MultiplyDouble(bigLeft, bigRight, big); + Assert.Equal(bigLeft.Select(v => v * 0.5), big); + Assert.Throws(() => SimdHelper.MultiplyDouble(new double[2], new double[3], new double[2])); + } + + [Theory] + [InlineData(new[] { 5 }, 5)] + [InlineData(new[] { 3, -7, 9 }, -7)] + [InlineData(new[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13 }, -13)] + public void MinInt32_ReturnsTheSmallestValue(int[] values, int expected) => + Assert.Equal(expected, SimdHelper.MinInt32(values)); + + [Fact] + public void MinInt32_Empty_Throws() => + Assert.Throws(() => SimdHelper.MinInt32([])); + + [Fact] + public void CountNonZero_CountsAcrossTheVectorBoundary() + { + Assert.Equal(0, SimdHelper.CountNonZero([])); + Assert.Equal(2, SimdHelper.CountNonZero([0, 1, 0, 2, 0])); + byte[] longSpan = [.. Enumerable.Range(0, 300).Select(i => (byte)(i % 3))]; + Assert.Equal(longSpan.Count(b => b != 0), SimdHelper.CountNonZero(longSpan)); + } + + [Fact] + public void HorizontalSum_ScalarAndVectorPaths_SumTheSpan() + { + Assert.Equal(0, SimdHelper.HorizontalSum([])); + Assert.Equal(15, SimdHelper.HorizontalSum([1, 2, 3, 4, 5])); + int[] big = [.. Enumerable.Range(-50, 100)]; + Assert.Equal(big.Sum(v => (long)v), SimdHelper.HorizontalSum(big)); + } + + [Fact] + public void CompareGreaterThan_WritesFlagsAndReturnsTheCount() + { + int[] values = [1, 5, 3, 8]; + byte[] results = new byte[4]; + Assert.Equal(2, SimdHelper.CompareGreaterThan(values, 3, results)); + Assert.Equal(new byte[] { 0, 1, 0, 1 }, results); + + Assert.Equal(0, SimdHelper.CompareGreaterThan([], 0, new byte[1])); + + int[] big = [.. Enumerable.Range(0, 20)]; + byte[] bigResults = new byte[20]; + Assert.Equal(big.Count(v => v > 9), SimdHelper.CompareGreaterThan(big, 9, bigResults)); + Assert.Equal(big.Select(v => v > 9 ? (byte)1 : (byte)0), bigResults); + } + + [Fact] + public void CompareGreaterThan_BufferTooSmall_Throws() => + Assert.Throws(() => SimdHelper.CompareGreaterThan(new int[3], 1, new byte[2])); + + [Fact] + public void IndexOf_FindsTheFirstMatchAcrossTheVectorBoundary() + { + Assert.Equal(-1, SimdHelper.IndexOf([], 7)); + Assert.Equal(-1, SimdHelper.IndexOf(new byte[10], 7)); + Assert.Equal(3, SimdHelper.IndexOf([0, 1, 2, 7, 7], 7)); + + byte[] big = new byte[80]; + big[70] = 0x42; + Assert.Equal(70, SimdHelper.IndexOf(big, 0x42)); + } + + [Fact] + public void EncodeUtf8Fast_MatchesTheFrameworkEncoder() + { + Assert.Equal(0, SimdHelper.EncodeUtf8Fast([], new byte[4])); + + const string ascii = "select * from t"; + byte[] buffer = new byte[64]; + int written = SimdHelper.EncodeUtf8Fast(ascii, buffer); + Assert.Equal(Encoding.UTF8.GetBytes(ascii), buffer[..written]); + + const string nonAscii = "café ☕ 漢字"; + byte[] bigBuffer = new byte[128]; + int bigWritten = SimdHelper.EncodeUtf8Fast(nonAscii, bigBuffer); + Assert.Equal(Encoding.UTF8.GetBytes(nonAscii), bigBuffer[..bigWritten]); + Assert.Equal(Encoding.UTF8.GetByteCount(nonAscii), SimdHelper.GetUtf8ByteCountFast(nonAscii)); + } + + [Fact] + public void IsAscii_DetectsNonAsciiInShortAndLongSpans() + { + Assert.True(SimdHelper.IsAscii([])); + Assert.True(SimdHelper.IsAscii("plain text")); + Assert.True(SimdHelper.IsAscii(new string('a', 100))); + Assert.False(SimdHelper.IsAscii("café")); + Assert.False(SimdHelper.IsAscii(new string('a', 40) + "é" + new string('b', 40))); + } + + [Fact] + public void GetUtf8ByteCountFast_CountsAsciiOneToOne() + { + Assert.Equal(0, SimdHelper.GetUtf8ByteCountFast([])); + Assert.Equal(11, SimdHelper.GetUtf8ByteCountFast("hello world")); + // 漢字 is two BMP characters outside ASCII → 3 bytes each in UTF-8. + Assert.Equal(6, SimdHelper.GetUtf8ByteCountFast("漢字")); + } + + [Fact] + public void ComputeHashCode_IsStableForEqualDataAndDiffersForDifferentData() + { + Assert.Equal(0, SimdHelper.ComputeHashCode([])); + byte[] small = [1, 2, 3]; + Assert.Equal(SimdHelper.ComputeHashCode(small), SimdHelper.ComputeHashCode([1, 2, 3])); + + byte[] first = [.. Enumerable.Range(0, 64).Select(i => (byte)i)]; + byte[] second = [.. first]; + second[63] = 0xFF; + Assert.Equal(SimdHelper.ComputeHashCode(first), SimdHelper.ComputeHashCode([.. first])); + Assert.NotEqual(SimdHelper.ComputeHashCode(first), SimdHelper.ComputeHashCode(second)); + } + + [Fact] + public void SequenceEqual_ComparesShortAndLongSpans() + { + Assert.False(SimdHelper.SequenceEqual([1], [1, 2])); + Assert.True(SimdHelper.SequenceEqual([], [])); + Assert.True(SimdHelper.SequenceEqual([1, 2, 3], [1, 2, 3])); + + byte[] first = [.. Enumerable.Range(0, 64).Select(i => (byte)i)]; + byte[] second = [.. first]; + Assert.True(SimdHelper.SequenceEqual(first, second)); + second[40] = 0xFF; + Assert.False(SimdHelper.SequenceEqual(first, second)); + } + + [Fact] + public void BufferPrimitives_RoundTripTheirContent() + { + byte[] buffer = [1, 2, 3, 4, 5]; + SimdHelper.ZeroBuffer(buffer); + Assert.All(buffer, b => Assert.Equal(0, b)); + + SimdHelper.FillBuffer(buffer, 9); + Assert.All(buffer, b => Assert.Equal(9, b)); + + byte[] destination = new byte[buffer.Length]; + SimdHelper.CopyBuffer(buffer, destination); + Assert.Equal(buffer, destination); + } + + [Fact] + public void RentTempBuffer_ReturnsABufferAtLeastTheRequestedSize() + { + byte[] rented = SimdHelper.RentTempBuffer(100); + Assert.True(rented.Length >= 100); + SimdHelper.ReturnTempBuffer(rented); + + byte[] again = SimdHelper.RentTempBuffer(100); + Assert.True(again.Length >= 100); + SimdHelper.ReturnTempBuffer(again); + } + + [Fact] + public void GetSimdCapabilities_ReportsAtLeastTheCommonBaseline() + { + string capabilities = SimdHelper.GetSimdCapabilities(); + Assert.False(string.IsNullOrWhiteSpace(capabilities)); + Assert.True(SimdHelper.GetOptimalVectorSizeBytes >= 16); + } + + [Fact] + public void DeserializeBatchInt32_ScalarPath_ReadsFlagsAndValues() + { + // 1-byte flag + 4-byte little-endian value, per item (the scalar tail layout). + byte[] data = + [ + 1, .. BitConverter.GetBytes(42), + 0, + 1, .. BitConverter.GetBytes(-7), + ]; + int[] results = new int[3]; + + Assert.Equal(11, SimdHelper.DeserializeBatchInt32(data, results)); + Assert.Equal([42, 0, -7], results); + Assert.Equal(0, SimdHelper.DeserializeBatchInt32(data, [])); + } + + [Fact] + public void DeserializeBatchInt32_TruncatedData_StopsAtTheBoundary() + { + // A flag without room for its value must stop the read rather than throw. + byte[] data = [1, 1, 0]; + int[] results = new int[2]; + int consumed = SimdHelper.DeserializeBatchInt32(data, results); + Assert.Equal(1, consumed); + Assert.Equal(0, results[1]); + } + + [Fact] + public void DeserializeBatchInt64_ReadsInterleavedFlagsAndValues() + { + // Every item occupies 9 bytes whether or not it is null: a null is its flag byte plus eight + // reserved (zero) value bytes, because the batch reader steps by i * 9. + byte[] data = + [ + 1, .. BitConverter.GetBytes(9_000_000_000L), + 0, .. new byte[8], + 1, .. BitConverter.GetBytes(-5L), + 1, .. BitConverter.GetBytes(7L), + ]; + long[] results = new long[4]; + + Assert.Equal(36, SimdHelper.DeserializeBatchInt64(data, results)); + Assert.Equal([9_000_000_000L, 0, -5L, 7L], results); + } + + [Fact] + public void DeserializeBatchDouble_ReadsTheFlagBlockThenTheValues() + { + // The double batch layout is the flags of the batch first, then the four values contiguously + // (unlike the int64/decimal readers, which interleave flag and value per item). + byte[] data = + [ + 1, 1, 0, 1, + .. BitConverter.GetBytes(2.5), + .. BitConverter.GetBytes(-0.25), + .. BitConverter.GetBytes(9.0), // reserved bytes behind a null flag: must be ignored + .. BitConverter.GetBytes(1.5), + ]; + double[] results = new double[4]; + + Assert.Equal(36, SimdHelper.DeserializeBatchDouble(data, results)); + Assert.Equal([2.5, -0.25, 0.0, 1.5], results); + } + + [Fact] + public void DeserializeBatchDecimal_ReadsFlagsAndSixteenByteDecimals() + { + byte[] value = new byte[16]; + int[] bits = decimal.GetBits(12.34m); + for (int i = 0; i < 4; i++) + { + BitConverter.GetBytes(bits[i]).CopyTo(value, i * 4); + } + + byte[] data = [1, .. value, 0]; + decimal[] results = new decimal[2]; + + // 1 flag + 16 bytes for the value, then a null flag byte alone. + Assert.Equal(18, SimdHelper.DeserializeBatchDecimal(data, results)); + Assert.Equal([12.34m, 0m], results); + } +} diff --git a/tests/SharpCoreDB.Tests/SingleFileBatchSchemaIsolationTests.cs b/tests/SharpCoreDB.Tests/SingleFileBatchSchemaIsolationTests.cs new file mode 100644 index 00000000..3d87d20f --- /dev/null +++ b/tests/SharpCoreDB.Tests/SingleFileBatchSchemaIsolationTests.cs @@ -0,0 +1,93 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using System; +using System.IO; +using Xunit; + +/// +/// Regression test for a cross-database defect the wider suite surfaced: the single-file batch path kept a +/// static prepared-INSERT cache keyed by the table NAME only, so two databases whose tables share a +/// name but not a shape mapped each other's rows through the wrong column list — a valid +/// INSERT INTO docs (name, age) failed with "Column 'name' cannot be NULL" once another database's +/// docs shape had filled the cache. The key now carries the column signature (name + columns + types). +/// +public sealed class SingleFileBatchSchemaIsolationTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _pathA; + private readonly string _pathB; + + public SingleFileBatchSchemaIsolationTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + var root = Path.Combine(Path.GetTempPath(), $"SCDB_BatchShape_{Guid.NewGuid():N}"); + Directory.CreateDirectory(root); + _pathA = Path.Combine(root, "a.scdb"); + _pathB = Path.Combine(root, "b.scdb"); + } + + public void Dispose() + { + try + { + var dir = Path.GetDirectoryName(_pathA); + if (dir is not null && Directory.Exists(dir)) Directory.Delete(dir, true); + } + catch { } + } + + private IDatabase Open(string path) => + _factory.CreateWithOptions(path, "pw", DatabaseOptions.CreateSingleFileDefault()); + + [Fact] + public void BatchInsert_OnTwoDatabasesWithSameTableNameDifferentShapes_MapsEachShape() + { + var a = Open(_pathA); + var b = Open(_pathB); + try + { + a.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, body TEXT)"); + b.ExecuteSQL("CREATE TABLE docs (name TEXT NOT NULL, age INTEGER)"); + + // A first, so the shared cache holds A's `docs` shape when B's batch is parsed. + a.ExecuteBatchSQL(new[] + { + "INSERT INTO docs (id, body) VALUES (1, 'alpha')", + "INSERT INTO docs (id, body) VALUES (2, 'beta')", + }); + + // Red before the shape-key fix: this mapped B's rows through A's columns and threw + // "Column 'name' cannot be NULL". + b.ExecuteBatchSQL(new[] + { + "INSERT INTO docs (name, age) VALUES ('Ann', 30)", + "INSERT INTO docs (name, age) VALUES ('Bob', 40)", + }); + + var aRows = a.ExecuteQuery("SELECT id, body FROM docs ORDER BY id"); + Assert.Equal(2, aRows.Count); + Assert.Equal("alpha", aRows[0]["body"] as string); + Assert.Equal("beta", aRows[1]["body"] as string); + + var bRows = b.ExecuteQuery("SELECT name, age FROM docs ORDER BY name"); + Assert.Equal(2, bRows.Count); + Assert.Equal("Ann", bRows[0]["name"] as string); + Assert.Equal(30, Convert.ToInt32(bRows[0]["age"])); + Assert.Equal("Bob", bRows[1]["name"] as string); + Assert.Equal(40, Convert.ToInt32(bRows[1]["age"])); + } + finally + { + (a as IDisposable)?.Dispose(); + (b as IDisposable)?.Dispose(); + } + } +} diff --git a/tests/SharpCoreDB.Tests/SingleFileCollationTests.cs b/tests/SharpCoreDB.Tests/SingleFileCollationTests.cs new file mode 100644 index 00000000..ab8f2b1f --- /dev/null +++ b/tests/SharpCoreDB.Tests/SingleFileCollationTests.cs @@ -0,0 +1,135 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using System; +using System.IO; +using System.Linq; +using Xunit; + +/// +/// Pins owner decision D2=A (plan 009): a column's declared `COLLATE NOCASE` is parsed, persisted in the +/// single-file column entry (bits 8-11 of the flags) and honoured by the WHERE evaluator and ORDER BY, on +/// both the first session and a reopen. A column without a declared collation stays BINARY. +/// +public sealed class SingleFileCollationTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _scdbPath; + + public SingleFileCollationTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _scdbPath = Path.Combine(Path.GetTempPath(), $"SCDB_Collation_{Guid.NewGuid():N}.scdb"); + } + + public void Dispose() + { + try { if (File.Exists(_scdbPath)) File.Delete(_scdbPath); } catch { } + } + + private IDatabase Open() => + _factory.CreateWithOptions(_scdbPath, "pw", DatabaseOptions.CreateSingleFileDefault()); + + private static void Seed(IDatabase db) + { + db.ExecuteSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT, nc TEXT COLLATE NOCASE)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'alpha', 'bb')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'beta', 'Dddd')"); + db.ExecuteSQL("INSERT INTO t VALUES (3, 'gamma', 'aaa')"); + } + + private static int[] Ids(IDatabase db, string sql) => + db.ExecuteQuery(sql).Select(r => Convert.ToInt32(r["id"])).ToArray(); + + [Fact] + public void NoCaseColumn_WhereEquality_IsCaseInsensitive_AndSurvivesReopen() + { + var db = Open(); + try { Seed(db); } + finally { (db as IDisposable)?.Dispose(); } + + // Reopen: the collation must come back from the persisted column entry. + db = Open(); + try + { + Assert.Equal(new[] { 2 }, Ids(db, "SELECT id FROM t WHERE nc = 'DDDD'")); + Assert.Equal(new[] { 2 }, Ids(db, "SELECT id FROM t WHERE nc = 'dddd'")); + // OrdinalIgnoreCase: only 'Dddd' sorts above 'bb'; ordinal would answer none. + Assert.Equal(new[] { 2 }, Ids(db, "SELECT id FROM t WHERE nc > 'bb'")); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void BinaryColumn_StaysCaseSensitive() + { + var db = Open(); + try + { + Seed(db); + // `name` declares no collation → BINARY: an upper-case literal matches nothing. + Assert.Empty(Ids(db, "SELECT id FROM t WHERE name = 'ALPHA'")); + Assert.Equal(new[] { 1 }, Ids(db, "SELECT id FROM t WHERE name = 'alpha'")); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void NoCaseColumn_OrderBy_SortsCaseInsensitively() + { + var db = Open(); + try + { + Seed(db); + // OrdinalIgnoreCase: aaa < bb < Dddd → ids 3, 1, 2 (ordinal would put Dddd first: 2, 3, 1). + Assert.Equal(new[] { 3, 1, 2 }, Ids(db, "SELECT id FROM t ORDER BY nc")); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void RTrimColumn_WhereEquality_IgnoresTrailingWhitespace_AndSurvivesReopen() + { + var db = Open(); + try + { + db.ExecuteSQL("CREATE TABLE r (id INTEGER PRIMARY KEY, rc TEXT COLLATE RTRIM, bin TEXT)"); + db.ExecuteSQL("INSERT INTO r VALUES (1, 'abc ', 'abc ')"); + db.ExecuteSQL("INSERT INTO r VALUES (2, 'abc', 'abc')"); + } + finally { (db as IDisposable)?.Dispose(); } + + db = Open(); + try + { + // RTRIM: the trailing blanks do not count, so both rows equal 'abc'. + Assert.Equal(new[] { 1, 2 }, Ids(db, "SELECT id FROM r WHERE rc = 'abc'")); + // The undeclared column stays BINARY and distinguishes them. + Assert.Equal(new[] { 2 }, Ids(db, "SELECT id FROM r WHERE bin = 'abc'")); + } + finally { (db as IDisposable)?.Dispose(); } + } + + [Fact] + public void RTrimColumn_OrderBy_TreatsTrailingWhitespaceAsEqual() + { + var db = Open(); + try + { + db.ExecuteSQL("CREATE TABLE r (id INTEGER PRIMARY KEY, rc TEXT COLLATE RTRIM)"); + // Insertion order makes the tie visible: RTRIM sorts 'a ' and 'a' equal, so the second key decides + // (ids 1, 2); ordinal BINARY would sort 'a' before 'a ' and answer 2, 1. + db.ExecuteSQL("INSERT INTO r VALUES (1, 'a ')"); + db.ExecuteSQL("INSERT INTO r VALUES (2, 'a')"); + Assert.Equal(new[] { 1, 2 }, Ids(db, "SELECT id FROM r ORDER BY rc, id")); + } + finally { (db as IDisposable)?.Dispose(); } + } +} diff --git a/tests/SharpCoreDB.Tests/SingleFileCompressionTests.cs b/tests/SharpCoreDB.Tests/SingleFileCompressionTests.cs new file mode 100644 index 00000000..05caffa3 --- /dev/null +++ b/tests/SharpCoreDB.Tests/SingleFileCompressionTests.cs @@ -0,0 +1,128 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using SharpCoreDB.Storage; +using System; +using System.IO; +using System.Linq; +using Xunit; + +/// +/// Pins owner decision D4=C (plan 009): Zstandard is a supported, opt-in single-file block compression mode +/// (in-box .NET 11 ZstandardStream, no package), it actually shrinks the file, and every block records +/// the mode it was written with — so a Zstd file opens and reads correctly without that option, and an +/// encrypted file keeps the compress-then-encrypt ordering. +/// +public sealed class SingleFileCompressionTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _root; + + public SingleFileCompressionTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _root = Path.Combine(Path.GetTempPath(), $"SCDB_Zstd_{Guid.NewGuid():N}"); + Directory.CreateDirectory(_root); + } + + public void Dispose() + { + try { if (Directory.Exists(_root)) Directory.Delete(_root, true); } catch { } + } + + /// A highly compressible ~1 KB text, so the row block crosses the compression threshold. + private static string Payload(int i) => + $"row-{i}-" + string.Concat(Enumerable.Repeat("the quick brown fox jumps over the lazy dog; ", 24)); + + private void Seed(IDatabase db, int rows) + { + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, body TEXT)"); + + // One batch → the row block is written once (an incremental insert grows the file page by page and + // never shrinks it, so only this shape makes the on-disk sizes comparable). + var statements = new System.Collections.Generic.List(rows); + for (int i = 1; i <= rows; i++) + { + statements.Add($"INSERT INTO docs (id, body) VALUES ({i}, '{Payload(i)}')"); + } + + db.ExecuteBatchSQL(statements); + db.Flush(); + } + + private IDatabase Open(string path, BlockCompressionMode mode, bool encrypt = false) + { + var options = DatabaseOptions.CreateSingleFileDefault( + enableEncryption: encrypt, + encryptionKey: encrypt ? new byte[32] : null); + options.BlockCompression = mode; + return _factory.CreateWithOptions(path, "pw", options); + } + + [Fact] + public void Zstd_BlockCompression_RoundTripsAndRejectsTheWrongMode() + { + var zstdPath = Path.Combine(_root, "zstd.scdb"); + + var zstd = Open(zstdPath, BlockCompressionMode.Zstd); + try { Seed(zstd, 200); } + finally { (zstd as IDisposable)?.Dispose(); } + + // Same mode → every value round-trips, and a write in this session stays readable. + var reopened = Open(zstdPath, BlockCompressionMode.Zstd); + try + { + var all = reopened.ExecuteQuery("SELECT id, body FROM docs"); + Assert.Equal(200, all.Count); + foreach (var row in all) + { + int id = Convert.ToInt32(row["id"]); + Assert.Equal(Payload(id), row["body"] as string); + } + + reopened.ExecuteSQL("UPDATE docs SET body = @body WHERE id = @id", + new System.Collections.Generic.Dictionary { ["@id"] = 7, ["@body"] = "updated" }); + var updated = reopened.ExecuteQuery("SELECT body FROM docs WHERE id = @id", + new System.Collections.Generic.Dictionary { ["@id"] = 7 }); + Assert.Equal("updated", updated[0]["body"] as string); + } + finally { (reopened as IDisposable)?.Dispose(); } + + // The file records its compression mode in the SCDB header: opening it with the wrong mode fails fast + // with an actionable message instead of handing back garbled rows. + var wrongMode = Assert.Throws(() => + { + var db = Open(zstdPath, BlockCompressionMode.None); + (db as IDisposable)?.Dispose(); + }); + Assert.Contains("Zstd", wrongMode.Message); + Assert.Contains("BlockCompression", wrongMode.Message); + } + + [Fact] + public void Zstd_BlockCompression_WithEncryption_RoundTripsAfterReopen() + { + var path = Path.Combine(_root, "zstd-encrypted.scdb"); + + var db = Open(path, BlockCompressionMode.Zstd, encrypt: true); + try { Seed(db, 50); } + finally { (db as IDisposable)?.Dispose(); } + + // Reopen with the same options (the key is required) — the compress-then-encrypt ordering must hold. + var reopened = Open(path, BlockCompressionMode.Zstd, encrypt: true); + try + { + var rows = reopened.ExecuteQuery("SELECT id, body FROM docs"); + Assert.Equal(50, rows.Count); + Assert.All(rows, row => Assert.Equal(Payload(Convert.ToInt32(row["id"])), row["body"] as string)); + } + finally { (reopened as IDisposable)?.Dispose(); } + } +} diff --git a/tests/SharpCoreDB.Tests/SingleFileKeyMoveTests.cs b/tests/SharpCoreDB.Tests/SingleFileKeyMoveTests.cs new file mode 100644 index 00000000..3d2c1d9f --- /dev/null +++ b/tests/SharpCoreDB.Tests/SingleFileKeyMoveTests.cs @@ -0,0 +1,315 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace SharpCoreDB.Tests; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using Xunit; + +/// +/// Pins owner decision D1=A (plan 009) on every UPDATE and DELETE path of single-file storage: a moved primary +/// key must not land on another row, the key set follows the move, and a DELETE releases the key again. The +/// statement-atomicity requirement — a rejected UPDATE changes nothing — is asserted with the row snapshot. +/// +public sealed class SingleFileKeyMoveTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _root = Path.Combine(Path.GetTempPath(), $"SCDB_KeyMove_{Guid.NewGuid():N}"); + + public SingleFileKeyMoveTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + Directory.CreateDirectory(_root); + } + + public void Dispose() + { + try + { + if (Directory.Exists(_root)) + { + Directory.Delete(_root, true); + } + } + catch (IOException) + { + // Best-effort cleanup of a temp directory. + } + } + + private IDatabase Open(string ddl) + { + var path = Path.Combine(_root, $"db_{Guid.NewGuid():N}.scdb"); + var db = _factory.CreateWithOptions(path, "pw", DatabaseOptions.CreateSingleFileDefault()); + db.ExecuteSQL(ddl); + return db; + } + + private SingleFileTable Table(IDatabase db, string name) + { + Assert.True(db.TryGetTable(name, out var table)); + return Assert.IsType(table); + } + + private static string[] Rows(IDatabase db, string sql) => + [.. db.ExecuteQuery(sql).Select(r => string.Join(",", r.Values.Select(v => Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture))))]; + + [Fact] + public void Update_MovingAPrimaryKeyOntoAnExistingRow_ThrowsAndChangesNothing() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + + Assert.ThrowsAny(() => db.ExecuteSQL("UPDATE t SET id = 2 WHERE id = 1")); + Assert.Equal(["1,a", "2,b"], Rows(db, "SELECT id, name FROM t").Order()); + } + + [Fact] + public void Update_MovingAPrimaryKeyToAFreeValue_MovesTheRowAndFreesTheOldKey() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + + db.ExecuteSQL("UPDATE t SET id = 9 WHERE id = 1"); + + Assert.Empty(db.ExecuteQuery("SELECT id FROM t WHERE id = 1")); + Assert.Equal(["9,a"], Rows(db, "SELECT id, name FROM t WHERE id = 9")); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'new')"); + Assert.Equal(2, db.ExecuteQuery("SELECT id FROM t").Count); + } + + [Fact] + public void Update_ChangingANonKeyColumn_KeepsKeyResolution() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + + db.ExecuteSQL("UPDATE t SET name = 'z' WHERE id = 1"); + + Assert.Equal(["1,z"], Rows(db, "SELECT id, name FROM t WHERE id = 1")); + // The untouched key still rejects a duplicate. + Assert.ThrowsAny(() => db.ExecuteSQL("INSERT INTO t VALUES (1, 'dup')")); + } + + [Fact] + public void UpdateAffectedCount_ComputedOverload_MovingOntoAnExistingKey_ThrowsAndChangesNothing() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + var table = Table(db, "t"); + + Assert.ThrowsAny(() => table.UpdateAffectedCount( + "id = 1", + new Dictionary { ["name"] = "x" }, + [new KeyValuePair, object?>>("id", _ => 2)])); + Assert.Equal(["1,a", "2,b"], Rows(db, "SELECT id, name FROM t").Order()); + } + + [Fact] + public void UpdateAffectedCount_ComputedOverload_MovingToAFreeKey_Succeeds() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + var table = Table(db, "t"); + + int affected = table.UpdateAffectedCount( + "id = 1", + new Dictionary { ["name"] = "x" }, + [new KeyValuePair, object?>>("id", _ => 5)]); + + Assert.Equal(1, affected); + Assert.Equal(["5,x"], Rows(db, "SELECT id, name FROM t WHERE id = 5")); + Assert.Empty(db.ExecuteQuery("SELECT id FROM t WHERE id = 1")); + } + + [Fact] + public void UpdateBatch_MovingARowOntoAnExistingKey_Throws() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + var table = Table(db, "t"); + + Assert.ThrowsAny(() => table.UpdateBatch( + new Dictionary> { [1] = new() { ["id"] = 2 } })); + Assert.Equal(["1,a", "2,b"], Rows(db, "SELECT id, name FROM t").Order()); + } + + [Fact] + public void UpdateBatch_MovingRowsToFreeKeys_RelocatesThem() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + var table = Table(db, "t"); + + table.UpdateBatch(new Dictionary> + { + [1] = new() { ["id"] = 7 }, + [2] = new() { ["id"] = 8 }, + }); + + Assert.Equal(["7,a", "8,b"], Rows(db, "SELECT id, name FROM t").Order()); + Assert.Empty(db.ExecuteQuery("SELECT id FROM t WHERE id = 1 OR id = 2")); + } + + [Fact] + public void UpdateBatch_MovingTwoRowsOntoTheSameKey_Throws() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + var table = Table(db, "t"); + + Assert.ThrowsAny(() => table.UpdateBatch(new Dictionary> + { + [1] = new() { ["id"] = 5 }, + [2] = new() { ["id"] = 5 }, + })); + } + + [Fact] + public void UpdateByPrimaryKey_MovingOntoAnExistingKey_Throws() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + + Assert.ThrowsAny(() => db.UpdateByPrimaryKey("t", 1, new Dictionary { ["id"] = 2 })); + Assert.Equal(["1,a", "2,b"], Rows(db, "SELECT id, name FROM t").Order()); + } + + [Fact] + public void UpdateByPrimaryKey_MovingToAFreeKey_MakesTheRowAddressableByItsNewKey() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + + Assert.True(db.UpdateByPrimaryKey("t", 1, new Dictionary { ["id"] = 9 })); + + Assert.Equal(["9,a"], Rows(db, "SELECT id, name FROM t WHERE id = 9")); + Assert.Empty(db.ExecuteQuery("SELECT id FROM t WHERE id = 1")); + } + + [Fact] + public void DeleteByPrimaryKey_ThenReinsertTheSameKey_Succeeds() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + + Assert.True(db.DeleteByPrimaryKey("t", 1)); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'again')"); + + Assert.Equal(["1,again"], Rows(db, "SELECT id, name FROM t")); + } + + [Fact] + public void DeleteAll_ThenReinsertPreviouslyUsedKeys_Succeeds() + { + var db = Open("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + + db.ExecuteSQL("DELETE FROM t"); + + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 'b')"); + Assert.Equal(2, db.ExecuteQuery("SELECT id FROM t").Count); + } + + [Fact] + public void DeleteAffectedRows_ThenReinsertTheSameCompositeKey_Succeeds() + { + var db = Open("CREATE TABLE t (a INTEGER NOT NULL, b INTEGER NOT NULL, v TEXT, PRIMARY KEY (a, b))"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 1, 'x')"); + var table = Table(db, "t"); + + Assert.Single(table.DeleteAffectedRows("a = 1")); + db.ExecuteSQL("INSERT INTO t VALUES (1, 1, 'again')"); + + Assert.Equal(["1,1,again"], Rows(db, "SELECT a, b, v FROM t")); + } + + [Fact] + public void CompositePrimaryKey_UpdateOntoAnExistingTuple_ThrowsAndChangesNothing() + { + var db = Open("CREATE TABLE t (a INTEGER NOT NULL, b INTEGER NOT NULL, v TEXT, PRIMARY KEY (a, b))"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 1, 'x')"); + db.ExecuteSQL("INSERT INTO t VALUES (2, 2, 'y')"); + + Assert.ThrowsAny(() => db.ExecuteSQL("UPDATE t SET a = 2, b = 2 WHERE a = 1")); + Assert.Equal(["1,1,x", "2,2,y"], Rows(db, "SELECT a, b, v FROM t").Order()); + } + + [Fact] + public void CompositePrimaryKey_UpdateToAFreeTuple_SucceedsAndFreesTheOldOne() + { + var db = Open("CREATE TABLE t (a INTEGER NOT NULL, b INTEGER NOT NULL, v TEXT, PRIMARY KEY (a, b))"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 1, 'x')"); + + db.ExecuteSQL("UPDATE t SET b = 3 WHERE a = 1"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 1, 'reused')"); + + Assert.Equal(["1,1,reused", "1,3,x"], Rows(db, "SELECT a, b, v FROM t").Order()); + } + + [Fact] + public void NoCaseKey_InsertingACaseVariantOfAnExistingKey_IsRejected() + { + var db = Open("CREATE TABLE t (k TEXT COLLATE NOCASE PRIMARY KEY, v TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES ('aa', '1')"); + + Assert.ThrowsAny(() => db.ExecuteSQL("INSERT INTO t VALUES ('AA', '2')")); + Assert.Single(db.ExecuteQuery("SELECT k FROM t")); + } + + [Fact] + public void NoCaseKey_UpdateOntoACaseVariantOfAnotherRowsKey_Throws() + { + var db = Open("CREATE TABLE t (k TEXT COLLATE NOCASE PRIMARY KEY, v TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES ('aa', '1')"); + db.ExecuteSQL("INSERT INTO t VALUES ('Bb', '2')"); + + Assert.ThrowsAny(() => db.ExecuteSQL("UPDATE t SET k = 'AA' WHERE v = '2'")); + Assert.Equal(["1,aa", "2,Bb"], Rows(db, "SELECT v, k FROM t").Order()); + } + + [Fact] + public void RTrimKey_TrailingWhitespaceIsIgnoredForUniqueness() + { + var db = Open("CREATE TABLE t (k TEXT COLLATE RTRIM PRIMARY KEY, v TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES ('abc ', '1')"); + + Assert.ThrowsAny(() => db.ExecuteSQL("INSERT INTO t VALUES ('abc', '2')")); + Assert.Single(db.ExecuteQuery("SELECT k FROM t")); + } + + [Fact] + public void KeyMove_SurvivesReopen() + { + var path = Path.Combine(_root, $"db_{Guid.NewGuid():N}.scdb"); + var db = _factory.CreateWithOptions(path, "pw", DatabaseOptions.CreateSingleFileDefault()); + db.ExecuteSQL("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)"); + db.ExecuteSQL("INSERT INTO t VALUES (1, 'a')"); + db.ExecuteSQL("UPDATE t SET id = 9 WHERE id = 1"); + (db as IDisposable)?.Dispose(); + + var reopened = _factory.CreateWithOptions(path, "pw", DatabaseOptions.CreateSingleFileDefault()); + Assert.Equal(["9,a"], Rows(reopened, "SELECT id, name FROM t WHERE id = 9")); + Assert.ThrowsAny(() => reopened.ExecuteSQL("INSERT INTO t VALUES (9, 'dup')")); + reopened.ExecuteSQL("INSERT INTO t VALUES (1, 'free')"); + Assert.Equal(2, reopened.ExecuteQuery("SELECT id FROM t").Count); + (reopened as IDisposable)?.Dispose(); + } +} diff --git a/tests/SharpCoreDB.Tests/SingleFileMetadataParityTests.cs b/tests/SharpCoreDB.Tests/SingleFileMetadataParityTests.cs new file mode 100644 index 00000000..e9ee8af7 --- /dev/null +++ b/tests/SharpCoreDB.Tests/SingleFileMetadataParityTests.cs @@ -0,0 +1,78 @@ +// +// Copyright (c) 2026 MPCoreDeveloper. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// +namespace SharpCoreDB.Tests; + +using Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using System; +using System.IO; +using System.Linq; +using Xunit; + +/// +/// Pins plan 008: db is IMetadataProvider answers the same for both storage modes, and the metadata +/// it returns agrees column for column. Before the change SingleFileDatabase had the methods (via +/// IDatabase) but not the interface, so the probe was true for a directory database and false for a +/// .scdb file — the roadmap item's explicit acceptance is that the two modes answer alike. +/// +public sealed class SingleFileMetadataParityTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _dirPath; + private readonly string _scdbPath; + + public SingleFileMetadataParityTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + _dirPath = Path.Combine(Path.GetTempPath(), $"SCDB_MetaParity_Dir_{Guid.NewGuid():N}"); + _scdbPath = Path.Combine(Path.GetTempPath(), $"SCDB_MetaParity_Scdb_{Guid.NewGuid():N}.scdb"); + } + + public void Dispose() + { + try { if (File.Exists(_scdbPath)) File.Delete(_scdbPath); } catch { } + try { if (Directory.Exists(_dirPath)) Directory.Delete(_dirPath, true); } catch { } + } + + [Fact] + public void MetadataProvider_ProbeAndMetadata_AgreeAcrossStorageModes() + { + var singleFile = _factory.CreateWithOptions(_scdbPath, "pw", DatabaseOptions.CreateSingleFileDefault()); + var directory = _factory.Create(_dirPath, "pw"); + try + { + const string ddl = "CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL)"; + singleFile.ExecuteSQL(ddl); + directory.ExecuteSQL(ddl); + + // The probe: both modes must answer yes (the .scdb side was false before the change). + Assert.True(singleFile is IMetadataProvider, "single-file database must be an IMetadataProvider"); + Assert.True(directory is IMetadataProvider, "directory database must be an IMetadataProvider"); + + var singleTables = ((IMetadataProvider)singleFile).GetTables(); + var dirTables = ((IMetadataProvider)directory).GetTables(); + Assert.Contains(singleTables, t => t.Name == "docs" && t.Type == "TABLE"); + Assert.Contains(dirTables, t => t.Name == "docs" && t.Type == "TABLE"); + + // Column parity — the fields a schema tool reads, compared one for one. + var singleColumns = ((IMetadataProvider)singleFile).GetColumns("docs") + .Select(c => (c.Table, c.Name, c.DataType, c.Ordinal, c.IsNullable, c.Collation)) + .ToList(); + var dirColumns = ((IMetadataProvider)directory).GetColumns("docs") + .Select(c => (c.Table, c.Name, c.DataType, c.Ordinal, c.IsNullable, c.Collation)) + .ToList(); + + Assert.Equal(dirColumns, singleColumns); + Assert.Equal(new[] { "id", "name", "score" }, singleColumns.Select(c => c.Name)); + } + finally + { + (singleFile as IDisposable)?.Dispose(); + (directory as IDisposable)?.Dispose(); + } + } +} diff --git a/tests/SharpCoreDB.Tests/SingleTableOrderByTests.cs b/tests/SharpCoreDB.Tests/SingleTableOrderByTests.cs index 8908c4aa..a828c184 100644 --- a/tests/SharpCoreDB.Tests/SingleTableOrderByTests.cs +++ b/tests/SharpCoreDB.Tests/SingleTableOrderByTests.cs @@ -102,9 +102,7 @@ public void OrderBy_OnTheSingleTablePath_SortsAsSqliteDoes(string mode, string s Assert.Equal(expectedIds, ids); } - [Fact(Skip = "Single-file storage does not record a column's declared COLLATE (it is neither parsed nor persisted, " + - "and its WHERE evaluator has no collation support): an owner decision on extending the column-entry " + - "format is pending. See docs/sharpcoredb-known-issues.md, 'Single-file storage ignores COLLATE'.")] + [Fact] public void OrderBy_ColumnDeclaredNoCase_OnSingleFile_SortsCaseInsensitively() { var db = Open("single-file"); diff --git a/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs b/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs index a33da7b0..ade7600a 100644 --- a/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs +++ b/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs @@ -291,6 +291,16 @@ static async Task Main(string[] args) return; } + // Optional: --pk-prepared → the prepared-statement path vs the raw-SQL path on the same data: + // the same 10.000 `UPDATE docs SET score = WHERE id = ` updates, once through + // ExecuteBatchSQL (raw SQL, one parse per statement) and once through ExecuteBatchPrepared + // (template classified once, parameters bound per row). Reports prepared/raw, not SQLite. + if (args.Any(a => a.Equals("--pk-prepared", StringComparison.OrdinalIgnoreCase))) + { + RunPkPreparedBenchmark(ParseEngineType(args)); + return; + } + // Optional: --pk-default → fair PK comparison using PURE default DatabaseConfig // (NoEncryptMode stays at its default false, no harness-only flags). Proves that the // out-of-the-box default path engages the fixed-width fast paths vs SQLite. @@ -4126,6 +4136,86 @@ static void RunPkInsertProfile(SharpCoreDB.Interfaces.StorageEngineType engineTy Console.WriteLine(" Per-statement stages fire once per InsertBatch call; per-row stages fire once per row."); } + /// + /// Prepared-statement path vs the raw-SQL path, same data, same run: 10.000 + /// UPDATE docs SET score = <v> WHERE id = <i> updates through ExecuteBatchSQL + /// (raw, one parse per statement) and through ExecuteBatchPrepared (template classified once, + /// parameters bound per row). Acceptance is "prepared beats raw by a measured margin" — it reports + /// prepared/raw, never against SQLite's raw arm as if the shapes were the same. + /// + static void RunPkPreparedBenchmark(SharpCoreDB.Interfaces.StorageEngineType engineType) + { + const int rows = 100_000; + const int updates = 10_000; + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + var sp = services.BuildServiceProvider(); + var factory = sp.GetRequiredService(); + var config = BuildConfig(engineType); + var dbPath = Path.Combine(BenchTempDirectory(), $"scdb-pk-prepared-{Guid.NewGuid()}"); + Console.WriteLine($"=== PREPARED vs RAW UPDATE (--pk-prepared), engine={engineType}, {rows:N0} rows / {updates:N0} updates ==="); + + using var db = (SharpCoreDB.Database)factory.Create(dbPath: dbPath, masterPassword: BenchDbPassword, isReadOnly: false, config: config); + try + { + db.ExecuteSQL("CREATE TABLE docs (id INTEGER PRIMARY KEY, name TEXT, score REAL)"); + for (int b = 0; b < rows; b += 10_000) + { + var batch = new List>(10_000); + for (int i = b; i < b + 10_000; i++) + { + batch.Add(new Dictionary { ["id"] = i, ["name"] = $"User{i}", ["score"] = i * 0.5 }); + } + + db.InsertBatch("docs", batch); + } + + db.Flush(); + db.ExecuteSQL("UPDATE docs SET score = 1.0 WHERE id = 0"); // warm-up + + var raw = new List(updates); + var paramSets = new List>(updates); + for (int i = 0; i < updates; i++) + { + raw.Add(string.Format(CultureInfo.InvariantCulture, "UPDATE docs SET score = {0:F1} WHERE id = {1}", i * 99.9, i)); + paramSets.Add(new Dictionary { ["@score"] = i * 99.9, ["@id"] = i }); + } + + const string template = "UPDATE docs SET score = @score WHERE id = @id"; + + var sw = Stopwatch.StartNew(); + db.ExecuteBatchSQL(raw); + sw.Stop(); + var rawOps = updates / sw.Elapsed.TotalSeconds; + + sw.Restart(); + db.ExecuteBatchPrepared(template, paramSets); + sw.Stop(); + var preparedOps = updates / sw.Elapsed.TotalSeconds; + + Console.WriteLine($" RAW ExecuteBatchSQL : {updates / rawOps * 1000:F1} ms ({rawOps:N0} ops/sec)"); + Console.WriteLine($" PREPARED ExecuteBatchPrepared : {updates / preparedOps * 1000:F1} ms ({preparedOps:N0} ops/sec)"); + Console.WriteLine($" prepared / raw : {preparedOps / rawOps:F2}x (>1 = prepared faster)"); + + var chk = db.ExecuteQuery("SELECT score FROM docs WHERE id = @id", new Dictionary { ["@id"] = 500 }); + Console.WriteLine($" verify id=500 score={chk[0]["score"]} (expected {500 * 99.9})"); + } + finally + { + try + { + if (Directory.Exists(dbPath)) + { + Directory.Delete(dbPath, true); + } + } + catch + { + // best-effort cleanup + } + } + } + static void RunPkComparison(SharpCoreDB.Interfaces.StorageEngineType engineType) { var engineLabel = engineType == SharpCoreDB.Interfaces.StorageEngineType.PageBased ? "PageBased" : "AppendOnly";