Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
110 changes: 110 additions & 0 deletions specs/001-metadata-flush-cost/plan.md
Original file line number Diff line number Diff line change
@@ -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.)*
109 changes: 109 additions & 0 deletions specs/001-metadata-flush-cost/spec.md
Original file line number Diff line number Diff line change
@@ -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.

Loading
Loading