34. Vector database II: persistence and schema evolution

Why this layer exists

A memory that forgets on restart is not a memory. Chapter 33’s graph lives in a process’s heap, and the process is a daemon that will be restarted, upgraded, killed by the OOM killer and sometimes caught by a power cut. Chapter 35’s service writes every message into a store and chapter 40’s daemon opens one store for its whole life, so the store has to say which acknowledged writes survive which failures, keep that promise, and refuse loudly the failures it cannot keep it through.

The second half is a promise chapter 21 made and chapter 32 repeated. An embedder is part of a vector store’s schema: the stored vectors are points in the space of one model, one pooling and one normalisation, and a query is only comparable with them if it is embedded in the same space. On 2026-09-29 honcho-embed was serving --pooling cls when it should have been serving --pooling last; the fix changed the vector space under every vector Honcho had stored, nothing but the vectors showed it, and Honcho’s whole store was re-embedded overnight. That is the worked example of this chapter’s second half. A store has three answers to a changed embedder: rebuild, read both spaces for a while, or refuse. The store here does all three, refuses by default, and checks the space at open, which is the promise chapter 32 made when it wrote that chapter 34 uses both: Equal for the schema at open and Check for the drift no name shows.

Mechanism

What is promised, and against what

Three failures are different enough to need different answers.

  • A process crash. The process dies (a panic, the OOM killer, kill -9) and the operating system does not. Every write that returned is in the kernel’s page cache and will be read back by the next process, synced or not.
  • An operating-system crash or a power cut. The page cache is gone. What survives is what had reached the device, plus an arbitrary subset of what had not: a file’s last write may come back with its first page and not its second, or with its length extended over zeros.
  • Damage at rest. A bad sector, a bit flipped in memory before the write, a stray write by another program. The bytes on disk are not the bytes the store wrote.

The store promises, per SyncPolicy:

process crash OS crash or power cut damage at rest
SyncEveryWrite (the default) every Add or Delete that returned is recovered every one that returned is recovered; the one in flight may or may not be detected: ErrCorrupt, or, when only the last record is damaged, cut and reported; a log cut exactly at a record boundary is not detected, unless a snapshot lies beyond the cut (“Sequence numbers”)
SyncOnSnapshot every one that returned is recovered recovered up to the last Snapshot or Close; after it, anything may be missing, and the log may not reopen (see “A torn tail is not interior damage”) as above

“Recovered” means the record is in the index after Open with the vector it was added with. “Detected” means Open returns an error wrapping ErrCorrupt, or reports in Recovery the bytes it cut, and in no case hands back an index that differs from what the files say. The record in flight is not acknowledged either way, so the contract allows both outcomes; what it forbids is a state that is not a prefix of the history (a later record present while an earlier one is missing), and a state that is a prefix but silent about it.

One process owns a store. None of this holds for two openers. A writer’s append reaches the page cache in chunks, and a second Open that reads the log between two chunks sees half a record at its end, which is what a torn tail looks like: it cuts it, the writer finishes its append at the old length and fsyncs, and the next Open finds a log that is damaged in the middle and refuses it, with acknowledged records in it. Two writers overwrite each other’s offsets and lose an acknowledged record without a trace, and a stale opener appends into a generation a rebuild has since removed. So Open takes an exclusive flock on Dir/LOCK before it reads anything, and Close, or the death of the process, releases it. A second Open of a live store, in this process or in another, is ErrBusy. That includes aec-vecdb recover and query, which open the store as its owner and therefore refuse a live one: to look at a live store, look at a copy. The lock is advisory, flock(2): it stops cooperating openers, not a program that writes the files directly. TestOwnerLockProtectsAnInFlightAppend builds the half-copied append and requires the second Open to be refused and the log to be byte-for-byte unchanged; the same scenario against the commit before the lock lost the writer’s acknowledged records.

Write-ahead

The mechanism is a write-ahead log (Mohan et al., ARIES, 1992, for its most general form): every change is appended to a file before it is applied to the index, and Open rebuilds the index by replaying the file. The invariant is that the log holds every change the index holds. Add has three steps and the order matters.

  1. Validate. The record’s ID, width and components are checked against the generation. A record the log accepted and the index refused would be a poison pill: every later Open would replay it into the same failure. So a NaN, a wrong width, an empty ID and a record whose encoding would exceed the log’s 64 MiB record limit (which the reader treats as damage, so the writer must never produce one) are refused before a byte is written. TestAddIsValidatedBeforeItIsLogged reads the log before and after the refusals and requires the bytes to be the same.
  2. Append, at the log’s end, and under SyncEveryWrite fsync it.
  3. Apply to the in-memory index and count the record.

If the append fails, the index is unchanged: TestAddFailureLeavesTheIndexAlone closes the log file under a store and requires both Add and Delete to fail with Len and Search as they were. The reverse order breaks the invariant that gives write-ahead its name: a search could then see a change the next Open would not reproduce. A mutant that applies before it appends fails at least four tests, TestAddFailureLeavesTheIndexAlone, TestStoreRoundTrip and TestAutoSnapshotAndHNSWStore among them.

The record and its checksum

A log is an 8-byte file header and a run of records. Each record is a 20-byte header, a payload and a 4-byte checksum, laid out in the listing ch34-wal-format below and drawn here.

The record, the log and the store directory Three panels from top to bottom. First, one WAL record as a strip of fields left to right: the magic AECR, a version byte, a kind byte, two zero bytes, a 32-bit length, a 64-bit sequence number, a 32-bit JSON length, the canonical JSON header, the vector as float32 values, and a CRC-32C over everything before it. Second, the log: a file header, four intact records and a fifth cut short, with the two outcomes of replay written beneath: no intact record after the damage means a torn tail, which is cut at the last good record and reported; an intact record after it means interior damage, which under SyncEveryWrite no crash makes and which is refused with ErrCorrupt and nothing is cut. Third, the store directory: an empty LOCK file holds the owner's exclusive lock from Open to Close; CURRENT, meta.json and fingerprint.json each end in a crc32c line; CURRENT names the live generation g2 and, during a dual-read, the previous g1; each generation holds meta.json, fingerprint.json, wal and snapshot. A rebuild writes a whole new generation and switches CURRENT with one atomic rename, so an interrupted rebuild leaves the old generation live. Record20-byte header, payload, 4-byte trailer; little-endian AECR ver kind 0 0 length, seq n JSON header float32 × d CRC the CRC-32C covers the header and the payload kind 1 add, 2 delete; the header is canonical JSON, so a record's bytes are a function of the record Log and replayappended before the index changes, fsynced per write or per snapshot AECW record record record record torn a damaged record with no intact record after it is a torn tail: cut at its start, report TruncatedAtandDropped, and the next append follows the last good record an intact record after the damage is interior damage, which under SyncEveryWrite no crash makes: ErrCorrupt, nothing cut, the operator decides Store directorygenerations, named by one small file LOCKempty file; an exclusive flock held from Open to Close, so a second Open is ErrBusy CURRENT{"generation":"g2","previous":"g1","next":3} CURRENT, meta.json and fingerprint.json each end in a crc32c: line g2/meta.json fingerprint.json wal snapshotthe live space g1/meta.json fingerprint.json wal snapshotthe space being left (dual-read) a snapshot is the index at a WAL offset, written to a temporary name, fsynced and renamed into place Rebuild builds a whole new generation, then switches CURRENT with one rename: interrupted, it leaves the old generation live and the half-built one unreferenced; Open never reads it the directory is fsynced after every rename: the entry is state too

The payload is a JSON header (the ID, the metadata, the text, the width) and then the vector as raw little-endian float32, so a replayed vector is bit-identical to the one logged and a record costs 4d4d bytes of vector plus its header. The header is canonical JSON: chapter 21’s rules, through internal/canon, so a record’s bytes are a function of the record. TestWALRecordBytes pins the layout byte by byte and shows a metadata map written in key order whatever the order it was built in. A record whose bytes are a function of its content is one that can be compared, diffed and checked against a second implementation, which is the lab’s use of it.

The checksum. The record ends with a CRC-32C of the header and the payload. Go’s hash/crc32 calls the polynomial Castagnoli; it is the one iSCSI and ext4 use. What a CRC guarantees can be derived, and the derivation says exactly where the guarantee stops.

The setting. Read a message of NN bits as a polynomial M(x)=∑imixiM(x) = \sum_i m_i x^i over the two-element field, where addition is XOR and there is no carry. Fix a generator G(x)G(x) of degree 32. The checksum of MM is the remainder R(x)=x32M(x)modG(x)R(x) = x^{32} M(x) \bmod G(x). Go computes it with the register started at all ones, complemented at the end, and fed the bits of each byte least significant first. The start value and the final complement add a constant that depends only on NN and cancel when two messages of the same length are compared; the bit order only renumbers the bits, so the error polynomial is read in that order, with the least significant bit of byte 0 as the coefficient of the highest power (crcBit in the test below makes the mapping). A corruption is an error polynomial E(x)E(x) (a 1 wherever a bit flipped). The corrupted message has the same checksum as the original if and only if

x32E(x)≡0(modG(x)), x^{32} E(x) \equiv 0 \pmod{G(x)},

and since GG has the constant term 1 it shares no factor with xx, so the condition is G∣EG \mid E. Everything below is a statement about which error polynomials a polynomial of degree 32 can divide. GG is the Castagnoli polynomial x32+x28+x27+x26+x25+x23+x22+x20+x19+x18+x14+x13+x11+x10+x9+x8+x6+1x^{32} + x^{28} + x^{27} + x^{26} + x^{25} + x^{23} + x^{22} + x^{20} + x^{19} + x^{18} + x^{14} + x^{13} + x^{11} + x^{10} + x^{9} + x^{8} + x^{6} + 1 (0x1EDC6F41 without the leading term; 0x82f63b78 is the same constant bit-reversed, the form Go writes). It has 18 terms.

Every single-bit error. E=xeE = x^e. If G∣xeG \mid x^e, every irreducible factor of GG divides xex^e, and the only irreducible factor of xex^e is xx. Then GG would be a power of xx, and it is not, since its constant term is 1.

Every error of odd weight, whatever the distance between the flipped bits. GG has an even number of terms, so G(1)=0G(1) = 0 and (x+1)∣G(x + 1) \mid G. For any EE, E(1)E(1) is the parity of its number of terms, so an error of odd weight has E(1)=1≠0E(1) = 1 \neq 0 and (x+1)(x+1) does not divide it, hence GG does not either. This is a property of this particular GG; a generator with an odd number of terms does not have it.

Every burst of at most 32 bits. A burst is E=xsB(x)E = x^s B(x) where BB has degree at most 31 and a nonzero constant term (the flips are confined to 32 consecutive bits). Because gcd(G,xs)=1\gcd(G, x^s) = 1, G∣xsBG \mid x^s B forces G∣BG \mid B. A nonzero polynomial of degree below 32 is not a multiple of one of degree 32. So no burst of 32 or fewer bits goes undetected, wherever it sits.

Where it stops. A burst of 33 bits is xsBx^s B with degB=32\deg B = 32, and B=GB = G is allowed: E=xsGE = x^s G is divisible by GG and the checksum cannot see it. The bound is tight, and TestCRC32CGuarantees builds the counterexample. It takes a real 4,194-byte add record, flips the 18 bits at the positions of the generator’s own terms (shifted to lie inside the vector), and the record still parses, with its CRC untouched and a different vector: one component went from 0.04666697 to 3.7549597e-35. crcBit in that test maps an exponent to a (byte, bit) position in Go’s reflected order, and the forged record passing is the check that the mapping and the claim G∣EG \mid E agree.

A random change. If the damage is a uniformly random nonzero pattern of fewer than nn bits, the undetected ones are the nonzero multiples of GG of degree below nn. There are 2n−32−12^{n-32} - 1 of them among 2n−12^n - 1 nonzero patterns, a fraction below 2−322^{-32}. One damaged record in four billion passes. That is the figure for “unlucky”, and it is a figure about accidents.

