From 7ac699e2d802367e5144f224b375e6a4cf6e88a3 Mon Sep 17 00:00:00 2001 From: MPCoreDeveloper Date: Sun, 29 Nov 2026 12:53:57 +0100 Subject: [PATCH 1/2] fix: serialize database metadata only on schema change (#532) Database.Flush() called SaveMetadata() unconditionally, so any caller that flushed per operation (a durable queue write, a log append, a move or a delete) paid a full TableMetadataDto build + JSON serialization + meta.dat rewrite on every row -- measured ~1.45 ms/op on NTFS and ~24.8 ms/op on ReFS. Introduce a dedicated schema-dirty signal (_schemaDirty), separate from the existing data-dirty flag (_metadataDirty, set by INSERT/UPDATE/DELETE for SELECT visibility), and call SaveMetadata() from Flush() only when the schema actually changed. The DDL path already persists the schema eagerly through ForceSave() (and the batch dispatcher / Dispose save it directly), so a data-only flush now skips the metadata work while the data flush (WAL batch buffer, tables, storage provider, storage engine) and its durability are unchanged. Also document the 2.2.0 EnableAtRestRecordEncryption default flip (false in 2.0.0.x, true in 2.2.0; ~40% point-read cost; EnableBatchEncryption is a different layer) on the property and in the changelog, and pin the secure default with DatabaseConfigDefaultsTests so an accidental flip back fails the build (#531). Tests: - DatabaseFlushMetadataTests (4 cases) -- 2 failed before (MetadataSaveCount 1->2 on one flush, 1->21 over 20 flushes) and pass after. - DatabaseConfigDefaultsTests (2 cases). Wider core suite: 3091 tests / 0 failed / 22 skipped; canaries + new tests 63/63. Build: 0 errors. Refs #532, #531. #532 closes only after the reporter's ServiceMq harness is re-run against the fixed build (see .clinerules/30-issue-closure.md). --- docs/CHANGELOG.md | 5 + specs/001-metadata-flush-cost/plan.md | 110 ++++++++++++++ specs/001-metadata-flush-cost/spec.md | 109 ++++++++++++++ specs/001-metadata-flush-cost/tasks.md | 79 ++++++++++ .../Database/Core/Database.Core.cs | 37 ++++- .../Database/Execution/Database.Batch.cs | 1 + .../Database/Execution/Database.Execution.cs | 4 + src/SharpCoreDB/DatabaseConfig.cs | 17 +++ .../DatabaseConfigDefaultsTests.cs | 44 ++++++ .../DatabaseFlushMetadataTests.cs | 142 ++++++++++++++++++ 10 files changed, 547 insertions(+), 1 deletion(-) create mode 100644 specs/001-metadata-flush-cost/plan.md create mode 100644 specs/001-metadata-flush-cost/spec.md create mode 100644 specs/001-metadata-flush-cost/tasks.md create mode 100644 tests/SharpCoreDB.Tests/DatabaseConfigDefaultsTests.cs create mode 100644 tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 23efc592..a7b03417 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 > New entries start here, above `[2.2.0]`. +### Changed + +- **`Database.Flush()` no longer re-serializes every table's metadata on a data-only flush (issue #532).** `Flush()` used to call `SaveMetadata()` unconditionally, so any caller that flushed per operation (a durable queue write, a log append, a move or a delete) paid a full `TableMetadataDto` build + JSON serialization + `meta.dat` rewrite on every row — measured by the reporter at **1,368 vs 2,271 ops/sec** (`IDatabase.Flush()` vs `ITable.Flush()`) on NTFS (~1.45 ms of metadata work per operation) and **184 vs 2,127 ops/sec** on ReFS (~24.8 ms). The fix introduces a dedicated schema-dirty signal (`_schemaDirty`) — separate from the existing `_metadataDirty`, which tracks pending **data** writes for SELECT visibility and is set by every INSERT/UPDATE/DELETE — and calls `SaveMetadata()` from `Flush()` only when the schema actually changed. The DDL path already persists the schema eagerly through `ForceSave()` (and the batch dispatcher and `Dispose` save it directly), so a data-only flush now skips the metadata work while the data flush (WAL batch buffer, tables, storage provider, storage engine) and its durability are unchanged. Pinned by `DatabaseFlushMetadataTests` (4 cases; 2 failed before the fix — `MetadataSaveCount` 1→2 on one flush and 1→21 over 20 flushes — and the reopen round-trips guard that schema and data still survive). + ## [2.2.0] - 2026-11-28 > **`2.2.0`** was cut from this line's `HEAD` on 2026-11-28. The .NET 11 dependency majors (EF Core / ASP.NET @@ -24,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **`DatabaseConfig.EnableAtRestRecordEncryption` now defaults to `true` (it defaulted to `false` up to 2.0.0.x) — documented as a behaviour *and* performance change (issue #531).** Beyond the write/scan costs already recorded (~1.11× CREATE/INSERT, one whole-file decrypt per full scan), every **point read** now decrypts the record envelope, measured at **≈1.66×** (≈40% of read throughput) on a store whose payloads the caller already seals itself, and the record key/area/timestamps are no longer plaintext in the data file. The secure default is deliberate (the constitution requires encryption at rest), so this is a documentation and expectation fix, not a flip back; `NoEncryptMode = true` remains the documented raw-speed opt-out. The property docs now also state how this interacts with `EnableBatchEncryption` (a different layer — it makes the bulk write cheaper but does not remove the point-read cost) and record the flip so an upgrade is not mistaken for a regression. - **Unquoted values in `UPDATE … SET` and `INSERT … VALUES` are now evaluated as expressions, the way SQLite evaluates them (option 2 of issue #525).** An `INSERT … VALUES (…, 2 * 3, …)` into a `TEXT` column stored the four characters `2 * 3` and into an `INTEGER` column failed with *"Invalid value '2 * 3'"*; a function call such as `upper('abc')` was stored as its own text. Both lists now evaluate a value that parses as an expression — constant arithmetic, a function of literals, a comparison — while a bare word that names no column (`SET status = active`) keeps the lenient literal reading, which is where SQLite itself raises *"no such column"*. One deliberate exception is kept: an unquoted date in a `DATETIME` column stays a date, because a typed column cannot hold the integer `2008` that SQLite's `2024-01-15` arithmetic would store. The `ExecuteBatchSQL` INSERT fast path reads through a second parser (`PreparedInsertStatement.ParseValuesToArray`) and follows the same rule, so a batched insert and a plain one agree. Pinned by `ValuesExpressionSqliteCompatTests` (20 cases; 10 failed before) and a **511-case differential matrix** (`ValuesExpressionMatrixTests`) that asserts every expression stores exactly what its equivalent literal stores — across integer/bigint/real/decimal/text/boolean columns × columnar/page-based/single-file storage × INSERT/UPDATE/batch. The matrix also exposed and fixed two parse inconsistencies: `ParseInsertValues` did not track parenthesis depth, so a multi-argument call such as `substr('abcdef', 2, 3)` in a VALUES tuple was split at its own commas — it is now one value, as in SQLite; and the batch `ParseValueFast` reads a numeric boolean the way `ParseValue` does (any non-zero number is true), so the batch and single-statement INSERT paths agree. Full run before release: **4886 tests / 0 failed / 6 skipped** across all 17 test projects. - **linq2db adapter: the package depends on `Microsoft.Data.Sqlite.Core` instead of the `Microsoft.Data.Sqlite` metapackage.** linq2db's SQLite dialect only reflects over the managed Microsoft.Data.Sqlite types when it builds its provider; every command runs on a `SharpCoreDBConnection`. The metapackage also pulled in `SQLitePCLRaw.bundle_e_sqlite3` — the native SQLite library for 29 runtime identifiers (66 MB in the package cache) — into every consumer, for nothing. Verified with a clean build of the adapter's test suite on `Microsoft.Data.Sqlite.Core`: no `e_sqlite3` binary in the output, and all 91 tests pass. `Directory.Packages.props` gains a `Microsoft.Data.Sqlite.Core` entry at the same 10.0.14 as `Microsoft.Data.Sqlite`. - **linq2db adapter: cancellation always surfaces as `OperationCanceledException`.** The adapter's error contract is now written down and uniform: methods returning `Option`/`Seq` throw on a failure, methods returning `Fin` capture it as `Fail`, and cancellation throws whether the token was cancelled before the call or during it. Up to 2.1.4 every `Fin` method caught everything, so a token cancelled before the call threw but one cancelled during the call came back as a `Fail`. The seven copies of that try/catch are now one helper. diff --git a/specs/001-metadata-flush-cost/plan.md b/specs/001-metadata-flush-cost/plan.md new file mode 100644 index 00000000..346ba32a --- /dev/null +++ b/specs/001-metadata-flush-cost/plan.md @@ -0,0 +1,110 @@ +# Implementation Plan: Metadata flush cost + at-rest encryption default documentation + +**Branch**: `[001-metadata-flush-cost]` | **Date**: 2026-11-29 | **Spec**: `specs/001-metadata-flush-cost/spec.md` + +**Input**: Feature specification from `/specs/001-metadata-flush-cost/spec.md` + +## Summary + +Issue #532 is an engine defect: `Database.Flush()` calls `SaveMetadata()` unconditionally, so a +data-only flush re-serializes every table's `TableMetadataDto` and rewrites `meta.dat`. The fix +introduces a schema-dirty signal (`_schemaDirty`) — distinct from the existing data-dirty flag +(`_metadataDirty`, set by INSERT/UPDATE/DELETE for SELECT visibility) — and gates the `SaveMetadata()` +call in `Flush()` on it. The data flush itself (WAL batch buffer, tables, storage provider, storage +engine) is untouched, so durability is preserved. Issue #531 is a documentation fix (changelog + +property XML doc) and a security-posture pin test; #171 is dispositioned out of scope (the graphical +UI belongs to `MPCoreDeveloper/SCDMS`). + +## Technical Context + +**Language/Version**: C# 15 preview / `net11.0` (SDK `11.0.100` pinned in `global.json`) + +**Primary Dependencies**: `System.Text.Json` (source-generated resolver), Microsoft.Testing.Platform (xunit.v3) + +**Storage**: directory mode (`meta.dat` via `IStorage.Write`) and single-file mode (`sys:metadata` block) + +**Testing**: `Microsoft.Testing.Platform` executable, `xunit.v3`; run +`tests/SharpCoreDB.Tests/bin/Release/net11.0/SharpCoreDB.Tests.exe -filterVSTest 'FullyQualifiedName~…'` + +**Target Platform**: Windows / Linux / macOS, embedded engine + +**Project Type**: library (engine + providers) + +**Constraints**: no encryption weakening, no durability trade (constitution §I); `dotnet test` does not work here — use the MTP exe. + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +- **I. Security and Durability Non-Negotiable** — PASS. The fix only removes a redundant metadata + serialization; the data flush and WAL/storage-engine durability are unchanged (guarded by + `Flush_DataOnlyChange_KeepsDataDurableOnReopen`). No encryption touched; #531's secure default stays + `true` and is pinned. +- **II. SQLite Compatibility** — PASS. No SQL surface changes. +- **III. Measured Performance, Reported Honestly** — PASS. The mechanism is pinned by a red→green + test (`MetadataSaveCount`) rather than an inferred ratio; the reporter's absolute numbers are cited + as the reporter's, not re-derived here. +- **IV. Verified Quality (red→green, green canaries)** — PASS. New tests are named + `MethodName_StateUnderTest_ExpectedBehavior`, use `xunit.v3`, and were proven red before the fix + (2 of 4 cases failed: count 1 vs 2 and 1 vs 21) then green after. +- **V. Optional, Modular Capability** — PASS. No new public API; `MetadataSaveCount` is `internal`. + +No violations — Complexity Tracking is empty. + +## Project Structure + +### Documentation (this feature) + +```text +specs/001-metadata-flush-cost/ +├── spec.md # this feature's specification +├── plan.md # this file +└── tasks.md # task breakdown +``` + +### Source Code (repository root) + +```text +src/SharpCoreDB/ +├── Database/Core/Database.Core.cs # _schemaDirty, MetadataSaveCount, Flush() gate, SaveMetadata() clear +├── Database/Execution/Database.Execution.cs # _schemaDirty = true in the 4 DDL branches +├── Database/Execution/Database.Batch.cs # _schemaDirty = true in the batch schema branch +└── DatabaseConfig.cs # EnableAtRestRecordEncryption doc: flip + point-read cost + batch interaction + +tests/SharpCoreDB.Tests/ +├── DatabaseFlushMetadataTests.cs # #532 red→green regression tests (4 cases) +└── DatabaseConfigDefaultsTests.cs # #531 security-posture pin (2 cases) + +docs/CHANGELOG.md # 2.2.0 Changed entry for the encryption default flip +``` + +**Structure Decision**: single project (the engine and its test project). The fix is confined to the +`Database` partial class and two of its partials; no new files under `src/`. Tests live in the +existing `tests/SharpCoreDB.Tests` project. + +## Phase 0 — Research (resolved during investigation) + +- **`_metadataDirty` is data-dirty, not schema-dirty.** It is set to `true` by every DML path + (`ExecuteSQL` else-branches, `UpdateByPrimaryKey`, `DeleteByPrimaryKey`, `FinishClassifiedBatch`) + and consumed by the SELECT-visibility flush. The issue's suggested fix ("consult `_metadataDirty`") + would therefore not work — a data-only INSERT sets it. Hence the dedicated `_schemaDirty` flag. +- **DDL is already persisted eagerly.** `IsSchemaChangingCommand` → `ForceSave()` → `SaveMetadata()`; + the batch dispatcher calls `SaveMetadata()` directly for schema-changing batches; `Dispose` and + `Load` migration also save. So `Flush()` never needs to save metadata; `_schemaDirty` is a + defensive gate. +- **Auto-increment counters are re-derived on reopen** (`InitializeAutoIncrementCountersFromData`), + so a skipped data-only metadata save cannot lose them. + +## Phase 1 — Design + +- Add `private bool _schemaDirty;` and `internal int MetadataSaveCount { get; private set; }` to + `Database` (`Database.Core.cs`). +- `SaveMetadata()` increments `MetadataSaveCount` and clears both `_metadataDirty` and `_schemaDirty`. +- `Flush()` replaces the unconditional `SaveMetadata();` with `if (_schemaDirty) { SaveMetadata(); }`. +- Set `_schemaDirty = true` before `ForceSave()` in the four `ExecuteSQL` DDL branches and before the + batch dispatcher's `SaveMetadata()`. +- Document the #531 flip on the property and in the changelog; add the pin tests. + +## Complexity Tracking + +*(No constitution violations — empty.)* diff --git a/specs/001-metadata-flush-cost/spec.md b/specs/001-metadata-flush-cost/spec.md new file mode 100644 index 00000000..c0396733 --- /dev/null +++ b/specs/001-metadata-flush-cost/spec.md @@ -0,0 +1,109 @@ +# Feature Specification: Metadata flush cost + at-rest encryption default documentation + +**Feature Branch**: `[001-metadata-flush-cost]` + +**Created**: 2026-11-29 + +**Status**: Implemented (spec-kit plan produced and applied in the same session) + +**Input**: Issues #532, #531 and #171 from MPCoreDeveloper/SharpCoreDB. Issue #532 is the primary +engineering work (an engine performance defect with a red→green regression test); #531 is a +documentation/expectation fix plus a security-posture pin; #171 is dispositioned as out of scope for +this repository. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Data-only flush must not rewrite schema metadata (Priority: P1) + +A caller that uses `IDatabase.Flush()` as a per-row durability barrier (a durable queue write, a log +append, a move or a delete) must not pay a full schema serialization + `meta.dat` rewrite on every +row. Today `Flush()` calls `SaveMetadata()` unconditionally, so a data-only flush re-serializes every +table's `TableMetadataDto` and rewrites `meta.dat` — ~1.45 ms of metadata work per operation on NTFS +and ~24.8 ms on ReFS (issue #532, measured by the reporter against the ServiceMq provider). + +**Why this priority**: it is the only engine-behaviour change in this spec and it directly costs +throughput on a real, shipped consumer path. + +**Independent Test**: In directory mode, capture `Database.MetadataSaveCount` after `CREATE TABLE`, +then `INSERT` + `db.Flush()`; the counter must not advance. Repeat 20× and it still must not advance. +A reopen round-trip must still find the table and its rows. + +**Acceptance Scenarios**: + +1. **Given** a table whose schema is already persisted, **When** the caller inserts data and calls `db.Flush()`, **Then** `SaveMetadata()` is not invoked and `meta.dat` is not rewritten. +2. **Given** a caller that flushes per row across 20 inserts, **When** each insert is followed by `db.Flush()`, **Then** the schema is serialized exactly as often as it changed (not once per row). +3. **Given** a schema change, **When** a `CREATE`/`DROP`/`ALTER` statement runs, **Then** the metadata is persisted eagerly and the table survives a reopen. +4. **Given** rows written through data-only flushes, **When** the database is reopened, **Then** every row is present (durability unchanged). + +--- + +### User Story 2 - Document the 2.2.0 at-rest-record-encryption default flip (Priority: P2) + +Consumers upgrading from 2.0.0.3 (where `EnableAtRestRecordEncryption` defaulted to `false`) to 2.2.0 +(where it defaults to `true`) see a ~40% point-read regression with no obvious cause. The default is +the posture the constitution requires (Principle I), so the fix is documentation and expectation +management, not flipping it back. + +**Why this priority**: it does not change behaviour but prevents a documented, secure default from +being misread as a regression — and pins it so an accidental flip-back is a failing build. + +**Independent Test**: `new DatabaseConfig()` and `DatabaseConfig.Default` must have +`EnableAtRestRecordEncryption == true` and `NoEncryptMode == false`; the raw-speed opt-out is still +available. The `docs/CHANGELOG.md` 2.2.0 section and the property XML doc must state the flip and +its point-read cost. + +**Acceptance Scenarios**: + +1. **Given** a fresh `DatabaseConfig`, **When** its defaults are read, **Then** per-record at-rest encryption is on and `NoEncryptMode` is off. +2. **Given** the 2.2.0 changelog and the property docs, **When** a consumer reads them, **Then** both record the default flip, the ~40% point-read cost, and the `EnableBatchEncryption` interaction. + +--- + +### User Story 3 - Dispose of the samples/CLI-GUI-tool request (Priority: P3) + +Issue #171 asks for more examples, C# code samples and a CLI/GUI database tool. The graphical UI +lives in the standalone `MPCoreDeveloper/SCDMS` repository (constitution Principle V: it MUST NOT be +re-added here). This spec dispositions #171 rather than implementing it. + +**Why this priority**: it is a roadmap/enhancement request, not a defect, and its tool half is out of +scope for this repository. + +**Acceptance Scenarios**: + +1. **Given** issue #171, **When** this feature is reviewed, **Then** it is explicitly marked out of scope for SharpCoreDB and pointed at `MPCoreDeveloper/SCDMS`. + +--- + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: `Database.Flush()` MUST continue to flush all pending data (WAL batch buffer, tables, storage provider, storage engine) — data-durability semantics MUST NOT change. +- **FR-002**: `Database.Flush()` MUST NOT serialize table metadata / rewrite `meta.dat` when only data changed since the last save. +- **FR-003**: `Database.Flush()` MUST persist metadata when a schema change is pending (defensive gate; the DDL path already persists eagerly). +- **FR-004**: Schema changes (`CREATE`/`DROP`/`ALTER`/`CREATE INDEX`) MUST be persisted on the DDL path (`ForceSave`) and by the batch dispatcher, so a reopen finds the schema. +- **FR-005**: `DatabaseConfig.EnableAtRestRecordEncryption` MUST default to `true` and `DatabaseConfig.NoEncryptMode` to `false`; flipping either requires an explicit owner decision (constitution Principle I). +- **FR-006**: The `docs/CHANGELOG.md` 2.2.0 section and the `EnableAtRestRecordEncryption` XML doc MUST record the default flip, the ~40% point-read cost and the `EnableBatchEncryption` interaction. +- **FR-007**: Issue #171 MUST be dispositioned as out of scope for this repository (graphical UI belongs to `MPCoreDeveloper/SCDMS`). + +### Key Entities + +- **Schema-dirty signal** (`_schemaDirty`): true when the table/column/constraint set changed since the last `SaveMetadata()`. Distinct from the existing data-dirty flag (`_metadataDirty`), which is set by INSERT/UPDATE/DELETE for SELECT visibility. +- **Metadata save counter** (`MetadataSaveCount`): internal diagnostic that counts `SaveMetadata()` invocations; the deterministic observation point for the #532 regression test. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: A data-only `db.Flush()` performs **zero** additional `SaveMetadata()` calls (red→green test, `DatabaseFlushMetadataTests`). +- **SC-002**: After 20 insert+flush cycles the metadata save count equals the count immediately after `CREATE TABLE` (no per-row re-serialization). +- **SC-003**: A table created and flushed is found after a reopen, and rows written through data-only flushes are all present after a reopen. +- **SC-004**: `new DatabaseConfig().EnableAtRestRecordEncryption` is `true` and `NoEncryptMode` is `false`, pinned by `DatabaseConfigDefaultsTests`. +- **SC-005**: The regression canaries (`ReopenRoundTripMatrixTests`, `SingleFileDirectoryParityTests`, `WritePathProfilerTests`, `FixedWidth*`, `FormatCompatPolicyTests`) stay green. + +## Assumptions + +- The reporter's ServiceMq harness measured against the prior build; this session reproduces the mechanism with an in-repository red→green test rather than the external harness. Re-running the reporter's harness against a fixed build is a follow-up for issue #532's close (per `.clinerules/30-issue-closure.md`). +- Directory mode is the storage path whose `SaveMetadata()` writes `meta.dat`; single-file mode writes the `sys:metadata` block and is gated the same way (the fix is storage-agnostic). +- Auto-increment counters persisted in the DTO are re-derived from data on reopen (`InitializeAutoIncrementCountersFromData`), so skipping a data-only metadata save is not a correctness risk; `Flush_DataOnlyChange_KeepsDataDurableOnReopen` guards the data path. + diff --git a/specs/001-metadata-flush-cost/tasks.md b/specs/001-metadata-flush-cost/tasks.md new file mode 100644 index 00000000..81cbad7d --- /dev/null +++ b/specs/001-metadata-flush-cost/tasks.md @@ -0,0 +1,79 @@ +# Tasks: Metadata flush cost + at-rest encryption default documentation + +**Input**: Design documents from `/specs/001-metadata-flush-cost/` + +**Prerequisites**: `plan.md` (required), `spec.md` (required for user stories) + +**Tests**: This feature explicitly requests regression tests (owner directive: prevent regression), so +test tasks are included and were written first, proven red, then made green. + +**Organization**: Tasks are grouped by user story. `[P]` = parallelizable; `[USn]` = user story. + +## Phase 1: Setup + +- [x] T001 Confirm the defects against master: `Flush()` calls `SaveMetadata()` unconditionally; `_metadataDirty` is set by DML, not only DDL. + +## Phase 2: Foundational + +- [x] T002 Add `internal int MetadataSaveCount { get; private set; }` to `Database` and increment it at the top of `SaveMetadata()` (`src/SharpCoreDB/Database/Core/Database.Core.cs`) — the deterministic observation point. +- [x] T003 [P] Add `private bool _schemaDirty;` (schema-dirty signal) next to `_metadataDirty`, with an XML doc explaining the data-dirty vs schema-dirty split. + +## Phase 3: User Story 1 — data-only flush must not rewrite metadata (P1) 🎯 MVP + +**Goal**: `Flush()` serializes the schema only when it changed; durability unchanged. + +**Independent Test**: `DatabaseFlushMetadataTests` (4 cases). + +### Tests for User Story 1 (written first, proven red) ⚠️ + +- [x] T004 [P] [US1] `Flush_DataOnlyChange_DoesNotRewriteMetadata` — `MetadataSaveCount` unchanged after an insert+flush (`tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs`). +- [x] T005 [P] [US1] `Flush_RepeatedDataOnlyFlushes_DoNotRepeatedlySerializeSchema` — 20 insert+flush cycles do not advance the count. +- [x] T006 [P] [US1] `Flush_SchemaChange_StillPersistsMetadataOnReopen` — a created+flushed table survives a reopen. +- [x] T007 [P] [US1] `Flush_DataOnlyChange_KeepsDataDurableOnReopen` — rows written through data-only flushes survive a reopen. +- [x] T008 [US1] Prove red: build the test project and run `-filterVSTest 'FullyQualifiedName~DatabaseFlushMetadataTests'`. Recorded: 2 failed (`Expected 1, Actual 2` and `Expected 1, Actual 21`), 2 passed. + +### Implementation for User Story 1 + +- [x] T009 [US1] Gate the `SaveMetadata()` call in `Flush()` on `_schemaDirty` and clear `_schemaDirty` in `SaveMetadata()` (`Database.Core.cs`). +- [x] T010 [US1] Set `_schemaDirty = true` before `ForceSave()` in the four `ExecuteSQL` schema branches (`Database.Execution.cs`). +- [x] T011 [P] [US1] Set `_schemaDirty = true` before the batch dispatcher's `SaveMetadata()` (`Database.Batch.cs`). +- [x] T012 [US1] Prove green: rebuild and re-run `DatabaseFlushMetadataTests` — `Total: 4, Failed: 0`. + +**Checkpoint**: #532 mechanism fixed and pinned. + +--- + +## Phase 4: User Story 2 — document the 2.2.0 default flip + pin the posture (P2) + +**Goal**: the at-rest encryption default flip is documented and cannot silently flip back. + +**Independent Test**: `DatabaseConfigDefaultsTests` (2 cases). + +- [x] T013 [P] [US2] Add to the `EnableAtRestRecordEncryption` XML doc: the 2.2.0 flip, the ~40% (~1.66×) point-read cost, and the `EnableBatchEncryption` interaction (`src/SharpCoreDB/DatabaseConfig.cs`). +- [x] T014 [P] [US2] Add a `[2.2.0] → Changed` changelog entry for the flip (`docs/CHANGELOG.md`). +- [x] T015 [P] [US2] `DatabaseConfig_Default_EncryptsPerRecordAtRest` + `DatabaseConfig_DefaultPreset_EncryptsPerRecordAtRest` (`tests/SharpCoreDB.Tests/DatabaseConfigDefaultsTests.cs`). + +--- + +## Phase 5: User Story 3 — disposition #171 (P3) + +- [x] T016 [US3] Record #171 as out of scope for this repository (graphical UI belongs to `MPCoreDeveloper/SCDMS`); no code. (Tracked in `spec.md` US3.) + +--- + +## Phase 6: Polish & Cross-Cutting + +- [x] T017 Build the test project: `dotnet build tests/SharpCoreDB.Tests/SharpCoreDB.Tests.csproj -c Release -f net11.0` — 0 errors. +- [x] T018 Run the wider core suite (CATEGORY filter excludes Debug/Manual/Performance) plus the canaries to confirm no regression. +- [ ] T019 Post the #532 close comment with the red→green evidence; keep #532 open until the reporter's ServiceMq harness is re-run against the fixed build (`.clinerules/30-issue-closure.md`). + +## Dependencies & Execution Order + +- Setup (T001) → Foundational (T002–T003) → US1 tests (T004–T008, red) → US1 fix (T009–T011) → US1 green (T012). +- US2 (T013–T015) is independent of US1 and can run in parallel. +- Polish (T017–T019) last. T018 (wider suite) gates the claim of "no regression". + +## Implementation Strategy + +MVP = US1 fixed and pinned (T001–T012). US2 is documentation + a canary. US3 is a disposition. The +wider-suite run (T018) and the reporter-harness re-run (T019) are the remaining closure gates. diff --git a/src/SharpCoreDB/Database/Core/Database.Core.cs b/src/SharpCoreDB/Database/Core/Database.Core.cs index 34f03cd5..ac567205 100644 --- a/src/SharpCoreDB/Database/Core/Database.Core.cs +++ b/src/SharpCoreDB/Database/Core/Database.Core.cs @@ -91,6 +91,28 @@ public partial class Database : IDatabase, IDisposable, IAsyncDisposable // Track if metadata needs to be flush private bool _metadataDirty; + /// + /// Diagnostic counter: how many times has serialized and written the + /// schema on this instance. Visible to the test assembly (SharpCoreDB.Tests via + /// InternalsVisibleTo) so DatabaseFlushMetadataTests can prove that a data-only + /// does not rewrite the schema (issue #532). Not part of the public API. + /// + internal int MetadataSaveCount { get; private set; } + + /// + /// True when the schema (table/column/constraint set) changed since the last + /// persisted it. This is deliberately separate from + /// : the latter tracks pending data writes (set by INSERT/UPDATE/ + /// DELETE and consumed by the SELECT-visibility flush), whereas this flag tracks schema + /// changes only. consults it so a data-only flush no longer re-serializes every + /// table's metadata (issue #532) — the schema is persisted eagerly on the DDL path by + /// and by the batch dispatcher, so this flag is normally already clear by + /// the time a data-only flush runs. It remains the source of truth for + /// 's dirty gate and a safety net for any future schema path that defers + /// the save. + /// + private bool _schemaDirty; + // ✅ 1.9.5: ULID encoding generation of this database. // true = created by 1.9.5+ (or already migrated) → ULIDs are spec-compliant. // false = created before 1.9.5 → may contain legacy-encoded ULIDs, see MigrateLegacyUlids(). @@ -552,6 +574,8 @@ config is { } fixedWidthConfig && /// private void SaveMetadata() { + MetadataSaveCount++; + // v2 (AOT readiness): strongly-typed DTO preserves the legacy anonymous-type JSON shape. var tablesList = tables.Values.OfType().Select(t => new TableMetadataDto { @@ -620,6 +644,7 @@ private void SaveMetadata() } _metadataDirty = false; + _schemaDirty = false; } /// @@ -793,7 +818,17 @@ public void Flush() storageEngine.Flush(); } - SaveMetadata(); + // Issue #532: only serialize the schema when it actually changed. A data-only flush used to + // call SaveMetadata() unconditionally, paying a full TableMetadataDto build + JSON + // serialization + meta.dat rewrite on every per-row durability barrier (~1.45 ms/op NTFS, + // ~25 ms/op ReFS). The DDL path persists the schema eagerly through ForceSave(), so + // _schemaDirty is clear here on a data-only flush and this branch is skipped. The data + // flush above (WAL batch buffer, tables, storage provider, storage engine) is unchanged, so + // durability is untouched. + if (_schemaDirty) + { + SaveMetadata(); + } _metadataDirty = false; } catch (Exception ex) diff --git a/src/SharpCoreDB/Database/Execution/Database.Batch.cs b/src/SharpCoreDB/Database/Execution/Database.Batch.cs index 1a0f044c..1a1f10b5 100644 --- a/src/SharpCoreDB/Database/Execution/Database.Batch.cs +++ b/src/SharpCoreDB/Database/Execution/Database.Batch.cs @@ -1656,6 +1656,7 @@ private void ExecuteClassifiedBatch(BatchClassification batch, string[] statemen if (!isReadOnly && statements.Any(IsSchemaChangingCommand)) { + _schemaDirty = true; SaveMetadata(); } } diff --git a/src/SharpCoreDB/Database/Execution/Database.Execution.cs b/src/SharpCoreDB/Database/Execution/Database.Execution.cs index 4b52c430..0693c1bd 100644 --- a/src/SharpCoreDB/Database/Execution/Database.Execution.cs +++ b/src/SharpCoreDB/Database/Execution/Database.Execution.cs @@ -164,6 +164,7 @@ public void ExecuteSQL(string sql) if (!isReadOnly && IsSchemaChangingCommand(sql)) { + _schemaDirty = true; ForceSave(); ApplyColumnarCompactionThresholdToTables(); } @@ -228,6 +229,7 @@ public void ExecuteSQL(string sql, Dictionary parameters) if (!isReadOnly && IsSchemaChangingCommand(sql)) { + _schemaDirty = true; ForceSave(); ApplyColumnarCompactionThresholdToTables(); } @@ -311,6 +313,7 @@ public async Task ExecuteSQLAsync(string sql, CancellationToken cancellationToke if (!isReadOnly && IsSchemaChangingCommand(sql)) { + _schemaDirty = true; ForceSave(); ApplyColumnarCompactionThresholdToTables(); } @@ -373,6 +376,7 @@ public async Task ExecuteSQLAsync(string sql, Dictionary parame if (!isReadOnly && IsSchemaChangingCommand(sql)) { + _schemaDirty = true; ForceSave(); ApplyColumnarCompactionThresholdToTables(); } diff --git a/src/SharpCoreDB/DatabaseConfig.cs b/src/SharpCoreDB/DatabaseConfig.cs index fa222599..1b832638 100644 --- a/src/SharpCoreDB/DatabaseConfig.cs +++ b/src/SharpCoreDB/DatabaseConfig.cs @@ -100,6 +100,23 @@ public class DatabaseConfig /// docs/performance/INSERT_UPDATE_PERFORMANCE_PLAN.md §3-1c and §3-1d. /// /// + /// Behaviour change in 2.2.0 (issue #531): this property defaulted to + /// up to 2.0.0.x and defaults to on the 2.2.0 line. Beyond the write/scan + /// costs above, consumers upgrading from 2.0.0.x see a point-read cost: every point read + /// decrypts the record envelope, measured at ≈1.66× (≈40% of read throughput) on a store + /// whose payloads the caller already seals itself. The secure default is deliberate (the + /// constitution requires encryption at rest), so this is documented rather than flipped back; it is + /// recorded here and in docs/CHANGELOG.md so an upgrade is not mistaken for a regression. + /// + /// + /// Interaction with : the two are different layers. + /// batches the encryption of rows during a bulk write (fewer + /// cipher calls on a large insert) but still ends with the same encrypted record format. This + /// property is the per-record at-rest posture — what the data file holds on disk, read back + /// one record at a time. Turning batch encryption on does not remove the per-record point-read + /// decryption cost described above; it only makes the bulk write cheaper. + /// + /// /// ⚠️ FORMAT: a file is encrypted only when it was CREATED with this option on. A pre-existing /// plaintext database stays byte-for-byte readable and is never mixed with encrypted records — but /// its tables are upgraded to the encrypted format when they are compacted, because compaction diff --git a/tests/SharpCoreDB.Tests/DatabaseConfigDefaultsTests.cs b/tests/SharpCoreDB.Tests/DatabaseConfigDefaultsTests.cs new file mode 100644 index 00000000..4c55f844 --- /dev/null +++ b/tests/SharpCoreDB.Tests/DatabaseConfigDefaultsTests.cs @@ -0,0 +1,44 @@ +// +// 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 Xunit; + +/// +/// Pins the security-posture defaults for issue #531. EnableAtRestRecordEncryption flipped +/// from false (2.0.0.x) to true (2.2.0), and the constitution (Principle I) requires +/// encryption at rest by default. This test makes an accidental flip back a failing build rather than +/// a silent regression of the posture; flipping it requires an explicit owner decision, not a code +/// edit. The ~40% point-read cost of the default is documented on the property and in the 2.2.0 +/// changelog. +/// +public sealed class DatabaseConfigDefaultsTests +{ + /// + /// A freshly constructed config MUST encrypt per-record data at rest and MUST NOT be in raw + /// (NoEncryptMode) mode. + /// + [Fact] + public void DatabaseConfig_Default_EncryptsPerRecordAtRest() + { + var config = new DatabaseConfig(); + + Assert.True(config.EnableAtRestRecordEncryption); + Assert.False(config.NoEncryptMode); + } + + /// + /// is the documented product default; it must carry the same + /// encrypted-at-rest posture. + /// + [Fact] + public void DatabaseConfig_DefaultPreset_EncryptsPerRecordAtRest() + { + var config = DatabaseConfig.Default; + + Assert.True(config.EnableAtRestRecordEncryption); + Assert.False(config.NoEncryptMode); + } +} diff --git a/tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs b/tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs new file mode 100644 index 00000000..ffe74fcd --- /dev/null +++ b/tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs @@ -0,0 +1,142 @@ +// +// 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 Microsoft.Extensions.DependencyInjection; +using SharpCoreDB.Interfaces; +using Xunit; + +/// +/// Regression tests for issue #532: rewrote ALL table metadata on +/// every call, even when only data changed, so a caller that flushed per row paid a full schema +/// serialization plus a meta.dat rewrite per operation (~1.45 ms/op on NTFS, ~25 ms/op on +/// ReFS). The fix gates SaveMetadata() on a schema-dirty signal, so a data-only flush no +/// longer serializes the schema while the data-durability guarantees are untouched. +/// +/// The tests observe Database.MetadataSaveCount (an internal diagnostic counter incremented +/// exactly once per SaveMetadata() call) and the reopen round-trip, so they pin both the +/// performance contract (no metadata rewrite on a data-only flush) and correctness (schema changes +/// still persist, data stays durable across a reopen). +/// +/// +public sealed class DatabaseFlushMetadataTests : IDisposable +{ + private readonly DatabaseFactory _factory; + private readonly string _dbPath; + + public DatabaseFlushMetadataTests() + { + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + _factory = services.BuildServiceProvider().GetRequiredService(); + // A directory path (no .scdb extension) selects directory storage, whose SaveMetadata() + // writes the meta.dat file this issue is about. + _dbPath = Path.Combine(Path.GetTempPath(), $"SCDB_FlushMeta_{Guid.NewGuid():N}"); + } + + private Database Open() => (Database)_factory.Create(_dbPath, "pwd"); + + /// + /// A data-only flush must not serialize the schema again. This is the defect itself: the old + /// implementation called SaveMetadata() unconditionally at the end of Flush(). + /// + [Fact] + public void Flush_DataOnlyChange_DoesNotRewriteMetadata() + { + using var db = Open(); + db.ExecuteSQL("CREATE TABLE t (id INTEGER, name TEXT)"); + + var afterSchema = db.MetadataSaveCount; // CREATE TABLE -> ForceSave() -> SaveMetadata() already ran + + db.ExecuteSQL("INSERT INTO t (id, name) VALUES (1, 'a')"); + db.Flush(); + + Assert.Equal(afterSchema, db.MetadataSaveCount); + } + + /// + /// Repeated data-only flushes (the per-row durability pattern the reporter measured) must not + /// each re-serialize the schema. + /// + [Fact] + public void Flush_RepeatedDataOnlyFlushes_DoNotRepeatedlySerializeSchema() + { + using var db = Open(); + db.ExecuteSQL("CREATE TABLE t (id INTEGER, name TEXT)"); + + var afterSchema = db.MetadataSaveCount; + + for (var i = 0; i < 20; i++) + { + db.ExecuteSQL($"INSERT INTO t (id, name) VALUES ({i}, 'n{i}')"); + db.Flush(); + } + + Assert.Equal(afterSchema, db.MetadataSaveCount); + } + + /// + /// The fix must not weaken schema persistence: a table created, then flushed, must exist after a + /// reopen (its metadata reaches disk through the DDL path, not through Flush()). + /// + [Fact] + public void Flush_SchemaChange_StillPersistsMetadataOnReopen() + { + using (var db = Open()) + { + db.ExecuteSQL("CREATE TABLE t (id INTEGER, name TEXT)"); + db.ExecuteSQL("INSERT INTO t (id, name) VALUES (1, 'a')"); + db.Flush(); + } + + using (var db = Open()) + { + var rows = db.ExecuteQuery("SELECT id FROM t"); + Assert.Single(rows); + } + } + + /// + /// The fix must not weaken data durability: rows written through data-only flushes must survive a + /// reopen. (The reporter verified this independently with Process.Kill; this test uses the + /// graceful dispose path.) + /// + [Fact] + public void Flush_DataOnlyChange_KeepsDataDurableOnReopen() + { + using (var db = Open()) + { + db.ExecuteSQL("CREATE TABLE t (id INTEGER, name TEXT)"); + for (var i = 0; i < 5; i++) + { + db.ExecuteSQL($"INSERT INTO t (id, name) VALUES ({i}, 'n{i}')"); + db.Flush(); + } + } + + using (var db = Open()) + { + var rows = db.ExecuteQuery("SELECT id FROM t"); + Assert.Equal(5, rows.Count); + } + } + + public void Dispose() + { + try + { + if (Directory.Exists(_dbPath)) + { + Directory.Delete(_dbPath, true); + } + } + catch + { + // best-effort cleanup + } + } +} From 7329932e429c9a3c32644daf54eee60d5495980d Mon Sep 17 00:00:00 2001 From: MPCoreDeveloper Date: Sun, 29 Nov 2026 13:00:48 +0100 Subject: [PATCH 2/2] bench: add --flush-per-row A/B for the #532 durability-barrier fix The comparative harness flushes once per batch/phase, so it never exercises the per-row IDatabase.Flush() pattern issue #532 is about. Add a focused --flush-per-row mode: N single-row ITable.Insert writes, each followed by either IDatabase.Flush() or ITable.Flush(), interleaved and reported as a median on the same table and machine. Measured (AppendOnly, at-rest records on, 5,000 rows/arm, 2 reps): before the fix: IDatabase.Flush 3,109 ops/s vs ITable.Flush 5,063 ops/s (1.63x gap) after the fix: IDatabase.Flush 5,301 ops/s vs ITable.Flush 5,281 ops/s (1.00x gap) Refs #532. --- .../Program.cs | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs b/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs index a33da7b0..31a04cc0 100644 --- a/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs +++ b/tests/benchmarks/SharpCoreDB.Benchmarks.Comparative/Program.cs @@ -221,6 +221,18 @@ static async Task Main(string[] args) return; } + // Optional: --flush-per-row → the #532 durability-barrier A/B. Writes N single rows through + // ITable.Insert and flushes after each, once with IDatabase.Flush() (the "make it durable" call + // that used to re-serialize every table's metadata) and once with ITable.Flush() (the table-only + // flush that never did). On the fixed build the two converge; before the fix IDatabase.Flush() + // paid a full schema serialization + meta.dat rewrite per row (the reporter measured 1,368 vs + // 2,271 ops/sec on NTFS, ~1.45 ms of metadata work per operation). + if (args.Any(a => a.Equals("--flush-per-row", StringComparison.OrdinalIgnoreCase))) + { + RunFlushPerRowBenchmark(ParseEngineType(args)); + return; + } + // Optional: --inserttest → focused SQL-vs-Direct insert micro-benchmark (median of N runs). if (args.Any(a => a.Equals("--inserttest", StringComparison.OrdinalIgnoreCase))) { @@ -1517,6 +1529,109 @@ static DatabaseConfig BuildConfig( }; } + /// + /// The #532 durability-barrier A/B in one process: N single-row writes through + /// , each followed by + /// either IDatabase.Flush() (the "make the row durable" call that used to re-serialize + /// every table's metadata and rewrite meta.dat) or ITable.Flush() (the table-only + /// flush that never did). Same table, same inserts, same machine, interleaved and reported as a median. + /// On the fixed build the two converge; before the fix IDatabase.Flush() paid the full schema + /// serialization per row (the reporter measured 1,368 vs 2,271 ops/sec on NTFS). + /// + static void RunFlushPerRowBenchmark(SharpCoreDB.Interfaces.StorageEngineType engineType) + { + const int rows = 5_000; + const int reps = 2; + + var services = new ServiceCollection(); + services.AddSharpCoreDB(); + var sp = services.BuildServiceProvider(); + var factory = sp.GetRequiredService(); + var config = BuildConfig(engineType); + var dbPath = Path.Combine(BenchTempDirectory(), $"scdb-flush-per-row-{Guid.NewGuid()}"); + + Console.WriteLine($"FLUSH-PER-ROW (#532) — engine={engineType}, rows={rows:N0}/arm, reps={reps}, " + + $"at-rest records={config.EnableAtRestRecordEncryption}"); + + using var db = (SharpCoreDB.Database)factory.Create( + dbPath: dbPath, + masterPassword: BenchDbPassword, + isReadOnly: false, + config: config); + + try + { + db.ExecuteSQL("CREATE TABLE docs (id INTEGER, name TEXT)"); + if (!db.TryGetTable("docs", out var tbl) || tbl is not SharpCoreDB.Interfaces.ITable table) + { + Console.WriteLine(" [error] table 'docs' not found"); + return; + } + + // Warmup: JIT + first-file allocation, on a throwaway range of ids. + for (var i = 0; i < 200; i++) + { + table.Insert(new Dictionary { ["id"] = -1 - i, ["name"] = "warm" }); + table.Flush(); + } + db.Flush(); + + static double RunArm(SharpCoreDB.Database db, SharpCoreDB.Interfaces.ITable table, int rows, bool databaseFlush) + { + var sw = Stopwatch.StartNew(); + for (var i = 0; i < rows; i++) + { + table.Insert(new Dictionary { ["id"] = i, ["name"] = "row" + i }); + if (databaseFlush) + { + db.Flush(); + } + else + { + table.Flush(); + } + } + sw.Stop(); + return sw.Elapsed.TotalSeconds; + } + + var dbSecs = new List(); + var tableSecs = new List(); + for (var rep = 0; rep < reps; rep++) + { + dbSecs.Add(RunArm(db, table, rows, databaseFlush: true)); + tableSecs.Add(RunArm(db, table, rows, databaseFlush: false)); + } + + static double Median(List v) + { + v.Sort(); + return v.Count % 2 == 1 ? v[v.Count / 2] : (v[v.Count / 2 - 1] + v[v.Count / 2]) / 2.0; + } + + var dbMed = Median(dbSecs); + var tableMed = Median(tableSecs); + Console.WriteLine($" IDatabase.Flush() per row : {dbMed:F2}s ({rows / dbMed:N0} ops/sec)"); + Console.WriteLine($" ITable.Flush() per row : {tableMed:F2}s ({rows / tableMed:N0} ops/sec)"); + Console.WriteLine($" database/table gap : under 1.00x the database flush is the slower one " + + $"({(dbMed / tableMed):F2}x table time)"); + } + finally + { + try + { + if (Directory.Exists(dbPath)) + { + Directory.Delete(dbPath, true); + } + } + catch + { + // best-effort cleanup + } + } + } + /// /// The product's per-record at-rest encryption default, read from a fresh /// so a benchmark arm can never drift from it. It flipped to