Cinder Kills Its Own Writer to Test a Single Promise

A zero-dependency Go key-value store that kills its writer mid-write, reopens the log, and checks whether every acknowledged key survived. Inside the recovery rule that decides when a torn tail is recoverable and when a file is corruption.

9 min read • View on GitHub • More from Abu103

An editorial ink illustration of a large open ledger book on a plain table, its pages filled with tightly ruled sequential entries. The right edge of the ledger is charred and blackened, and a hand holding a straight blade is trimming the burned edge away, leaving the surviving entries crisp. It illustrates how an append-only log survives a crash and recovery cleanly cuts the damaged tail.
Recovery as an act of trimming: an append-only log survives a crash, and the damaged tail is cut away cleanly. This is the whole thesis of Cinder's crash model in one gesture.
Key Takeaways

The Harness That Kills the Writer

Most key-value stores claim durability in a README and leave it there. Cinder ships a program whose entire job is to make that claim fail. It lives in cmd/crashtest, and it does exactly what the name says.

The harness builds cmd/writer, runs it, and kills the process at a random moment. Then it reopens the store and checks one narrow promise: every key the writer acknowledged must come back. Nothing more, nothing less.

The clever part is that the harness never trusts the victim. The writer prints a key only after Put returns, so its standard output is the record of what it claims succeeded. The harness verifies against that contract. A tiny shared package, internal/crashproto, defines deterministic key names and values so the harness can reconstruct the expected state without reading the child process's memory or asking it anything.

That design choice is the whole point. If the writer could report its own success after the fact, the test would be circular. By fixing the key and value scheme in advance, the harness knows what a correct store should contain after any crash, and it can prove the store wrong.

Bitcask in 80 KB

Cinder is a Bitcask store. Every mutation appends a checksummed record to a log file. An in-memory map[string]entry points at the newest record for each key. Deletes write tombstone records. Compaction rewrites live data into fresh segments and drops the old ones. The whole engine is about 80 KB of Go, standard library only.

The record header is 21 bytes, big-endian: a CRC-32C checksum, an 8-byte timestamp, a 4-byte key length, a 4-byte value length, and a 1-byte flag. The interesting decision is what the checksum covers.

// store/record.go
const HeaderSize = 21 // CRC-32C(4) + timestamp(8) + keyLen(4) + valLen(4) + flag(1)

// Encode computes the CRC over buf[4:] -- the timestamp, both lengths,
// the flag, the key, and the value. A flipped bit in a length field is
// detected, not trusted.

Many simple logs checksum only the payload. Cinder checksums the lengths and the flag too, so a corrupted length field is caught before the decoder tries to allocate against it. There is a second guard behind that one: the decoder rejects any record whose declared keyLen + valLen exceeds a 64 MiB cap before it allocates the payload, so a garbage length cannot trigger a multi-gigabyte allocation.

The Manifest Is the Only Commit Point

An editorial ink illustration of a filing room with two banks of wooden card-catalog drawers. The old bank on the left is being emptied by a gloved hand while the new bank on the right is being filled with fresh identical cards. On a small desk in the foreground, a single master index card sits in a brass holder as a third hand places it, with the drawers still mid-transfer behind. It illustrates the manifest as the single commit point that makes the new state real.
Two banks of drawers swapping contents, and one master index card on the desk. The drawers mid-transfer are orphaned segments. The single card is the manifest write that makes the new state real.

Compaction is where a log-structured store usually gets dangerous. Cinder's Compact holds the write lock for its entire run. It iterates the index, copies each live record into a temporary segment, seals and rolls to a new temp file when the size cap hits, renames the sealed temp files into place, creates a fresh active segment, writes a new manifest listing only the new segments, then reopens those files, swaps the in-memory state, and deletes the old ones.

One file is the switch. Everything before the manifest write is invisible to the next open, and everything after it is authoritative. The same care shows up one level down: startSegment opens the new file, updates the in-memory maps, and then writes the manifest. If that manifest write fails, it rolls the in-memory state back and closes the file, so the live view never points at a segment the manifest does not know about.

Torn Tail or Corruption?

