Skip to content
Merged
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 @@ -46,6 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **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.

### 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 @@ -61,6 +65,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.)*
Loading
Loading