storage/db: XxHash3 record integrity, garbage-ratio compaction

Two streams of work land together: they are interleaved in storage.zig
and db.zig and only build as a unit.

Already in the working tree before this session:
  - ReleaseFast as the default zig build (Debug was 10-200x slower)
  - group commit: one fsync per write command instead of per document
  - plan_id returned a pointer to a stack temporary; ReleaseFast read
    garbage and silently broke findOne({_id: ObjectId})
  - perf suite: big.js, compare.js, compare-run.sh, e2e6.js

Phase 1 performance work:

Record integrity hash CRC32 -> XxHash3. std.hash.Crc32 is the
table-driven byte-at-a-time Crc32IsoHdlc, measured at 408 MB/s against
XxHash3's 31 GB/s: 38us versus 0.5us on a 16 KiB document, which was
about two thirds of the entire bulk-insert cost. The record header
grows from u32 crc to u64 hash (header_len 20 -> 24), a breaking
format change. Bulk insert 260 -> 700 MB/s, reopen 1.1 -> 0.5s.

Compaction fsynced once per live document, because Log.open leaves
defer_sync false and compact never set it. It now issues one sync for
the whole rewrite, before the rename that publishes it.

Compaction triggers on the share of the log that is garbage
(live_docs/dead_docs, maintained at evict_doc, the single point where
a document dies) rather than on bytes appended. A fixed byte count is
wrong in both directions: a 1 GB bulk load holds no garbage at all yet
would compact ~64 times under the 16 MiB default, rewriting 1 GB each
time, while a small collection rewritten in place accumulates garbage
indefinitely without ever reaching the count. Pure inserts now never
compact, and the file stays near 1.25x the live data. Bulk load at the
default threshold: 41.6 -> 702.7 MB/s.

remove() never called maybe_compact, so a delete-heavy workload grew
the log without bound.

e2e6's compaction check required the file to bloat past 30 MiB before
being reclaimed, which encoded the old policy and failed on strictly
better behaviour (ends at 15.8 MB against ~12 MB live, was ~30 MB). It
now asserts the file ends near the live size and peaked well above it,
which does not depend on when the trigger fires. Sampling interval 50
-> 10ms: the operations now finish inside the old window.

Verified: 70 unit tests under both ReleaseFast and ReleaseSafe, e2e
29/16/17/3/2 checks, the crash-a/kill -9/crash-b pair, and e2e6 72/72
across three consecutive runs.
This commit is contained in:
2026-08-02 18:20:40 +03:00
parent d90cde394c
commit 556ad7dc86
12 changed files with 1572 additions and 55 deletions

110
README.md
View File

@@ -11,7 +11,7 @@ driver, PyMongo — connect over TCP and just work.
zig build # build the server
zig build test # run the unit test suite
zig-out/bin/mongo-lite --port 27017 --db data.log
zig-out/bin/mongo-lite --port 27017 --db data.log --compact-threshold 256m
# in another terminal:
mongosh --port 27017
@@ -53,10 +53,11 @@ mongosh --port 27017
`$rename`, with dot-path creation (including array indices).
- **Storage**: append-only record log (CRC32-checked, `fsync` per write,
torn-tail tolerant) with in-memory indexes rebuilt on open and automatic
compaction (rewrite + atomic rename when the log grows past 16 MB).
Killed mid-write (`kill -9`), the database recovers all committed writes;
the log and compaction both work with relative or absolute `--db` paths.
Records up to the announced 16 MB `maxBsonObjectSize` replay correctly.
compaction (rewrite + atomic rename when the log grows past
`--compact-threshold`, default 16 MB). Killed mid-write (`kill -9`), the
database recovers all committed writes; the log and compaction both work
with relative or absolute `--db` paths. Records up to the announced 16 MB
`maxBsonObjectSize` replay correctly.
- **Concurrency**: a writer-preferring read/write lock splits command
execution — reads (`find`, `count`, `aggregate`, `list*`) run concurrently
across connections, writes (CRUD, DDL) are exclusive and totally ordered,
@@ -77,7 +78,7 @@ src/
query.zig filter matcher, regex engine, sort, projection
index.zig secondary indexes: entries, search, query planner
update.zig update operators with dot-path navigation
main.zig CLI: --port, --bind, --db, --ttl-sweep-secs
main.zig CLI: --port, --bind, --db, --ttl-sweep-secs, --compact-threshold
```
## Indexes
@@ -139,9 +140,100 @@ longer one.
- `collMod`, so an index's `expireAfterSeconds` cannot be changed in
place — drop the index and re-create it with the new expiry
- `dropCollection`/`dropDatabase` write no log record, so a dropped
collection (and its index definitions) resurrect on restart; and
compaction never resets `log_bytes`, so every write after the first
compaction re-triggers the threshold check
collection (and its index definitions) resurrect on restart
## Working with large collections
Everything lives in RAM (db → collection → _id → document maps) and every
write command is logged with `fsync` before it is acknowledged (one sync per
command via group commit — a 500-doc `insertMany` syncs once, not 500
times), so multi-GB collections work, with cost/behavior notes measured by
the `tests/e2e/big.js` harness (12-core/32 GB Mac):
- **Build in ReleaseFast** — `zig build` defaults to it. A Debug server is
10-200x slower on every path (the matcher alone was 70 µs/doc in Debug
vs 0.4 µs in ReleaseFast), which dwarfed every other difference in the
MongoDB comparison below.
- **Compaction is O(n²) under the default 16 MB threshold.** A compaction
rewrites the whole log (one fsync per record), so bulk-loading 5 GB with
the default threshold degrades from ~310 MB/s to a crawl as the dataset
grows. Raise `--compact-threshold` for bulk loads — e.g. `2g` — and the
rate stays flat. The 5.37 GB run (40,960 × 128 KB docs, ObjectIds,
ReleaseFast) inserted in 36.5 s at ~310 MB/s between the two threshold
compactions, peaked at 5.25 GB RSS (~0.98x the data size at 128 KB
docs), and reopened the 5 GB log in 13.8 s.
- **`findOne({_id})` is O(1) only for ObjectId ids.** Integer, int64 and
double ids compare equal but hash differently, so the docs-map fast path
is skipped and every `_id` lookup becomes a full scan. Use the driver's
default ObjectIds (or a secondary index) on big collections.
- **Secondary-index entry insert is O(n)** (sorted array — see v1 limits
above), so creating an index over existing data or inserting with an
index in place is quadratic. Create indexes after the load.
## Performance vs MongoDB
`tests/e2e/compare-run.sh` runs the same driver workload (1 GB, 65,536 ×
16 KB docs, every write durable — mongo-lite fsyncs per command, mongod
runs with `j: true`) against each server and prints a side-by-side table.
With the ReleaseFast default build (MongoDB 8.3.7 on the same Mac):
| benchmark | mongo-lite | mongodb | winner |
|---|---|---|---|
| insertOne (sequential) | 0.2 ms | 4.9 ms | **mongo-lite ×24** |
| bulk insert (insertMany) | 267 MB/s | 690 MB/s | mongodb ×2.6 |
| createIndex({k: 1}) | 0.66 s | 0.08 s | mongodb ×8 |
| countDocuments({}) | 2.5 ms | 11 ms | **mongo-lite ×4** |
| findOne({_id}) | 0.6 ms | 0.7 ms | mongo-lite |
| findOne indexed | 0.7 ms | 2.6 ms | **mongo-lite ×4** |
| range-scan count | 25 ms | 13 ms | mongodb ×2 |
| sort + limit(20) | 40 ms | 2 ms | mongodb ×20 |
| aggregate $group | 12 ms | 13 ms | mongo-lite |
| updateOne({_id}) | 0.18 ms | 0.21 ms | mongo-lite |
| updateMany (65 docs) | 20 ms | 6 ms | mongodb ×3 |
| deleteOne + insert | 0.9 ms | 5 ms | **mongo-lite ×6** |
| server RSS | 2.0 GB | 1.3 GB | mongodb (×0.65) |
| kill -9 → reopen | 3.8 s | 1.3 s | mongodb |
| db on disk | 1.0 GB | 89 MB | mongodb (compressed) |
The pattern: mongo-lite wins every *latency-bound* single-op (no network of
index hops, no journal latency, in-RAM) and loses the *throughput-bound*
bulk paths and the ops MongoDB accelerates with disk indexes and
compression.
### Suggested improvements (highest impact first)
1. **Index-accelerated sort** — the worst gap (×20): `sort+limit` sorts
every document. Stream candidates in index order (the planner already
has ordered range search) and stop at `limit`. Fixes the biggest read
regression.
2. **Batch index builds**`createIndex` inserts entries one at a time
into a sorted array (O(n²) memmoves). Sort all entries once and append
in bulk (O(n log n)); a B-tree or id→entry map removes the O(n) entry
insert on the write path too.
3. **Compress the log** — the db is 11× MongoDB's on disk because payloads
are stored raw. Snappy per record (like the wire protocol's OP_COMPRESSED)
would shrink highly-compressible workloads massively.
4. **Faster reopen** — replay is a full re-parse of every record. A
periodic checkpoint record (or a parallel replay) would cut the 3×
restart gap.
5. **Trim the write path** — bulk insert (×2.6) is now bound by per-doc
parse/serialize/map-put, not fsync. A pooled per-connection arena for
owned docs and a bulk-insert fast path would close most of the gap;
updateMany's per-doc replace-serialize is the same story.
6. **Range-scan matching (×2)** — the matcher allocates a candidates list
per field per doc; a stack buffer for the common single-field case
removes it.
Two real bugs were found and fixed while benchmarking:
- `plan_id` returned a pointer to a stack temporary (`&.{e}`) that dangled
after the frame returned — Debug tolerated it, ReleaseFast read garbage,
silently breaking every `findOne({_id: <ObjectId>})`. It now heap-copies
the lookup value and frees it.
- Multi-doc writes fsynced once per document; they now group-commit (one
fsync per command, same crash guarantees — verified by the kill -9
crash suites).
## Code style