This is the payoff. On open, replaySegment in store/recover.go scans records from offset zero. A clean end of stream stops the scan. A decode error is where it gets interesting: the code computes remaining := size - (cur + consumed), the number of bytes that follow the bad record, and then makes one decision.

If bytes remain, or the segment is sealed (not the newest one), it returns ErrCorrupt and refuses to touch the file. Otherwise it treats the damage as a torn write, truncates the segment to cur, adds the cut bytes to a BytesCut counter, and stops.

The whole durability contract in one branch. Click a record to damage it, drag the file end to tear the write, and watch the verdict flip. The 'Show the leak' mode reproduces the misclassification the author documented around.

The rule rests on an invariant, stated plainly in the code: rotation always happens between records, so damage inside a sealed segment cannot be a torn write, it can only be corruption. The newest segment is the only one that can end mid-record, and only at its tail.

// store/recover.go (the shape of the branch)
remaining := size - (cur + consumed)
if remaining > 0 || sealed {
    return ErrCorrupt // bytes follow the damage, or the file is closed: do not touch it
}
// no bytes follow and the segment is the newest one: torn tail
// truncate to cur, add the cut bytes to BytesCut, stop

Where the Model Leaks

The torn-tail decision depends only on whether bytes follow the bad record. It never checks whether that record's declared length is plausible. And that gap is exploitable by a single flipped bit.

Picture a bit flip in the keyLen or valLen field of record 50 of 100, in the newest segment. If the corrupted length still fits under the 64 MiB cap, the decoder tries to read that many bytes. If the claimed length runs past the end of the file, the read returns a partial-record error and consumed swallows every remaining byte. remaining lands at zero. The code classifies the damage as a torn tail, truncates the file there, and silently discards the live records sitting behind the corruption.

A store that documents its own leak is doing something most projects avoid. The gap is real, it is narrow, and the honest reading is that the recovery rule is a good heuristic rather than a proof. Anyone who has written a storage engine will recognize the shape of the problem: the check that distinguishes a recoverable crash from corruption is a single comparison, and single comparisons are exactly where subtle bugs hide.

What Cinder Is Not

Cinder is a learning-grade engine, not a database you deploy. The honest way to place it is against the tools it borrows from, on the same problem with different commitments.

Durability modelIndexCompactionDependenciesCrash testing
CinderAppend-only log + manifest commitIn-memory hash map rebuilt by replayRewrite live records, swap manifestGo stdlib onlyBuilt-in process-killing harness
Bitcask (paper)Append-only logIn-memory keydirMerge old filesN/ADescribed, not shipped
bboltB+tree, single file, mmapOn-disk B+treeCopy-on-write pagesNoneExternal test suites
BadgerLSM-tree, value logLSM + value logLSM compactionSeveralExternal test suites
SQLiteWAL / rollback journalB-treeVacuum / checkpointNoneExtensive external

Read the last column. Cinder is not competing on features or throughput. It competes on the readability of its durability argument, and the harness is the only place where it does something the others do not ship. Everything else here is a well-trodden design, executed carefully and small enough to read end to end.

One Contributor, No License, No Stars

The repository has no description, no topics, no license, and one recorded contribution. That is not a flaw to apologize for. It is a specimen, not a dependency. The value is that you can read the entire engine, including its crash model and its crash harness, in an afternoon.

There is evidence the author ran it on the target platform. store/log.go opens the log with O_RDWR and deliberately avoids O_APPEND. The comment explains why: on Windows a handle opened with O_APPEND gets only FILE_APPEND_DATA, and SetEndOfFile, used by truncation, then fails with an access error, which would make torn-tail recovery impossible. That is a bug found by running the code where it was meant to run, and the fix is documented where the next reader will find it.

There is one more subtlety worth flagging. In Append, the write cursor advances before the fsync runs, and the comment says why: even a failed fsync leaves the bytes in the file, so the next append must not overwrite them. The consequence is that a Put which returns an error after a successful write can still be durable, and replay on the next open will index it as live. The caller was told the write failed, but the write may come back. Cinder does not discuss that ambiguity, and it is the kind of edge a reader of storage engines should learn to spot.