What a CRC is not. It protects against faults, not against someone who can write the file. Anyone who can change a byte can recompute the four checksum bytes, and the tests that forge snapshots below do exactly that (reseal). The log has no key, so the store does not claim authenticity. What defends a forged-but-checksummed record is the structural validation it also gets (width, finiteness, ID, the count a snapshot claims), and what defends against a forged-and-well-formed one is file permissions, which are not this chapter’s. Hamming-distance tables for longer even-weight errors, which say how many bits a CRC of this polynomial is guaranteed to catch at a given message length, are Castagnoli, Bräuer and Herrmann’s (1993) and are cited, not restated. Exercise (a) asks for the one case between the single bit and the burst.

TestCRC32CGuarantees also counts what it tried on that record: all 33,552 single-bit flips, 20,000 errors of odd weight from 1 to 23 bits, 456,407 two-bit errors at 14 distances at every position, and 93,000 bursts of 2 to 32 bits, with none accepted. Those counts are samples, and the guarantees above are theorems; the test is evidence that the code computes the theorem’s CRC and that ParseRecord cannot be tricked past it by anything it checks around it.

A torn tail is not interior damage

An append-only file has a shape after a crash, and the recovery rule is an argument about that shape. Every write begins at the file’s current end and the end only grows, so a record’s bytes are written once, at the then-end. Under SyncEveryWrite the next record is not written until the previous one has been fsynced. Whatever the crash does, it therefore damages the record that was being written, which is the last one; everything before it was already on the device. The damage may be a cut (the file ends mid-record), a hole (a page of the last record is missing and zeros are there), or garbage. In every case no intact record follows the damaged one, on the assumption that the file’s unwritten bytes are zeros or garbage that does not itself spell a well-formed record (ext4’s default ordered mode extends a file over zeros). A file system that exposed stale blocks could hand back the intact records of a deleted log, and Open would refuse a log that SyncEveryWrite was meant to recover, which is the safe direction.

The converse is the rule. A damaged record followed by an intact one cannot be a torn write: the intact one was written after the damaged one was finished, and finished writes are durable under this policy. It is media corruption, a stray write, or a bug. Cutting the file there would discard the intact records after it, which are good data, so Replay (listing ch34-replay) refuses with ErrCorrupt and changes nothing on disk, and the operator, who is told the byte, decides. When no intact record follows, the damaged tail is cut at the last good record, and what was cut is reported in Recovery.TruncatedAt and Recovery.Dropped. The cut is fsynced before Open returns, and the next append follows the last good record.

Replay finds out whether an intact record follows by searching for the four magic bytes after the damage and trying ParseRecord at each hit. The search runs only when a record has failed, so a healthy Open pays nothing for it.

Four limits are part of the rule, and the tests do not hide them.

  • The rule cannot tell a torn last record from a corrupted last record. A flipped bit in the length field of the final record, which was written, fsynced and acknowledged, makes it unparseable with nothing after it, and it is cut like a torn write. It is reported (Dropped is not zero), not silent, but an acknowledged record is gone. Exercise (b) asks for the trace. No scheme that looks at a log alone can separate the two; a second copy or a checksum chain kept elsewhere could.
  • Under SyncOnSnapshot the premise does not hold. Several records may be in flight, and a power cut can keep a later page while losing an earlier one. The log then has a damaged record followed by an intact one without any media failure, and Open refuses it with ErrCorrupt. That is the safe direction (it never invents or silently drops anything), but it is an availability failure the policy buys with its cheaper writes: after a power cut with unsynced appends, the operator may have to cut the log at the reported byte by hand. The contract table above says so.
  • A run of damage that reaches the end of the file is a torn tail, whatever caused it. A bad sector under the last three records reads as a tail of three records, which are cut and reported together if no intact record follows. The report says how many bytes; it cannot say how many records they were.
  • The scan for an intact record can be fooled by a vector. A vector is arbitrary bytes. A torn last record whose vector happens to contain the bytes of a complete record (crafted, or astronomically unlucky) is read as interior damage and refused, again the safe direction. The scan resynchronises on the four magic bytes, not on a record framing that content cannot imitate.

Two tests exhaust the rule on a small log. TestTruncateEveryOffset cuts a five-record log at every byte of its last record and requires that the first four records come back, that the cut be reported with the right offset and byte count, and that after a new record is appended and the store closed, a second open find nothing to cut. TestFlipEveryByte flips every byte of a three-record log in turn: a flip anywhere in the last record is a torn tail (cut, reported), a flip anywhere before it is ErrCorrupt. The lab runs the same two checks against your own Replay.

Sequence numbers

A CRC says a record’s bytes are the bytes that were written. It does not say they are where they were written. So each record carries its position under the checksum, a sequence number: 1 for the first record of a log, one more for each after. Replay is told the number it expects and refuses, with ErrCorrupt, an intact record that carries any other. A record copied over another of the same length by a misdirected write, two records swapped, a record duplicated at the end, a whole record removed from the middle: each record is intact and the log is wrong, and each is refused (TestSequenceNumbers). Without the field, all four open clean with acknowledged records missing or reordered. A snapshot records the sequence number of the last record it holds, and Open checks it against the log (below).

What a sequence number cannot give is the log’s length. A log cut exactly at a record boundary is a valid shorter log, and nothing inside it says it was ever longer. If a snapshot lies past the cut, the snapshot says so and Open refuses; if none does, the records after the cut are gone and Open is clean. TestSequenceNumbers has both cases. Only a count kept outside the log closes it, the snapshot’s being one, and the contract table says that this case is not detected.

fsync, and what it buys

SyncEveryWrite calls fsync on the log before Add returns; SyncOnSnapshot calls it only when a snapshot is taken and at Close. SQLite’s documentation states the assumption underneath both: “SQLite assumes that the flush or fsync will not return until all pending write operations for the file that is being flushed have completed” (Atomic Commit In SQLite), and says in the same paragraph that the primitive is reported broken on some Windows and Linux versions and that there is nothing the library can do about it. A disk that acknowledges a flush it has not performed defeats every protocol in this chapter, and none of them can detect it.

Pillai et al. (OSDI 2014) show that applications’ crash-consistency protocols depend on persistence properties of the file system (for example, which operations are atomic and in what order they reach the device) and that these differ among Linux file systems. Two rules in this store come from taking that seriously. A file is fsynced before it is renamed over another, so the rename can never make a half-written file the live one. A directory is fsynced after a rename or a new file in it, because the entry that names the file is state too: POSIX requires rename to be atomic (its Rationale: “That specification requires that the action of the function be atomic”) and the page says nothing about when the new name is durable. writeFileAtomic and writeSnapshot do both.

What SyncEveryWrite costs is measurable, and depends on the disk it is measured on and on nothing else in the code. On straylight, whose store directory is ext4 on a dm-crypt volume, aec-vecdb fsync adds 1,000 records of width 1,024 (4,151 bytes each) under each policy; three runs gave a median Add of 0.250, 0.284 and 0.254 ms with a flush on every write and 0.007, 0.008 and 0.006 ms without, 36 to 42 times as much, and a 1,000-record load of 0.26 to 0.29 s against 0.01 s. One flush per write therefore bounds a single writer at roughly 3,400 to 3,800 records per second on that disk before any embedding happens; chapter 21 measured a median of 20.5 ms to embed one text on dixie (from talos, through tether) and chapter 32 31.2 ms, so for the memory service the flush is not the bottleneck. A disk with no write cache pays milliseconds per flush instead. The same command on talos, whose scratch directory is a tmpfs, reported 0.008 ms for the flushing policy and 0.016 ms for the other: on a memory file system fsync does nothing, the two policies are indistinguishable, and the number says nothing about durability. Measure the disk the store will live on.

Snapshots

Replaying a log costs what building the index cost. On the fixture, with a graph of 1,018 records, replay is the whole build. A snapshot (listing ch34-snapshot-format) is the index at one log offset, so Open loads it and replays only what follows. On talos, Open of the fixture store took 21, 22 and 18 ms from a snapshot and 546, 572 and 543 ms from the log alone (recover -time, three runs each): the second is the build of chapter 33, and it grows with the corpus while the first grows only with the bytes read.

A snapshot is a claim about the log and the log is the authority, so Open checks the claim before it uses a byte of the index.

  1. Checksum first. The CRC over the whole file is verified before anything is decoded. A damaged snapshot is ErrCorrupt; there is no fallback to the log, because the log may have been the thing the snapshot was supposed to replace, and a store that quietly falls back may be a store whose log has been truncated since.
  2. Structure. The decoders (decodeHNSW, chapter 33’s, and decodeFlat) validate everything a search relies on: a width bound before any allocation, counts checked against the stream as it is read, no repeated live ID, no non-finite component, every link pointing at a node that reaches its layer, the enter point on the top layer. Nothing is allocated from a header’s count, so a snapshot that claims two to the 40th rows cannot make Open ask for memory. The stream must end where the index does, and the header’s record count must be the index’s.
  3. Shape. The snapshot must be the kind of index meta.json describes: a graph where the generation has graph parameters and an exact index where it has none, the same metric, the same width, the same parameters.
  4. The log. The header names a byte offset and the sequence number of the last record before it. Open walks the log from its header to that offset, parsing and checking each record and its sequence number, and requires that it land on the offset exactly, after the record with exactly that number. An offset past the log’s end describes records the log no longer holds. An offset inside a record would otherwise read as a torn tail and cut a good record. An offset one record too far would skip a record the snapshot does not contain. All three are ErrCorrupt, and TestSnapshotLiesAboutTheLog tries each, with the offset and the sequence number a lie would need to be consistent. The walk costs the checksum of every log byte before the offset, at the speed of the processor and not of the index; the log is already read whole into memory by Open, which is a cost the log’s growth makes real (below).

What the four checks cannot catch is a snapshot whose contents disagree with the log prefix its header agrees with, because deciding that means replaying the prefix, which is the work the snapshot exists to skip. A file that has been forged and resealed can do that; a fault cannot do it by accident, because the checksum fails first. This is the CRC’s limit restated: the store defends against faults, not forgery.

Snapshot and Close write the snapshot: to a temporary name, fsynced, renamed over the old one, the directory fsynced, after the log has been fsynced, because a snapshot must never describe bytes the disk could still lose. Close snapshots any generation with records since its last snapshot, so a clean restart replays nothing (TestStoreRoundTrip); records replayed by Open count, so a store that recovered a log and was then closed cleanly does not replay it a second time (TestCloseAfterRecoverySnapshots). SnapshotEvery, zero by default, snapshots after that many appends. If that snapshot fails after the record was logged and applied, Add returns a *SnapshotError, whose message says that the record is durable and visible and only the snapshot is missing; the next one retries (TestAutoSnapshotFailureIsReportedAsSuch). The write happens under the store’s lock, and the file is assembled in memory before it is written, so a snapshot transiently needs memory the size of the index again; at a million 1,024-wide records that is 4 GB beyond the index.

The graph’s random-number state is inside the snapshot. A graph that was saved, loaded and then extended draws the levels an uninterrupted build would have drawn: TestAutoSnapshotAndHNSWStore builds 45 records with a snapshot every ten, abandons the store, recovers it and compares its encoding byte for byte with a graph built straight through. Chapter 33’s claim that a build is a function of the data, the order and the seed therefore survives a restart.

What a snapshot never does in Part V is make the log shorter. The log holds every record ever appended, deleted ones included, and Open reads all of it. Dropping the log below a snapshot’s offset is log rotation, which is chapter 40’s; it is a generation switch, as in the next section, that starts a new generation from a snapshot with an empty log, not a truncation in place. The carry-forward is explicit, and exercise (c) designs it.

Generations and CURRENT

A store is a directory. One small file, CURRENT, names the live generation, and each generation is a subdirectory with its own meta.json, fingerprint.json, wal and snapshot (listing ch34-layout). Everything a store can do to its own layout is built on one operation: rename a file over CURRENT, atomically, after the new generation is complete and durable.

Open treats the directory as untrusted input, because after a crash or a restore it is.

  • CURRENT, meta.json and fingerprint.json are JSON followed by a line holding its CRC-32C. These small files are read by people, and a flipped bit in one is a different setting that nothing else would notice: with "M":16 changed to "M":17 in meta.json, a store without the checksum opened and rebuilt its graph at M = 17. Now it is ErrCorrupt (TestSmallFilesAreChecksummed flips bits across all three).
  • CURRENT is parsed strictly. A generation name is g and a decimal number with no sign and no leading zero, because the name becomes a path: "../g1" and "g1/x" are refused. The previous generation differs from the live one, and next is above both numbers, so a rebuild can never be handed the name of a directory that is in use (createGeneration removes a stale directory of its name). TestDirectoryAttacks has fourteen malformed or lying CURRENT files and requires ErrCorrupt for each.
  • A missing CURRENT over a directory that holds records is ErrCorrupt, not a new empty store. Creating a store removes a stale g1, so a lost CURRENT must not look like a first run. The one thing a first run may find is what its own interruption leaves: generation directories whose log is only its header and which hold no snapshot, and a CURRENT.tmp.
  • The directory is private. The log carries each record’s text, so a store creates every file with mode 0600 and every directory with 0700, whatever the umask (TestStoreFilesArePrivate runs with umask 0 and walks the tree). A store created by an earlier build keeps its old modes; the owner of that store (chapter 35’s service does) tightens them.
  • A generation’s log must exist and begin with its 8-byte header. A missing or empty log is ErrCorrupt; Open does not create one, since a generation that was opened before has had those bytes on disk since its creation and a log that has lost them has lost records too.

A rebuild writes a whole new generation, fsyncs it, then switches CURRENT. A crash before the switch leaves the old generation live and the half-built one unreferenced; Open never reads a directory CURRENT does not name, and the number the failed attempt took is not reused (next is written before the build starts), so a later rebuild cannot collide with the leftover. TestRebuildInterruptedMidway cancels a rebuild on its third embedding call and checks all of that: the old generation live, 200 records and width 64 intact, g2 gone, and the retry named g3. A crash, unlike a cancellation, kills the process that would have removed the half-built directory, so it stays until an operator removes it; Part V does not garbage-collect directories, and an orphan is never read.

The cost is two copies on disk while a rebuild runs. A rebuild copies live records only. Chapter 33’s tombstones, which Delete leaves in the graph so that routing survives, stay in the old generation’s snapshot and go with it when the old directory is removed. TestRebuildDropsTombstones builds a graph with 20 deleted and 10 replaced records, 30 tombstones among 70 nodes, and requires 0 tombstones among 40 nodes after the rebuild and after a reopen. Nothing else compacts them in Part V: log rotation would, without re-embedding anything, and it is chapter 40’s.

Filtering

A Filter reads a record’s metadata, and Match builds the one the lab needs: every key present with the given value. Flat applies it before scoring, so a rejected row costs the call and no multiply-adds. HNSW applies it on layer 0 during traversal and expands rejected nodes without admitting them (chapter 33’s extension, which is why a selective filter does not disconnect the search). Store.Search passes the filter straight through, and SearchText passes it to both spaces during a migration; TestDualRead checks that no record from outside the filter appears in a merged list. The recall cost of a very selective filter is chapter 33’s exercise (e). What a filter changes in an answer is easiest to see on the fixture, in the walkthrough: the same query with -book 16.

Schema evolution

The schema of a store is its width, its metric, its graph parameters and the space its vectors live in, which is the fingerprint: the embedding model’s name, the model, the width, the pooling, the normalisation, and the probe texts with the vectors the space gave them. The first three are checked by comparison. A different Dim, Metric or non-zero Params in Options is ErrSchema at Open, and so is a fingerprint that is not Equal to the stored one. A nil fingerprint accepts whatever the store is bound to, and a fingerprint given to an empty unbound store binds it (TestStoreBindsEmpty); an unbound store that holds records cannot be bound by Open, only by Migrate. The record’s own shape is versioned too: the log’s header and every record carry version 2, and Open refuses a log whose header carries any other version (ErrCorrupt), while TestRecordFormat’s version case shows ParseRecord rejecting a record that does, so a store written in another record shape is refused, never read by guess. Chapter 40’s daemon turns that refusal into a rebuild: a store vecdb refuses as corrupt is renamed aside and rebuilt from the journal.

Equal compares what the fingerprint says, and the incident of 2026-09-29 is the case where nothing it says changed. Chapter 21’s table shows it: the alias, the GGUF, the width (1,024), the norms and the latency were as before, every request returned 200 with 1,024 finite numbers, and the server’s preset had said pooling = cls, which made every text that began with the same token one vector, until the reader changed it to pooling = last at about 23:48. A fingerprint captured before and one captured after would differ in the pooling field, but only if someone wrote the pooling down, and only if the embedder were captured again. Check does not rely on either: it embeds the fingerprint’s probe texts through the live embedder and requires each cosine with the stored vector to be at least the fingerprint’s threshold. So Open runs both. Options.Embedder is the embedder that will feed the store; when it is set, Open runs Check on the store’s bound fingerprint and returns ErrSchema wrapping embedding.ErrMismatch when it fails. TestOpenRunsCheck shows both refusals on one store: an embedder that rotates every vector by one place has the same name, width and norms, Equal passes, Check refuses, and Open returns the error before the store is used. TestStoreBindsEmpty has the Equal refusal, a changed pooling string. A new store, or an unbound one being bound, checks too, so a fingerprint that the embedder does not reproduce is never written. Open decides everything before it writes anything: a torn tail is noted while the log is read and cut only after the width, metric, fingerprint and Check have passed, so a refused Open leaves the files as it found them (TestRecoveryChangesNothingUntilEveryCheckPasses). The check costs one embedding batch per Open (chapter 32’s live run of six probes against dixie took 243 ms); in a dual-read it checks the previous space against Options.Previous as well.

When the embedder has changed, the operator chooses a policy, and Migrate (listing ch34-migrate) carries it out.

Refuse is the default. Open fails and nothing moves, and Migrate(Refuse) does the same on a live store. It is the right answer for a store whose records cannot be re-derived, and it is what chapter 21’s jev-lite does with its probes: a student whose heads were fitted to one space must not answer in another, so its probe check refuses it.

Rebuild re-embeds every live record’s text into a new generation and switches CURRENT. It needs the text, so a store whose records carry none cannot rebuild, and says so with ErrNoText before anything is written. It needs the new embedder to be the one the new fingerprint describes, so it runs the Check on the new space first; a rebuild with an embedder that does not reproduce its own fingerprint would bind the store to a space it does not hold (TestMigrateRefusesAnEmbedderThatIsNotTheFingerprint). A vector from the new embedder that is the wrong width or non-finite stops the rebuild and removes the half-built generation (TestMigrateRefusesNonFiniteVectors). A cancelled context between batches does the same. The lab’s TestSchema compares, after the rebuild and after a dual-read, the stored vector of each of the 300 records with the one the new embedder gives its text, through Store.Get; and recall@10 of five queries against a fresh exact index over the new vectors is 1 besides.

Rebuild’s price is time and availability. Migrate holds the store’s lock for the whole job, so no search or add proceeds until it ends. The time is the embedder’s: at chapter 32’s measured median of 1,089.3 ms per request of 32 paragraphs, the fixture’s 1,018 records are 32 requests and about 35 seconds, and a million records are 31,250 requests and about 9.5 hours (arithmetic from that median, not a run). Honcho’s took one night (DECISIONS.md, 2026-09-30).

DualRead opens the new generation beside the old and moves up to 256 records per Migrate call, until the old generation holds nothing the new one lacks, then switches CURRENT and removes the old directory. While both exist: Add goes to the new generation, so the caller’s vector must come from the new embedder; Search reads the new generation only; Delete reaches both, the previous generation first, so that a failure between the two appends leaves the ID in the new generation only, as a delete not yet applied that a retry finishes, and never in the old generation only, where the migration would copy it back (TestDualDeleteOrder); Len counts distinct IDs, so it does not move while records move; and SearchText (listing ch34-search-text) embeds the query twice, once per space, searches each generation in its own space, and merges the two ranked lists. SearchText without Options.Previous returns ErrNoPrevious rather than answer from the new space alone, because that would drop every record not yet moved from the results for the whole migration, silently (exercise (f)). An interrupted migration reopens in the dual state, with the fingerprint checked against the new generation (TestDualRead closes in the middle and finishes after reopening).

Dual-read has a requirement that is easy to miss: the old embedder must still exist. That is true when a model is upgraded and the old one can be served beside the new. It was not true of the incident. A llama.cpp server’s --pooling is a flag of the process; honcho-embed served cls and then, after the fix, last, and no endpoint was left that embedded a query into the cls space. For that failure Rebuild (or Refuse) was the only way, and the book’s record agrees: Honcho’s store was being re-embedded on dixie overnight, and by 12:03 on 2026-09-30 dixie’s GPU was idle and the job had finished (DECISIONS.md, 2026-09-30). Beyond the records quoted here (pooling flag, whole store, overnight, dixie), this chapter says nothing of how Honcho scheduled the job or what it served meanwhile; its design is Honcho’s.

Why ranks. The merge cannot add scores. A cosine in one space says nothing about a cosine in another: for two independent unit vectors drawn uniformly from the sphere in Rd\mathbb{R}^d, E[(u⋅v)2]=∑i,jE[uiuj]E[vivj]=∑iE[ui2]E[vi2]=d⋅1d⋅1d=1dE[(u \cdot v)^2] = \sum_{i,j} E[u_i u_j]\,E[v_i v_j] = \sum_i E[u_i^2]\,E[v_i^2] = d \cdot \frac1d \cdot \frac1d = \frac1d (E[ui2]=1/dE[u_i^2] = 1/d because the dd squares are exchangeable and sum to 1), the terms with i≠ji \neq j vanishing because E[uiuj]=0E[u_i u_j] = 0 by the symmetry ui↦−uiu_i \mapsto -u_i of the sphere, so unrelated pairs scatter with a standard deviation of 1/d1/\sqrt{d}: 0.0625 at 256 dimensions and 0.0884 at 128. Two spaces of different widths do not share a scale, and two spaces of the same width need not either. Ranks, which any search returns, are comparable. Reciprocal rank fusion (Cormack, Clarke and Büttcher, SIGIR 2009) scores an ID by

score(d)=∑i1k+ri(d) \text{score}(d) = \sum_i \frac{1}{k + r_i(d)}

over the lists ii it appears in, ri(d)r_i(d) being its 1-based rank in list ii, and sorts by that. With k=60k = 60, the paper’s value, rank 1 in one list scores 1/611/61 and rank 2 scores 1/621/62, a ratio of 62/61=1.01662/61 = 1.016: the constant flattens the top of each list: an ID ranked rr in both lists scores 2/(60+r)2/(60 + r), which exceeds the 1/611/61 of an ID first in one list and absent from the other exactly when r<62r < 62, so agreement anywhere in the first 61 places beats a lone first place, which is the point of fusing (exercise (e) computes an example). The largest possible fused score is 2/(k+1)=0.03282/(k+1) = 0.0328, for an ID first in both lists, and TestDualRead checks that no hit exceeds it. Two things follow that the code does not hide. A record that has already moved is in both lists, because the old generation keeps it until the migration ends, so it can collect two votes while an unmoved one can collect one: the fused order drifts towards moved records as the job proceeds, which is acceptable because the new space is where they are going. And hits carry the fused score, which is a rank score and not a similarity; a caller that thresholds on cosine must not threshold on it.

What a kill proves and what it does not

crashloop starts the load subcommand in a child process on a fresh directory, kills it with SIGKILL after a random delay so that the kill lands anywhere in a write, opens the store and classifies what Open found: clean (the log ended on a record boundary), torn (a partial record was cut and reported) or corrupt (Open refused). A correct store under SyncEveryWrite produces the first two only. The table is below, from straylight: torn is 0 in all twenty rows, and 1 in a second run of 300.

That result needs two corrections to the obvious reading, and both come from the failure models at the top of the chapter.

A process kill does not test fsync. SIGKILL ends the process and leaves the kernel alone, so every write that completed is in the page cache and is read back by the next Open whether or not it was synced. Run with -sync snapshot, where Add never calls fsync, 100 kills on straylight (-runs 100 -n 200000 -seed 3, 8 microseconds per Add) ended runs=100 finished=0 clean=100 torn=0 corrupt=0 lost_acknowledged=0, with recovered equal to acked in 96 rows and one more in 4: the table has the same shape, because the page cache is what the next Open reads. What the loop tests is the ordering (the log is written before Add returns, and a record’s bytes are complete before the next begins) and the replay (Open reads back whatever the log holds). Durability across a power cut is not a thing a kill can test; it needs a machine that loses its page cache, which means a virtual machine killed from outside or a block device that drops unflushed writes. The tests that stand in for it here are the exhaustive ones above, which build the on-disk states a power cut could leave and check that Open does the right thing with each.

A kill can tear a write, and did. The comfortable explanation, that a write that has entered the kernel completes, is not what the kernel does: in Linux 6.12’s generic_perform_write (mm/filemap.c, line 4049) the loop that copies a write into the page cache one chunk at a time returns -EINTR and stops, with a short write, when fatal_signal_pending(current) is true at the top of an iteration. The chunk is a page unless the file system uses larger folios, and a record is not aligned to one: the loop’s records are 328 bytes at width 64, so about one append in thirteen (327/4096327/4096) straddles a page boundary, and a 1,024-wide record of 4,151 bytes always does. Row 284 of the 300-run is such a kill: the log was cut at byte 122,570 with 310 bytes after it, the front of a record that was never finished, and 122570+310=122880=30×4096122570 + 310 = 122880 = 30 \times 4096: what reached the log ended exactly on a page boundary. Open cut it and reported truncated=122570 dropped=310, acked and recovered were both 374, and nothing acknowledged was lost. One tear in 420 kills (320 under SyncEveryWrite, 100 under SyncOnSnapshot) is a measurement and not a predicted rate: this chapter does not derive one. It is also why torn=0 in the first twenty rows is not evidence that tears are impossible, and why the truncate-at-every-offset test, not the kill, is what shows that tears are handled.

What the table does show: no acknowledged record was ever lost (lost_acknowledged=0), and recovered is acked or acked plus one. The extra record is the one in flight: its write completed, the child was killed inside its fsync or before it printed the count, and it was recovered though never acknowledged. 270 of the 300 rows in the longer run, and 17 of 20 in the shown one, recovered one more than was acknowledged, which is what a cycle that spends almost all of its time inside fsync (0.250 to 0.284 ms of every cycle, above) would produce.

Walkthrough

The code, in the order a record meets it. The format first.

// The write-ahead log is a file header followed by records. Every number is
// little-endian.
//
//    file header   "AECW" u32 version(2)                                  8 bytes
//    record        "AECR" u8 version(2) u8 kind u16 0 u32 length         20 bytes
//                  u64 seq (1 for the first record of a log, then +1)
//                  payload: u32 n, n bytes of canonical JSON, then for an
//                  add record dim × float32 (the vector as raw bytes)
//                  u32 CRC-32C over the record header and the payload      4 bytes
//
// kind is 1 for an add and 2 for a delete. The JSON header is
// {"dim":D,"id":"…","meta":{…},"text":"…"} for an add (meta and text
// omitted when empty) and {"id":"…"} for a delete; canonical JSON (chapter
// 21's rules, internal/canon) so a record's bytes are a function of the
// record. The CRC is Castagnoli's polynomial (0x82f63b78, the one iSCSI
// and ext4 use), which detects every single-bit error, every burst of 32
// bits or fewer, and a random change with probability 1 − 2^−32; a record
// whose CRC fails is unreadable, not trusted. The sequence number is under
// the CRC: a record copied over another, two records swapped, or one
// duplicated is intact and out of sequence, which Replay refuses.
const (
    walMagic   = "AECW"
    recMagic   = "AECR"
    walVersion = 2
    walHeader  = 8
    recHeader  = 20
    kindAdd    = 1
    kindDelete = 2
    maxRecord  = 64 << 20 // a length over this is damage, not a record
)

var castagnoli = crc32.MakeTable(crc32.Castagnoli)

// ErrTooLarge is a record whose encoding would exceed the log's record limit
// (64 MiB): the reader treats a longer length as damage, so the writer must
// never produce one.
var ErrTooLarge = errors.New("vecdb: the record is larger than the log allows")

// WALRecord is one logged operation: a Record added, or (Delete set) an ID
// removed, in which case only Record.ID is meaningful.
type WALRecord struct {
    Seq    uint64 // position in the log, 1-based; set by the writer, checked by Replay
    Delete bool
    Record
}

// recordHeader is the JSON part of a record's payload.
type recordHeader struct {
    Dim  int               `json:"dim,omitempty"`
    ID   string            `json:"id"`
    Meta map[string]string `json:"meta,omitempty"`
    Text string            `json:"text,omitempty"`
}

// EncodeRecord renders one record as the bytes appended to the log.
func EncodeRecord(rec WALRecord) ([]byte, error) {
    if rec.ID == "" {
        return nil, ErrEmptyID
    }
    kind := byte(kindAdd)
    h := recordHeader{ID: rec.ID}
    if rec.Delete {
        kind = kindDelete
    } else {
        if len(rec.Vector) == 0 || len(rec.Vector) > maxDim {
            return nil, ErrDim
        }
        h.Dim, h.Meta, h.Text = len(rec.Vector), rec.Meta, rec.Text
    }
    hdr, err := canon.JSON(h)
    if err != nil {
        return nil, err
    }
    n := recHeader + 4 + len(hdr) + 4
    if !rec.Delete {
        n += 4 * len(rec.Vector)
    }
    if n-recHeader-4 > maxRecord {
        return nil, ErrTooLarge
    }
    buf := make([]byte, 0, n)
    buf = append(buf, recMagic...)
    buf = append(buf, walVersion, kind, 0, 0)
    buf = binary.LittleEndian.AppendUint32(buf, uint32(n-recHeader-4))
    buf = binary.LittleEndian.AppendUint64(buf, rec.Seq)
    buf = binary.LittleEndian.AppendUint32(buf, uint32(len(hdr)))
    buf = append(buf, hdr...)
    if !rec.Delete {
        for _, x := range rec.Vector {
            buf = binary.LittleEndian.AppendUint32(buf, math.Float32bits(x))
        }
    }
    return binary.LittleEndian.AppendUint32(buf, crc32.Checksum(buf, castagnoli)), nil
}

Replay, which decides between a torn tail and interior damage:

// Replay reads the log from offset from to its end and applies every intact
// record, which must carry the sequence numbers nextSeq, nextSeq+1, and so on.
// When a record is damaged it decides which of two events it is seeing. A
// torn write is at the tail: if no intact record follows the damage, the tail
// is cut at the last good record (good is where to truncate, dropped how many
// bytes go). If an intact record does follow, the damage is in the middle of
// the log, which a crash under SyncEveryWrite does not produce: that is media
// corruption or a foreign write, and cutting there would discard good records
// too, so Replay returns ErrCorrupt and the caller changes nothing on disk. An
// intact record whose sequence number is not the expected one was moved,
// swapped, duplicated or left over from another log; it is not a torn write
// wherever it sits, and is ErrCorrupt too.
func Replay(data []byte, from int64, nextSeq uint64, apply func(WALRecord) error) (replayed int, good int64, dropped int, err error) {
    if from < walHeader || from > int64(len(data)) {
        return 0, 0, 0, fmt.Errorf("%w: WAL offset %d outside the file (%d bytes)", ErrCorrupt, from, len(data))
    }
    off := int(from)
    for off < len(data) {
        rec, n, ok := ParseRecord(data[off:])
        if !ok {
            if nextIntact(data[off+1:]) {
                return replayed, int64(off), 0, fmt.Errorf("%w: a damaged record at byte %d is followed by intact records", ErrCorrupt, off)
            }
            return replayed, int64(off), len(data) - off, nil
        }
        if rec.Seq != nextSeq {
            return replayed, int64(off), 0, fmt.Errorf("%w: the record at byte %d has sequence %d, the log is at %d", ErrCorrupt, off, rec.Seq, nextSeq)
        }
        if err := apply(rec); err != nil {
            return replayed, int64(off), 0, err
        }
        off += n
        nextSeq++
        replayed++
    }
    return replayed, int64(off), 0, nil
}

// nextIntact reports whether any intact record starts anywhere in b.
func nextIntact(b []byte) bool {
    for at := 0; ; {
        i := bytes.Index(b[at:], []byte(recMagic))
        if i < 0 {
            return false
        }
        if _, _, ok := ParseRecord(b[at+i:]); ok {
            return true
        }
        at += i + 1
    }
}

The snapshot’s format and the contract it is read under:

// A snapshot is the whole index at one WAL offset, written to a temporary
// name, fsynced, renamed over the old snapshot, and the directory fsynced
// (POSIX rename is atomic: a reader sees the old file or the new one, never
// a mixture). Layout, little-endian:
//
//    "AECS" u32 version(2)
//    u32 n, n bytes of JSON {"wal_offset":…, "wal_seq":…,
//                            "kind":"flat"|"hnsw", "records":…}
//    the index: Flat's or HNSW's encoding
//    u32 CRC-32C over everything before it
//
// Open reads the snapshot, verifies the CRC before decoding a byte of it,
// decodes with every count checked against the stream, then walks the log
// from its header to wal_offset and replays what follows. The walk must land
// on wal_offset exactly after the record numbered wal_seq. A snapshot whose
// offset lies beyond the log's end describes records the log no longer
// holds; one whose offset is inside a record, or after more records than it
// claims, was written against a different log: all ErrCorrupt rather than
// silently accepted.
const (
    snapMagic   = "AECS"
    snapVersion = 2
)

type snapshotHeader struct {
    WALOffset int64  `json:"wal_offset"`
    WALSeq    uint64 `json:"wal_seq"`
    Kind      string `json:"kind"`
    Records   int    `json:"records"`
}

The directory layout and CURRENT:

// A Store is a directory. CURRENT names the live generation (and, during a
// dual-read migration, the one being left); each generation is a
// subdirectory holding its own meta.json (dim, metric, graph parameters),
// fingerprint.json (the embedding space, when bound), wal and snapshot.
// A rebuild writes a whole new generation and then switches CURRENT with
// one atomic rename, so an interrupted migration leaves the old generation
// untouched and the half-built one unreferenced. LOCK is the owner lock: an
// exclusive flock held from Open to Close. CURRENT, meta.json and
// fingerprint.json are JSON followed by a line holding their CRC-32C.
//
//    Dir/LOCK                 held by the process that owns the store
//    Dir/CURRENT              {"generation":"g2","previous":"g1","next":3}
//    Dir/g1/meta.json         {"dim":256,"metric":0,"params":{…}}
//    Dir/g1/fingerprint.json  embedding.Fingerprint
//    Dir/g1/wal               the write-ahead log
//    Dir/g1/snapshot          the index at a WAL offset
type current struct {
    Generation string `json:"generation"`
    Previous   string `json:"previous,omitempty"`
    Next       int    `json:"next"`
}

type genMeta struct {
    Dim    int        `json:"dim"`
    Metric Metric     `json:"metric"`
    Params HNSWParams `json:"params"`
}

Open:

// Open opens or creates the store, and owns it until Close: it takes an
// exclusive lock on Dir/LOCK first, and ErrBusy means another Open holds it.
// A new store takes its width from Options.Dim (or the fingerprint's). An
// existing one is checked against the options: a different Dim or Metric,
// non-zero Params that differ, or a Fingerprint that is not Equal to the one
// on disk is ErrSchema (Migrate is the way past it); a nil Fingerprint
// accepts whatever the store is bound to, and a Fingerprint given to an empty
// unbound store binds it. When Options.Embedder is set, the bound fingerprint
// is also Checked against it: Equal compares what the fingerprint says, and
// only Check sees a space that changed behind the same names. The snapshot is
// loaded and the WAL replayed; only when every check has passed is a torn tail
// cut from the file, so a refused Open changes nothing. What was found is in
// Recovery.
func Open(opts Options) (*Store, error) {
    if opts.Dir == "" {
        return nil, errors.New("vecdb: Options.Dir is empty")
    }
    if opts.Fingerprint != nil {
        if opts.Dim == 0 {
            opts.Dim = opts.Fingerprint.Dim
        } else if opts.Dim != opts.Fingerprint.Dim {
            return nil, fmt.Errorf("%w: Options.Dim %d, fingerprint dim %d", ErrSchema, opts.Dim, opts.Fingerprint.Dim)
        }
    }
    if opts.Clock == nil {
        opts.Clock = time.Now
    }
    if _, err := os.Stat(opts.Dir); os.IsNotExist(err) {
        if opts.Dim <= 0 || opts.Dim > maxDim {
            return nil, errors.New("vecdb: a new store needs Options.Dim or a Fingerprint")
        }
        if err := os.MkdirAll(opts.Dir, 0o700); err != nil {
            return nil, err
        }
        if err := syncDir(filepath.Dir(filepath.Clean(opts.Dir))); err != nil {
            return nil, err
        }
    } else if err != nil {
        return nil, err
    }
    lock, err := lockDir(opts.Dir)
    if err != nil {
        return nil, err
    }
    s, err := openLocked(opts)
    if err != nil {
        lock.Close()
        return nil, err
    }
    s.lock = lock
    return s, nil
}

func openLocked(opts Options) (*Store, error) {
    s := &Store{opts: opts, rec: Recovery{TruncatedAt: -1}}
    err := readChecked(filepath.Join(opts.Dir, "CURRENT"), &s.state)
    switch {
    case os.IsNotExist(err):
        if opts.Dim <= 0 || opts.Dim > maxDim {
            return nil, errors.New("vecdb: a new store needs Options.Dim or a Fingerprint")
        }
        if err := emptyDir(opts.Dir); err != nil {
            return nil, err
        }
        if err := checkSpace(context.Background(), opts.Fingerprint, opts.Embedder); err != nil {
            return nil, err
        }
        g, err := s.createGeneration("g1", genMeta{opts.Dim, opts.Metric, opts.Params}, opts.Fingerprint)
        if err != nil {
            return nil, err
        }
        s.state = current{Generation: "g1", Next: 2}
        if err := s.writeCurrent(); err != nil {
            g.wal.Close()
            return nil, err
        }
        s.cur = g
        return s, nil
    case err != nil:
        return nil, err
    }
    if !validCurrent(s.state) {
        return nil, fmt.Errorf("%w: CURRENT", ErrCorrupt)
    }
    cur, err := s.openGeneration(s.state.Generation, &s.rec)
    if err != nil {
        return nil, err
    }
    var prev *generation
    fail := func(err error) (*Store, error) {
        cur.wal.Close()
        if prev != nil {
            prev.wal.Close()
        }
        return nil, err
    }
    if opts.Dim != 0 && opts.Dim != cur.meta.Dim {
        return fail(fmt.Errorf("%w: the store is %d wide, Options.Dim is %d", ErrSchema, cur.meta.Dim, opts.Dim))
    }
    if opts.Metric != cur.meta.Metric {
        return fail(fmt.Errorf("%w: the store uses %s, Options.Metric is %s", ErrSchema, cur.meta.Metric, opts.Metric))
    }
    if !opts.Params.IsZero() && opts.Params != cur.meta.Params {
        return fail(fmt.Errorf("%w: the store's graph parameters differ from Options.Params", ErrSchema))
    }
    bind := false
    if opts.Fingerprint != nil {
        switch {
        case cur.fp == nil && cur.idx.Len() == 0:
            if err := checkSpace(context.Background(), opts.Fingerprint, opts.Embedder); err != nil {
                return fail(err)
            }
            bind = true
        case cur.fp == nil:
            return fail(fmt.Errorf("%w: the store is unbound and holds %d records; Migrate(Rebuild) binds it", ErrSchema, cur.idx.Len()))
        case !cur.fp.Equal(opts.Fingerprint):
            return fail(fmt.Errorf("%w: store %s/%s dim %d, embedder %s/%s dim %d", ErrSchema,
                cur.fp.Name, cur.fp.Model, cur.fp.Dim, opts.Fingerprint.Name, opts.Fingerprint.Model, opts.Fingerprint.Dim))
        }
    }
    if err := checkSpace(context.Background(), cur.fp, opts.Embedder); err != nil {
        return fail(err)
    }
    var prevRec Recovery
    if s.state.Previous != "" {
        prev, err = s.openGeneration(s.state.Previous, &prevRec)
        if err != nil {
            return fail(err)
        }
        if err := checkSpace(context.Background(), prev.fp, opts.Previous); err != nil {
            return fail(err)
        }
    }
    // Every check has passed: now the files may change.
    if bind {
        if err := writeFingerprint(cur.dir, opts.Fingerprint); err != nil {
            return fail(err)
        }
        cur.fp = opts.Fingerprint
    }
    if err := cur.cut(&s.rec); err != nil {
        return fail(err)
    }
    if prev != nil {
        if err := prev.cut(&prevRec); err != nil {
            return fail(err)
        }
        s.rec.Replayed += prevRec.Replayed
        if s.rec.TruncatedAt < 0 && prevRec.TruncatedAt >= 0 {
            s.rec.TruncatedAt, s.rec.Dropped = prevRec.TruncatedAt, prevRec.Dropped
        }
    }
    s.cur, s.prev = cur, prev
    return s, nil
}

openGeneration, the recovery:

// openGeneration loads a generation: meta, fingerprint, the snapshot if
// there is one (else an empty index), then the WAL from the snapshot's
// offset. It reads and decides; it does not write: a torn tail is noted in
// the generation and cut by cut() when Open has finished its checks. Interior
// damage and out-of-sequence records are ErrCorrupt (see Replay). A record
// that passed its checksum but that no correct writer logs (the wrong width,
// a NaN, a delete of an unknown id) is ErrCorrupt too.
func (s *Store) openGeneration(name string, rec *Recovery) (*generation, error) {
    dir := filepath.Join(s.opts.Dir, name)
    var meta genMeta
    if err := readChecked(filepath.Join(dir, "meta.json"), &meta); err != nil {
        if os.IsNotExist(err) {
            return nil, fmt.Errorf("%w: %s/meta.json is missing", ErrCorrupt, name)
        }
        return nil, err
    }
    if meta.Dim <= 0 || meta.Dim > maxDim || meta.Metric < Cosine || meta.Metric > L2 ||
        meta.Params.M < 0 || meta.Params.Mmax0 < 0 || meta.Params.EfConstruction < 0 || meta.Params.Ef < 0 {
        return nil, fmt.Errorf("%w: %s/meta.json", ErrCorrupt, name)
    }
    g := &generation{name: name, dir: dir, meta: meta}
    fp := new(embedding.Fingerprint)
    switch err := readChecked(filepath.Join(dir, "fingerprint.json"), fp); {
    case err == nil:
        g.fp = fp
        if g.fp.Dim != meta.Dim {
            return nil, fmt.Errorf("%w: %s: fingerprint dim %d, meta dim %d", ErrCorrupt, name, g.fp.Dim, meta.Dim)
        }
    case !os.IsNotExist(err):
        return nil, err
    }
    idx, hdr, found, err := readSnapshot(dir)
    if err != nil {
        return nil, err
    }
    wal, data, err := openWAL(filepath.Join(dir, "wal"), false)
    if err != nil {
        return nil, err
    }
    from := int64(walHeader)
    if found {
        if idx.Dim() != meta.Dim || !snapshotMatches(idx, meta) {
            wal.Close()
            return nil, fmt.Errorf("%w: %s: the snapshot is not the index meta.json describes", ErrCorrupt, name)
        }
        if hdr.WALOffset < walHeader || hdr.WALOffset > int64(len(data)) {
            wal.Close()
            return nil, fmt.Errorf("%w: %s: the snapshot is at WAL byte %d, the log has %d", ErrCorrupt, name, hdr.WALOffset, len(data))
        }
        // The snapshot's claim about the log is checked against the log: the
        // intact records from the header to its offset must be numbered 1 to
        // wal_seq and end exactly there. An offset inside a record would
        // otherwise read as a torn tail and cut a good record; one past a
        // record the snapshot does not hold would skip it.
        off, n := int64(walHeader), uint64(0)
        for off < hdr.WALOffset {
            r, sz, ok := ParseRecord(data[off:])
            if !ok || r.Seq != n+1 {
                break
            }
            off += int64(sz)
            n++
        }
        if off != hdr.WALOffset || n != hdr.WALSeq {
            wal.Close()
            return nil, fmt.Errorf("%w: %s: the snapshot says records up to sequence %d end at WAL byte %d; the log has %d in sequence ending at byte %d", ErrCorrupt, name, hdr.WALSeq, hdr.WALOffset, n, off)
        }
        g.idx, from, g.walSeq, rec.Snapshot = idx, hdr.WALOffset, hdr.WALSeq, true
    } else {
        g.idx = newIndex(meta)
    }
    replayed, good, dropped, err := Replay(data, from, g.walSeq+1, func(wr WALRecord) error {
        r := wr.Record
        if wr.Delete {
            if err := g.idx.Delete(r.ID); err != nil {
                return fmt.Errorf("%w: WAL deletes %q, which the index does not hold", ErrCorrupt, r.ID)
            }
            return nil
        }
        if len(r.Vector) != meta.Dim {
            return fmt.Errorf("%w: WAL record %q is %d wide, the store %d", ErrCorrupt, r.ID, len(r.Vector), meta.Dim)
        }
        if !finite(r.Vector) {
            return fmt.Errorf("%w: WAL record %q holds a NaN or infinite component", ErrCorrupt, r.ID)
        }
        if err := g.idx.Add(r); err != nil {
            return fmt.Errorf("%w: WAL record %q: %v", ErrCorrupt, r.ID, err)
        }
        return nil
    })
    if err != nil {
        wal.Close()
        return nil, err
    }
    rec.Replayed += replayed
    g.walSeq += uint64(replayed)
    g.since = replayed // a clean Close snapshots what was replayed, so the next start replays nothing
    g.wal, g.walLen, g.dropped = wal, good, dropped
    return g, nil
}

Migrate:

// Migrate is what happens when the embedder's space (fp) is not the
// store's. Refuse returns ErrSchema and changes nothing (Open's default,
// D8). Rebuild re-embeds every live record's Text with e into a new
// generation and switches CURRENT to it in one rename; records without Text
// make it ErrNoText before anything is written, e that does not reproduce
// fp's probes makes it ErrSchema before anything is written, and a cancelled
// ctx leaves the old generation live and removes the half-built one. The new
// generation holds live records only, so the old one's tombstones go with
// it. DualRead opens the new generation beside the old and moves up to
// dualBatch records per call; until Remaining reaches 0 the store answers
// SearchText from both spaces. A fingerprint Equal to the store's is a no-op
// report.
func (s *Store) Migrate(ctx context.Context, e embedding.Embedder, fp *embedding.Fingerprint, p SchemaPolicy) (MigrateReport, error) {
    start := s.opts.Clock()
    s.mu.Lock()
    defer s.mu.Unlock()
    rep := MigrateReport{Policy: p, From: fpModel(s.cur.fp), To: fpModel(fp)}
    if s.closed {
        return rep, ErrClosed
    }
    if s.prev != nil {
        if p != DualRead {
            return rep, ErrMigrating
        }
        if fp == nil || !s.cur.fp.Equal(fp) {
            return rep, fmt.Errorf("%w: the migration in progress is to %s", ErrSchema, fpModel(s.cur.fp))
        }
        // Every step is checked: an embedder that fails the fingerprint
        // (a wrong pooling, a swapped model) would move records into the wrong
        // space, and a continuation call is as likely to be handed one as the first.
        if err := checkSpace(ctx, s.cur.fp, e); err != nil {
            return rep, err
        }
        return s.dualStep(ctx, e, rep, start)
    }
    if s.cur.fp.Equal(fp) {
        rep.Duration = s.opts.Clock().Sub(start)
        return rep, nil
    }
    switch p {
    case Refuse:
        return rep, fmt.Errorf("%w: store %s, embedder %s", ErrSchema, rep.From, rep.To)
    case Rebuild, DualRead:
    default:
        return rep, fmt.Errorf("vecdb: unknown SchemaPolicy %d", p)
    }
    if fp == nil || e == nil {
        return rep, errors.New("vecdb: Rebuild and DualRead need the new embedder and its fingerprint")
    }
    if !allHaveText(s.cur.idx) {
        return rep, ErrNoText
    }
    // The new space is verified before anything is written: a store rebuilt
    // with an embedder that does not reproduce its own fingerprint would be
    // bound to a space it does not hold.
    if err := checkSpace(ctx, fp, e); err != nil {
        return rep, err
    }
    // The generation number is consumed even if the build fails, so a stale
    // half-built directory is never reopened as a live one.
    name := fmt.Sprintf("g%d", s.state.Next)
    s.state.Next++
    if err := s.writeCurrent(); err != nil {
        return rep, err
    }
    meta := genMeta{Dim: fp.Dim, Metric: s.cur.meta.Metric, Params: s.cur.meta.Params}
    g, err := s.createGeneration(name, meta, fp)
    if err != nil {
        return rep, err
    }
    if p == DualRead {
        s.state = current{Generation: name, Previous: s.cur.name, Next: s.state.Next}
        if err := s.writeCurrent(); err != nil {
            g.wal.Close()
            os.RemoveAll(g.dir)
            return rep, err
        }
        s.prev, s.cur = s.cur, g
        return s.dualStep(ctx, e, rep, start)
    }
    // Rebuild: every record, in batches, into the new generation.
    var batch []Record
    flush := func() error {
        if len(batch) == 0 {
            return nil
        }
        if err := ctx.Err(); err != nil {
            return err
        }
        vecs, err := reembed(ctx, e, fp, batch)
        if err != nil {
            return err
        }
        for i, r := range batch {
            r.Vector = vecs[i]
            if err := validate(r, fp.Dim); err != nil {
                return fmt.Errorf("%w: the embedder's vector for %q: %w", ErrSchema, r.ID, err)
            }
            if err := s.appendTo(g, kindAdd, r); err != nil {
                return err
            }
            rep.Rebuilt++
        }
        batch = batch[:0]
        return nil
    }
    var ferr error
    each(s.cur.idx, func(r Record) bool {
        batch = append(batch, r)
        if len(batch) == migrateBatch {
            ferr = flush()
        }
        return ferr == nil
    })
    if ferr == nil {
        ferr = flush()
    }
    if ferr == nil {
        ferr = s.snapshot(g) // syncs the log, then writes the snapshot
    }
    if ferr != nil {
        g.wal.Close()
        os.RemoveAll(g.dir) // the old generation is still CURRENT and untouched
        rep.Rebuilt = 0
        return rep, ferr
    }
    s.state = current{Generation: name, Next: s.state.Next}
    if err := s.writeCurrent(); err != nil {
        g.wal.Close()
        os.RemoveAll(g.dir)
        rep.Rebuilt = 0
        return rep, err
    }
    old := s.cur
    s.cur = g
    old.wal.Close()
    os.RemoveAll(old.dir)
    rep.Duration = s.opts.Clock().Sub(start)
    return rep, nil
}

SearchText and the fusion:

// SearchText embeds text with e (as given: the caller applies Query or
// Document) and searches the live generation. During a dual-read migration
// it also embeds text with Options.Previous, searches the old generation in
// its own space, and merges the two lists by reciprocal rank fusion,
// score(id) = Σ 1/(rrfK + rank), because a cosine in one space says nothing
// about a cosine in another. Hits carry the fused score.
func (s *Store) SearchText(ctx context.Context, e embedding.Embedder, text string, k int, fl Filter) ([]Hit, error) {
    q, err := e.Embed(ctx, []string{text})
    if err != nil {
        return nil, err
    }
    if len(q) != 1 {
        return nil, fmt.Errorf("vecdb: embedder returned %d vectors for one text", len(q))
    }
    s.mu.Lock()
    prev := s.prev
    previous := s.opts.Previous
    s.mu.Unlock()
    if prev == nil {
        return s.Search(q[0], k, fl)
    }
    if previous == nil {
        return nil, ErrNoPrevious
    }
    pq, err := previous.Embed(ctx, []string{text})
    if err != nil {
        return nil, err
    }
    if len(pq) != 1 {
        return nil, fmt.Errorf("vecdb: previous embedder returned %d vectors for one text", len(pq))
    }
    s.mu.Lock()
    defer s.mu.Unlock()
    if s.closed {
        return nil, ErrClosed
    }
    if s.prev == nil { // the migration finished while we embedded
        return s.cur.idx.Search(q[0], k, fl)
    }
    newHits, err := s.cur.idx.Search(q[0], k, fl)
    if err != nil {
        return nil, err
    }
    oldHits, err := s.prev.idx.Search(pq[0], k, fl)
    if err != nil {
        return nil, err
    }
    return fuse(k, newHits, oldHits), nil
}

// fuse merges ranked lists by reciprocal rank fusion and returns the k best.
func fuse(k int, lists ...[]Hit) []Hit {
    score := map[string]float64{}
    meta := map[string]map[string]string{}
    for _, l := range lists {
        for rank, h := range l {
            score[h.ID] += 1 / float64(rrfK+rank+1)
            if _, ok := meta[h.ID]; !ok {
                meta[h.ID] = h.Meta
            }
        }
    }
    out := make([]Hit, 0, len(score))
    for id, sc := range score {
        out = append(out, Hit{ID: id, Score: float32(sc), Meta: meta[id]})
    }
    sort.Slice(out, func(i, j int) bool { return better(out[i].Score, out[i].ID, out[j].Score, out[j].ID) })
    if len(out) > k {
        out = out[:k]
    }
    return out
}

The two commands that measured the disk and the kill:

// fsync times one Add under each SyncPolicy on the given disk: with
// SyncEveryWrite every record waits for the device, with SyncOnSnapshot the
// write returns from the page cache and the device is waited for once, at
// the snapshot. The two numbers are the price of the durability guarantee
// per record and name the host's disk, not the code.
func fsyncCmd(args []string) error {
    fs := flag.NewFlagSet("fsync", flag.ExitOnError)
    dir := fs.String("dir", "", "a directory on the disk to measure (two stores are created under it)")
    n := fs.Int("n", 1000, "records")
    dim := fs.Int("dim", 1024, "width")
    fs.Parse(args)
    if *dir == "" {
        return errors.New("-dir is required")
    }
    pts, _ := vecdb.Synthetic(5, *n, 0, *dim, 1, 0.5)
    enc, err := vecdb.EncodeRecord(vecdb.WALRecord{Record: vecdb.Record{ID: fmt.Sprintf("r%06d", 0), Vector: pts[0]}})
    if err != nil {
        return err
    }
    recBytes := len(enc)
    for _, pol := range []struct {
        name string
        p    vecdb.SyncPolicy
    }{{"every", vecdb.SyncEveryWrite}, {"snapshot", vecdb.SyncOnSnapshot}} {
        d := filepath.Join(*dir, "fsync-"+pol.name)
        os.RemoveAll(d)
        s, err := vecdb.Open(vecdb.Options{Dir: d, Dim: *dim, Sync: pol.p})
        if err != nil {
            return err
        }
        lat := make([]float64, *n)
        t0 := time.Now()
        for i, v := range pts {
            t1 := time.Now()
            if err := s.Add(vecdb.Record{ID: fmt.Sprintf("r%06d", i), Vector: v}); err != nil {
                return err
            }
            lat[i] = msf(time.Since(t1))
        }
        total := time.Since(t0)
        t2 := time.Now()
        if err := s.Close(); err != nil {
            return err
        }
        sort.Float64s(lat)
        fmt.Printf("sync=%-8s n=%d dim=%d  add p50=%.3fms p99=%.3fms  total=%.2fs  close(snapshot)=%.1fms  record=%d bytes\n",
            pol.name, *n, *dim, lat[*n/2], lat[*n*99/100], total.Seconds(), msf(time.Since(t2)), recBytes)
        os.RemoveAll(d)
    }
    return nil
}
// crashloop is the process-level recovery test: -runs times it starts this
// binary's load subcommand on a fresh directory, kills it with SIGKILL
// after a random delay (so the kill lands anywhere in a write), opens the
// store and classifies what Open found: clean (the log ended on a record
// boundary), torn (a partial record was cut and reported), or corrupt (Open
// refused). With SyncEveryWrite the first two are the only outcomes a
// correct implementation produces; a corrupt result is a bug in the store,
// not in the disk. A killed process leaves the kernel's page cache alone, so
// the loop does not test fsync (it would print the same table without it); it
// tests that a record is in the log before Add returns and that Open reads
// back what the log holds. recovered is acked, or acked plus the one record
// in flight. The loop runs under tools/remote/straylight.sh and its
// output is pasted into chapter 34, named by host.
func crashloopCmd(args []string) error {
    fs := flag.NewFlagSet("crashloop", flag.ExitOnError)
    dir := fs.String("dir", "", "working directory (one subdirectory per run)")
    runs := fs.Int("runs", 20, "runs")
    n := fs.Int("n", 2000, "records the child tries to write")
    dim := fs.Int("dim", 64, "width")
    seed := fs.Uint64("seed", 1, "delay seed")
    syncName := fs.String("sync", "every", "the child's policy: every or snapshot")
    minDelay := fs.Duration("min", 5*time.Millisecond, "shortest delay before the kill")
    maxDelay := fs.Duration("max", 200*time.Millisecond, "longest delay before the kill")
    fs.Parse(args)
    if *dir == "" {
        return errors.New("-dir is required")
    }
    self, err := os.Executable()
    if err != nil {
        return err
    }
    r := rand.New(rand.NewPCG(*seed, 99))
    var clean, torn, corrupt, finished, lost int
    fmt.Printf("%-4s %-9s %-8s %-9s %-9s %-8s %-11s %-8s\n", "run", "delay", "exit", "acked", "recovered", "snapshot", "truncated", "dropped")
    for i := 0; i < *runs; i++ {
        d := filepath.Join(*dir, fmt.Sprintf("run%02d", i))
        os.RemoveAll(d)
        cmd := exec.Command(self, "load", "-dir", d, "-n", fmt.Sprint(*n), "-dim", fmt.Sprint(*dim), "-sync", *syncName)
        cmd.Stderr = os.Stderr
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            return err
        }
        if err := cmd.Start(); err != nil {
            return err
        }
        acked := make(chan int, 1)
        go func() { // the last count the child printed before it died
            last, sc := 0, bufio.NewScanner(stdout)
            for sc.Scan() {
                fmt.Sscan(sc.Text(), &last)
            }
            acked <- last
        }()
        delay := *minDelay + time.Duration(r.Int64N(int64(*maxDelay-*minDelay)))
        timer := time.NewTimer(delay)
        done := make(chan error, 1)
        go func() { done <- cmd.Wait() }()
        exit := "killed"
        select {
        case <-timer.C:
            cmd.Process.Signal(syscall.SIGKILL)
            <-done
        case err := <-done:
            timer.Stop()
            exit = "finished"
            finished++
            _ = err
        }
        ack := <-acked
        s, err := vecdb.Open(vecdb.Options{Dir: d, Dim: *dim})
        if err != nil {
            corrupt++
            fmt.Printf("%-4d %-9s %-8s CORRUPT: %v\n", i, delay.Round(time.Millisecond), exit, err)
            continue
        }
        rec := s.Recovery()
        if rec.TruncatedAt >= 0 {
            torn++
        } else {
            clean++
        }
        if s.Len() < ack {
            lost++
        }
        fmt.Printf("%-4d %-9s %-8s %-9d %-9d %-8v %-11d %-8d\n", i, delay.Round(time.Millisecond), exit, ack, s.Len(), rec.Snapshot, rec.TruncatedAt, rec.Dropped)
        s.Close()
        os.RemoveAll(d)
    }
    fmt.Printf("runs=%d finished=%d clean=%d torn=%d corrupt=%d lost_acknowledged=%d\n", *runs, finished, clean, torn, corrupt, lost)
    if corrupt > 0 || lost > 0 {
        return fmt.Errorf("%d runs recovered as corrupt, %d lost an acknowledged record", corrupt, lost)
    }
    return nil
}

The fixture store, and a record’s bytes

Chapter 32’s fixture is 1,018 Iliad paragraphs with 1,024-wide honcho-embed vectors. build makes a store from it: an HNSW graph at M = 16 with DefaultParams (seed 0), SyncEveryWrite, the fingerprint bound, and a snapshot at Close. Run from go/ on talos:

go run ./cmd/aec-vecdb build -dir STORE
graph: nodes=1018 edges=16933 max_layer=2 distances=843198
built 1018 records in 565ms (sync=every), closed with a snapshot

The graph is chapter 33’s graph: aec-vecdb bench on the same vectors with -seed 0 -M 16 reports edges=16933 and distances during build=843198, the same two numbers. (Chapter 33’s tables use seed 1, which is why they say 17,315 edges.) The directory holds an empty LOCK, a 45-byte CURRENT (the JSON {"generation":"g1","next":2} and a crc32c: line), and in g1/ a 193-byte meta.json, a 78,329-byte fingerprint.json, a 4,992,075-byte wal and a 5,039,010-byte snapshot. The snapshot is slightly larger than the log it summarises, because it holds the graph’s links as well as the same vectors.

The first 112 bytes of the log, from od -A d -t x1z -N 112 STORE/g1/wal:

0000000 41 45 43 57 02 00 00 00 41 45 43 52 02 01 00 00  >AECW....AECR....<
0000016 a5 11 00 00 01 00 00 00 00 00 00 00 a1 01 00 00  >................<
0000032 7b 22 64 69 6d 22 3a 31 30 32 34 2c 22 69 64 22  >{"dim":1024,"id"<
0000048 3a 22 70 30 30 30 30 22 2c 22 6d 65 74 61 22 3a  >:"p0000","meta":<
0000064 7b 22 62 6f 6f 6b 22 3a 22 31 22 7d 2c 22 74 65  >{"book":"1"},"te<
0000080 78 74 22 3a 22 53 69 6e 67 2c 20 4f 20 67 6f 64  >xt":"Sing, O god<
0000096 64 65 73 73 2c 20 74 68 65 20 61 6e 67 65 72 20  >dess, the anger <
0000112

Bytes 0 to 7 are the file header: 41 45 43 57 is AECW, and 02 00 00 00 is version 2 as a little-endian u32. The first record starts at byte 8. 41 45 43 52 is AECR; then the version byte 02, the kind byte 01 (an add), and two zero bytes. At byte 16, a5 11 00 00 is the payload length 0x11a5 = 4,517; at byte 20, 01 00 00 00 00 00 00 00 is the sequence number, 1, as a little-endian u64; at byte 28, a1 01 00 00 is the JSON length 0x01a1 = 417. The canonical JSON begins at byte 32: {"dim":1024,"id":"p0000","meta":{"book":"1"},"text":"Sing, O goddess, th…, keys in sorted order. The payload is 4+417+4096=45174 + 417 + 4096 = 4517 bytes, which is the length field’s own value, and the whole record is 20+4517+4=454120 + 4517 + 4 = 4541 bytes. Every byte but the two lengths, the sequence number and the paragraph’s text is fixed by the format.

A query, with and without a filter

query -i 3 -k 5 ranks the store’s answers to the fixture’s fourth query, q04, “Who kills Patroclus?”, whose answer lies in Book XVI; -book 16 adds Match(book=16):

query q04: "Who kills Patroclus?"
 1  0.7333  p0668  book 16  Patroclus now cut off the battalions that were nearest to him and drove them back to the ships. They were doing their best to reach the city, but he would not l…
 2  0.6884  p0689  book 16  With this the god went back into the hurly-burly, and Hector bade Cebriones drive again into the fight. Apollo passed in among them, and struck panic into the A…
 3  0.6853  p0761  book 18  Thus spoke Hector; and the Trojans, fools that they were, shouted in applause, for Pallas Minerva had robbed them of their understanding. They gave ear to Hecto…
 4  0.6852  p0800  book 19  Briseis, fair as Venus, when she saw the mangled body of Patroclus, flung herself upon it and cried aloud, tearing her breast, her neck, and her lovely face wit…
 5  0.6711  p0647  book 16  Thus did they fight about the ship of Protesilaus. Then Patroclus drew near to Achilles with tears welling from his eyes, as from some spring whose crystal stre…
query q04: "Who kills Patroclus?"
 1  0.7333  p0668  book 16  Patroclus now cut off the battalions that were nearest to him and drove them back to the ships. They were doing their best to reach the city, but he would not l…
 2  0.6884  p0689  book 16  With this the god went back into the hurly-burly, and Hector bade Cebriones drive again into the fight. Apollo passed in among them, and struck panic into the A…
 3  0.6711  p0647  book 16  Thus did they fight about the ship of Protesilaus. Then Patroclus drew near to Achilles with tears welling from his eyes, as from some spring whose crystal stre…
 4  0.6677  p0680  book 16  At first the Trojans made some headway against the Achaeans, for one of the best men among the Myrmidons was killed, Epeigeus, son of noble Agacles who had erew…
 5  0.6557  p0692  book 16  Then, as the life ebbed out of you, you answered, O knight Patroclus: “Hector, vaunt as you will, for Jove the son of Saturn and Apollo have vouchsafed you vi…

The top two hits are the same. Ranks 3 and 4 of the unfiltered list are Book XVIII and Book XIX paragraphs, and the filter replaces them with two Book XVI paragraphs that scored lower and were outside the unfiltered five, p0680 (0.6677) and p0692 (0.6557). p0692 is the paragraph in which Patroclus answers Hector as his life ebbs out: it is the answer, and it is ninth in the unfiltered ranking (-k 12) and fifth under the filter. A filter by itself does not make retrieval better; it removes candidates from other books, which here happens to remove two paragraphs that were not the answer and promote one that is.

Recovery by hand

A clean store reports what Close left, a snapshot and nothing to replay:

generation=g1 previous="" records=1018 dim=1024 snapshot=true replayed=0 truncated_at=-1 dropped=0

A torn tail: copy the store, remove its snapshot so recovery has only the log, and cut the last 5 bytes of the log (4,992,075 bytes before, 4,986,846 after the first recovery):

cp -r STORE TORN && rm TORN/g1/snapshot && truncate -s -5 TORN/g1/wal
go run ./cmd/aec-vecdb recover -dir TORN
go run ./cmd/aec-vecdb recover -dir TORN
generation=g1 previous="" records=1017 dim=1024 snapshot=false replayed=1017 truncated_at=4986846 dropped=5224
generation=g1 previous="" records=1017 dim=1024 snapshot=true replayed=0 truncated_at=-1 dropped=0

The first run replays 1,017 records, finds 5,224 bytes that are the front of a record whose last 5 bytes are missing, and cuts them at byte 4,986,846. The last record was 5,229 bytes long, and 5229−5=52245229 - 5 = 5224. The second run finds nothing to cut, and no log to replay: the first run’s Close snapshotted the 1,017 records it had recovered, so the second loads that snapshot (snapshot=true replayed=0). The cut happened once, on the file.

Interior damage: copy the store again, remove the snapshot, and overwrite byte 40 (inside the first record’s JSON header, the 0 of the width 1024) with a zero, using a ten-line program of the reader’s own that opens the file and calls WriteAt([]byte{0}, 40):

aec-vecdb: vecdb: snapshot or WAL header is corrupt: a damaged record at byte 8 is followed by intact records

The command exits 1. The record at byte 8 is damaged and 1,017 intact records follow it, so nothing is cut. cmp -l of the log against the original lists one byte, 41 (1-based), changed from 060 (octal for 0) to 0: Open left the file as it found it.

Opening from a snapshot and from the log

The same store opened three times each way on talos (recover -time):

snapshot log only
open took 21 ms, 22 ms, 18 ms 546 ms, 572 ms, 543 ms

The log-only column is the build of chapter 33 again: 565 ms for the build above on the same host.

The disk

aec-vecdb fsync on straylight, in a directory on its ext4 volume (three runs; the first is shown verbatim and the other two gave add p50=0.284ms p99=0.432ms and add p50=0.254ms p99=0.402ms for sync=every, and add p50=0.008ms p99=0.056ms and add p50=0.006ms p99=0.025ms for sync=snapshot):

tools/remote/straylight.sh 5b-t4 -- go -C go run ./cmd/aec-vecdb fsync -dir fsync-run -n 1000 -dim 1024
sync=every    n=1000 dim=1024  add p50=0.250ms p99=0.433ms  total=0.26s  close(snapshot)=8.6ms  record=4151 bytes
sync=snapshot n=1000 dim=1024  add p50=0.007ms p99=0.030ms  total=0.01s  close(snapshot)=8.5ms  record=4151 bytes

record=4151 is 20+4+27+4096+420 + 4 + 27 + 4096 + 4 bytes: the record header with its sequence number, the JSON length, the 27-byte header {"dim":1024,"id":"r000000"}, the vector and the checksum. On talos’s tmpfs the same command reported the flushing policy at 0.008 ms and the other at 0.016 ms.

The kill

crashloop on straylight, twenty runs of a child that appends 20,000 records of width 64 under SyncEveryWrite and is killed after 5 to 200 ms:

tools/remote/straylight.sh 5b-t4 -- go -C go run ./cmd/aec-vecdb crashloop -dir crash-run -runs 20 -n 20000 -dim 64
run  delay     exit     acked     recovered snapshot truncated   dropped 
0    153ms     killed   545       546       false    -1          0       
1    54ms      killed   185       186       false    -1          0       
2    190ms     killed   675       676       false    -1          0       
3    193ms     killed   704       705       false    -1          0       
4    7ms       killed   10        11        false    -1          0       
5    42ms      killed   144       145       false    -1          0       
6    181ms     killed   603       604       false    -1          0       
7    116ms     killed   397       398       false    -1          0       
8    101ms     killed   352       352       false    -1          0       
9    199ms     killed   688       689       false    -1          0       
10   148ms     killed   429       430       false    -1          0       
11   68ms      killed   204       204       false    -1          0       
12   156ms     killed   384       385       false    -1          0       
13   70ms      killed   211       212       false    -1          0       
14   108ms     killed   191       191       false    -1          0       
15   35ms      killed   64        65        false    -1          0       
16   127ms     killed   266       267       false    -1          0       
17   85ms      killed   248       249       false    -1          0       
18   28ms      killed   66        67        false    -1          0       
19   65ms      killed   186       187       false    -1          0       
runs=20 finished=0 clean=20 torn=0 corrupt=0 lost_acknowledged=0

exit is killed in every row, recovered is acked in 3 rows and acked + 1 in 17, no run recovered fewer records than it had acknowledged, and none had a torn tail to cut. A second run of 300 (-runs 300 -seed 7) ended:

runs=300 finished=0 clean=299 torn=1 corrupt=0 lost_acknowledged=0

Its 300 rows split 30 with recovered = acked and 270 with recovered = acked + 1, and one of them is a real torn tail:

run  delay     exit     acked     recovered snapshot truncated   dropped 
284  125ms     killed   374       374       false    122570      310

Run 284 was killed with a record half written: its first 310 bytes reached the log, Open cut them and reported it, and acked and recovered agree (the Mechanism explains the page boundary, and why the child is killed most often inside the fsync of a record whose bytes are already in the page cache).

With the child’s policy changed to SyncOnSnapshot (-runs 100 -n 200000 -seed 3 -sync snapshot, straylight), where no Add waits for the disk (about 8 microseconds each):

runs=100 finished=0 clean=100 torn=0 corrupt=0 lost_acknowledged=0

recovered equals acked in 96 of the 100 rows and exceeds it by one in 4. The kill leaves the page cache, so the weaker policy loses nothing to it.

The schema, without the fleet

The lab’s TestSchema takes the stand-in embedder at 256 dimensions (chapter 21’s HashEmbedder) to the one at 128 over 300 records and logs what each policy did (talos):

=== RUN   TestSchema
    lab_test.go:373: Rebuild: policy=rebuild from=fhash-256 to=fhash-128 rebuilt=300 remaining=0
    lab_test.go:412: DualRead step 1: rebuilt=256 remaining=44
    lab_test.go:424: DualRead step 2: rebuilt=44 remaining=0
--- PASS: TestSchema (0.04s)
PASS
ok      aec/labs/ch34    0.044s

The default Open refuses the new fingerprint; Migrate(Refuse) refuses; Migrate(Rebuild) re-embeds all 300 records and recall@10 against a fresh exact index over the new vectors is 1; Migrate(DualRead) moves 256 and then the remaining 44, SearchText merges both spaces between the two calls, and the old generation is removed at the end.

What the tests catch

The lab’s tests are above. The store has its own, written to attack its files. The damaged-file test applies 600 seeded mutations (a flipped bit, a zeroed run, a truncation, appended junk, a rotated file, a deleted run) to a store’s snapshot or log. For a damaged snapshot the only acceptable outcome is a refusal. For a damaged log there are three: an error wrapping ErrCorrupt; the complete history; or the history up to a record boundary at or before the first byte touched, with the shortfall reported in Recovery.Dropped. The one silent shortfall the oracle allows is the log cut exactly at a record boundary, which nothing in the log can detect. A looser oracle that accepted any subset of the written records let whole-record deletions and boundary cuts through without a word, which is why this one compares the recovered state with the history record by record. On talos:

=== RUN   TestDamagedFilesNeverLieQuietly
    store_attack_test.go:982: 600 damaged stores: 536 refused with ErrCorrupt, 0 opened complete, 64 opened cut and reported, 0 opened cut at a record boundary and silent
--- PASS: TestDamagedFilesNeverLieQuietly (0.12s)
PASS
ok      aec/internal/vecdb    0.123s

The forging tests rebuild a snapshot from an in-memory index with a NaN row, a repeated ID, the wrong metric, the wrong width, a graph in a flat store and an exact index in a graph store, a graph with other parameters, trailing bytes and a wrong count; each is checksummed correctly and each is ErrCorrupt. The forged-record tests build records with a valid CRC around a NaN, an infinity, the wrong width, a delete of nobody, and headers that would overflow ("dim":4611686018427387905 makes 4⋅dim4 \cdot \text{dim} wrap to 4); none panics and each is refused.

Each of these tests is run against a one-line change that breaks the property it pins (the checksum skipped, interior damage cut instead of refused, the snapshot’s sequence number or offset not checked, the record applied before it is logged, Open skipping Check), in a scratch copy of go/; the repository does not carry the harness, so no count is given. The one change found that no test can tell apart is the explicit non-finite check in decodeFlat, which Flat.Add shadows: it refuses the same row, and decodeFlat wraps that as ErrCorrupt, so the check is belt and braces.

Exercises

(a) Two bits are flipped 40 positions apart. Does CRC-32C always catch it? What about two bits flipped in a record that is 64 MiB long?

Answer

The error is E=xs(1+x40)E = x^s (1 + x^{40}), and since gcd(G,x)=1\gcd(G, x) = 1 it passes if and only if GG divides 1+x401 + x^{40}, that is, if and only if x40≡1(modG)x^{40} \equiv 1 \pmod{G}, which says the order of xx modulo GG divides 40. The order is a property of GG, so compute it: stepping x⋅amodGx \cdot a \bmod G from a=1a = 1 until it returns to 1 takes 2,147,483,647 = 231−12^{31} - 1 steps (a short Go program, talos), so xd≡1x^d \equiv 1 first at d=231−1d = 2^{31} - 1, and x40modGx^{40} \bmod G is 0x9f5fc3df, not 1. Two flipped bits are caught at every distance that is not a multiple of 231−12^{31} - 1 bits, about 268 MB, and so at every distance within any record the store accepts. The largest record the store accepts is 64 MiB, 229=536,870,9122^{29} = 536{,}870{,}912 bits, which is below 231−12^{31} - 1, so no pair of flipped bits inside any record it accepts is undetected. TestCRC32CGuarantees tried 456,407 pairs at 14 distances including 40, and none passed.

(b) One bit of a record’s length field is flipped, upward in one case and downward in another. Trace ParseRecord and Replay through both, for a record in the middle of the log and for the last one. Is anything lost that was acknowledged?

Answer

Upward: the length either runs past the end of the file, so the record is short and not intact, or lands inside the file, where the CRC is read from the wrong four bytes and fails (a flip that leaves the CRC valid has probability about 2−322^{-32}, and a length above 64 MiB or below 4 is refused before the CRC). Downward: the trailer is read from inside the payload and fails. Either way ParseRecord says “not intact” at that record. For a record in the middle, Replay searches the bytes after the damage, finds the next record’s magic, parses it intact, and returns ErrCorrupt; nothing is cut and no record is lost. For the last record, no intact record follows, so it is a torn tail: cut, and reported in Recovery. The record was whole and acknowledged and it is gone, reported but gone. This is the rule’s limit, stated in the Mechanism: a log by itself cannot separate a torn last record from a corrupted one.

(c) The log never shrinks in Part V. How large is it after a million adds of 1,024-wide records, what does Open do with it, and how would you add rotation so that Open is correct through a crash at every step of it?

Answer

A record with a short ID and no metadata is 4,151 bytes at width 1,024, so a million adds are 4,151,000,000 bytes, about 4.2 GB. Open reads the whole file into memory and, with a snapshot, checksums the part before the snapshot’s offset, so every start costs 4 GB of reads and of memory whatever the snapshot saves. Rotation as a rebuild that copies vectors instead of re-embedding: write a new generation whose log holds the live records only, snapshot it, fsync both, then switch CURRENT. It reuses the atomic switch of Rebuild, so the argument that every intermediate state is recoverable is the same one (until the rename the old generation is the store and the new directory is unreferenced; after it the new one is), and it needs no new recovery rule. It also drops the old generation’s tombstones. What it costs is a rewrite of every live vector and a pause; the alternative, a new log segment starting at the snapshot’s offset, needs a rule for which segments an Open reads, and a crash between writing the snapshot and deleting the old segment is a new state to prove.

(d) Chapter 35’s service keeps one journal, fsynced on every append, as its source of truth, and one vector store under it that is an index rebuildable from the journal. It opens that store with SyncEveryWrite. What does that cost per message, and would SyncOnSnapshot be safe there?

Answer

AddMessages adds each vector to the store first and then appends the batch to the journal once, so a call of nn messages pays nn store flushes (the every median, 0.250 to 0.284 ms on straylight’s disk, so 5.0 to 5.7 ms for 20 messages) and one journal flush. SyncOnSnapshot would not be safe as chapter 35 stands, and a lost tail is not the only way it fails: a power cut can leave a log with a hole before an intact record, which Open refuses (see the torn-tail section). Its Open never re-embeds from the journal: it assumes the index holds what the journal holds, so a store tail lost in a crash leaves messages the journal has and the store does not, and Recall silently never finds them. It is safe only when something rebuilds the store from the journal at open (compare the journal’s message IDs with the store’s and re-embed the missing ones, which costs one embedding per lost record, in batches, through the guarded embedder before the service answers). Chapter 40’s daemon does that at every open, and when Open refuses a store as corrupt it renames the directory aside (the daemon never deletes one), opens a fresh store and rebuilds it from the journal. Without that rebuild the per-message flush is what buys the invariant, and the policy’s cheaper writes would be paid for in the one place the service cannot see.

(e) Give two ranked lists of five IDs whose fused order, with k=60k = 60, differs from both lists, and compute the scores. Show an ID that is second in both lists beating an ID that is first in one list and absent from the other.

Answer

Take list A = (p, q, r, s, t) and list B = (u, q, v, w, p). The scores 1/(60+r)1/(60 + r) summed over the lists (a script, talos): q is second in both, 1/62+1/62=0.0322581/62 + 1/62 = 0.032258; p is first in A and fifth in B, 1/61+1/65=0.0317781/61 + 1/65 = 0.031778; u is first in B and absent from A, 1/61=0.0163931/61 = 0.016393; r and v are third in one list each, 1/63=0.0158731/63 = 0.015873; s and w fourth, 1/64=0.0156251/64 = 0.015625; t fifth, 1/65=0.0153851/65 = 0.015385. The fused order is q, p, u, r, v, s, w, t: it begins with the one ID that neither list puts first. q beats u because 2/62=0.03232/62 = 0.0323 exceeds 1/61=0.01641/61 = 0.0164: agreement at rank 2 is worth nearly twice a lone first place, which is the property that lets the fusion tolerate one space having ranked an item badly. Ties (r and v, s and w) are broken by ID, as every ordering in this package is.

(f) SearchText returns ErrNoPrevious during a dual-read migration when Options.Previous is nil. Why is that better than searching the new space alone?

Answer

A caller that cannot embed for the old space would silently lose every record that has not moved from its results for the whole migration, which at the start is all of them. The answers would be plausible and short of the truth, a wrong answer that nothing flags. Refusing turns a missing embedder into a configuration error at the first call. A caller that really does want the new space only can call Search with a vector it embedded itself, which says what it is doing.

Lab

go/labs/ch34 declares Impl{ParseRecord, Replay, Fuse}; you write mine/wal.go, the log reader and the rank fusion, and run

make lab CH=34 IMPL=mine

Provided: EncodeRecord (the writer, so your reader has bytes to read), the record format as described above, the store with its snapshots and generations, the stand-in embedder and its fingerprints. ParseRecord returns one record or “not intact” for anything short, mismatched or failing its checksum, including a header that no writer produces behind a valid one. Replay(data, from, nextSeq, apply) applies every intact record from an offset, which must be numbered nextSeq onward, and an intact record out of sequence is an error wrapping vecdb.ErrCorrupt; at the first damaged record it looks for an intact record anywhere after it: none means a torn tail (return the damaged record’s offset as good and the bytes after it as dropped), one means interior corruption (an error wrapping vecdb.ErrCorrupt and nothing applied from the damage on). Fuse(k, lists...) is reciprocal rank fusion with k=60k = 60, ties by ID. Five tests, all of which call your code:

  • TestRecordFormat pins the layout field by field, every damaged variant (short, empty, wrong magic, version, kind, the zero bytes, length, sequence, JSON, vector, CRC), that bytes after an intact record are not its business, and eight records with a valid checksum around a header no writer produces: a width that wraps 4⋅dim4 \cdot \text{dim} into the vector’s length, a JSON length past the payload, a length of 232−12^{32} - 1, a delete that carries a vector, an add without its vector;
  • TestTruncateEveryOffset cuts a five-record log at every byte from the file header to the end, requires the complete records to replay and the partial one to be a torn tail with the right offsets, that an apply error stops the replay and is returned, that an offset outside the file is ErrCorrupt, that two swapped records, a duplicated record and a wrong starting sequence number are ErrCorrupt, and that replay from a middle offset sees only what follows;
  • TestFlipEveryByte flips every byte of a four-record log: in the last record a torn tail, before it ErrCorrupt, and in that case apply must not have been called for the damaged record or any after it;
  • TestStoreRecovers writes real logs with the reference store (a log alone, a log cut seven bytes into its last record, a flipped interior byte, a snapshot whose offset lies beyond the log) and requires your Replay, run over those bytes before Open touches them, to reach the verdict Open reaches: the same count, the same cut, the same refusal;
  • TestSchema: the spec’s schema-evolution obligation, the three policies on the stand-in embedder’s 256-to-128 change, with the numbers above, every one of the 300 records compared with the vector the new embedder gives its text after the rebuild and after the dual-read, and your Fuse pinned to exercise (e)’s lists, order and scores and to the 2/(k+1)2/(k+1) cap.

Under IMPL=mine the starter fails all five, and make lab CH=34 passes against the reference. The store’s attacks (forged snapshots, forged records, damaged directories and small files, sequence numbers, the owner lock, the open-time Check) are tests of the vecdb package and not of the lab; run them with go -C go test ./internal/vecdb.

Further reading

results matching ""

    No results matching ""