Skip to content

Database.Flush() rewrites all table metadata unconditionally (SaveMetadata ignores _metadataDirty) — ~1.45 ms/op on NTFS, ~25 ms/op on ReFS #532

Done

Description

@MPCoreDeveloper

Summary

Database.Flush() writes the complete database metadata to disk on every call, even when nothing changed. Any caller that flushes per operation (a durable queue write, a log append, a move or a delete) pays a full schema serialization plus a meta.dat rewrite on every row.

Measured on a directory-mode database, 5,000 single-row durable writes, median of 3, net11.0, NTFS: 1,368 ops/sec when the caller uses IDatabase.Flush() versus 2,271 ops/sec with ITable.Flush() — about 1.45 ms of metadata work per operation. On a ReFS volume the same comparison is 184 ops/sec vs 2,127 ops/sec (~24.8 ms per operation), because a synchronous small-file overwrite is far more expensive there.

Where

src/SharpCoreDB/Database/Core/Database.Core.cs (master, checked 2026-11-29):

  • private bool _metadataDirty; — declared ~line 92, maintained by the DDL paths.
  • public void Flush() (~line 747) ends with SaveMetadata(); (~line 796) unconditionally; _metadataDirty is not consulted (it is only cleared at ~line 797).
  • private void SaveMetadata() (~line 553) builds a TableMetadataDto for every table (tables.Values.OfType<Table>()), serializes it all to JSON and writes it — _storageProvider.WriteBlockAsync("sys:metadata", …) + FlushAsync() in single-file mode, storage.Write(<db>/meta.dat, metaJson) in directory/legacy mode.

ITable.Flush() (src/SharpCoreDB/DataStructures/Table.cs) only flushes that table's storage engine, so a data-only caller can avoid this today — but nothing in the API signals that IDatabase.Flush() is orders of magnitude heavier, and IDatabase.Flush() is the natural "make it durable" call.

The behaviour predates 2.2.0 (the same SaveMetadata() call is in release/v2.0), so this is not a regression — it is a long-standing cost that becomes visible as soon as a provider flushes per row.

Impact in practice

ServiceMq's SharpCoreDB provider used IDatabase.Flush() as its row-durability barrier. Switching that one line to ITable.Flush() (no data-path change) gave, same machine, NTFS:

Operation with IDatabase.Flush() with ITable.Flush()
Write (FlushToDisk) 1,368 ops/sec 2,271 ops/sec
Append 1,301 ops/sec 2,157 ops/sec
Move 669 ops/sec 1,102 ops/sec
Delete 1,346 ops/sec 2,182 ops/sec

Durability of the ITable.Flush() path was verified independently: 100 durable rows, then Process.Kill() with no Dispose and no graceful close, then a fresh process reopening the store — 100/100 rows present.

Reproduction

  1. Directory mode: new DatabaseFactory(services).Create(path, password, false, new DatabaseConfig { AutoFixedWidthRecords = false }).
  2. Write 5,000 rows through ITable.Insert, timing two variants: table.Flush() per insert versus database.Flush() per insert.
  3. Isolate further by timing N database.Flush() calls with no writes at all — each still serializes the schema and rewrites meta.dat.

This also biases any engine benchmark that calls db.Flush() inside the timed region: the per-flush metadata save is a separate, avoidable component of "commit" cost.

Suggested fix

  • Consult _metadataDirty in Flush() and skip SaveMetadata() when no DDL changed (cheap, keeps the public contract).
  • Track a per-table schema version so SaveMetadata() re-serializes only tables whose schema actually changed; the DTO carries column arrays, constraints, collations and inline-capacity flags that DML never touches.
  • Optionally make intent explicit (FlushData() vs FlushSchema()) and/or document on IDatabase.Flush() that it persists metadata too.

Happy to re-run the ServiceMq benchmark harness against any build to confirm the numbers.

Activity

  1. MPCoreDeveloper commented on Nov 29, 2026

    @MPCoreDeveloper
    OwnerAuthor

    Surfaced during the same upgrade review; the read-side finding is tracked separately in #531 (EnableAtRestRecordEncryption default flip). The numbers in this issue were measured with the ServiceMq provider after switching its row-durability barrier from IDatabase.Flush() to ITable.Flush(), and the benchmark harness can be re-run per release if that helps verification.

  2. added
    bug
    enhancement
    priority:p1
    on Nov 29, 2026
  3. added a commit that references this issue on Nov 29, 2026
  4. MPCoreDeveloper commented on Nov 29, 2026

    @MPCoreDeveloper
    OwnerAuthor

    Fixed and verified (PR #533)

    Root cause

    Database.Flush() (src/SharpCoreDB/Database/Core/Database.Core.cs) ended with an unconditional SaveMetadata(), so a data-only flush re-serialized every TableMetadataDto and rewrote meta.dat — the cost this issue measured.

    Correction to the suggested fix

    "Consult _metadataDirty" does not work: _metadataDirty is set by every DML path (ExecuteSQL else-branches, UpdateByPrimaryKey, DeleteByPrimaryKey, FinishClassifiedBatch) — it tracks pending data for SELECT visibility, not schema. The fix adds a dedicated _schemaDirty signal (set on the DDL branches, cleared by SaveMetadata()) and gates Flush()'s SaveMetadata() on it. The data flush (WAL batch buffer, tables, storage provider, storage engine) is untouched, so durability is unchanged.

    Regression test (red → green)

    tests/SharpCoreDB.Tests/DatabaseFlushMetadataTests.cs (4 cases). Proven red before the fix — MetadataSaveCount went 1→2 on one data-only flush and 1→21 over 20 insert+flush cycles — and green after (4/4). Reopen round-trips guard that schema and data still survive.

    Benchmark — --flush-per-row A/B (same machine, interleaved median; ITable.Insert + flush per row, AppendOnly, at-rest records on, 5,000 rows/arm)

    arm before the fix after the fix
    IDatabase.Flush() per row 3,109 ops/s 5,301 ops/s (+70%)
    ITable.Flush() per row 5,063 ops/s 5,281 ops/s
    database/table gap 1.63× (matches ~1.66× in the report) 1.00×

    The durability barrier in the report is no longer the slow call. The general CRUD comparative run is unchanged by this fix — expected, because it flushes once per batch, not per row.

    Verification

    New tests 4/4; canaries + new 63/63; wider core suite (Category!=Debug/Manual/Performance) 3091 tests / 0 failed / 22 skipped; build 0 errors.

    Closed on owner directive on the in-repository fix; the external ServiceMq harness was not re-run in this session.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugenhancementinvesttigationpriority:p1

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions