Skip to content

opfs-lsm design ​


@opfs-lsm/kv is an embedded key-value store for the browser. Keys and values are byte arrays. It is a log-structured merge tree (LSM). Writes go to a write-ahead log (WAL) in IndexedDB. Sorted, immutable SST files in the Origin Private File System (OPFS) hold the data once it has been flushed out of the log.

Every tab of an origin can open the same database. Each tab appends to the shared log, keeps its own memtable of the writes that are not yet in an SST, and answers reads on its main thread. One SharedWorker, the host, turns the log into SST files and compacts them.

The design ranks its goals in this order:

  1. Read and write latency.
  2. Consistency. Every read sees the state after one prefix of the log.
  3. Persistence. An acked write should survive, but the engine trades this away before the first two.

This document covers the kv engine only. The packages built on it are not described here.

All multi-byte integers are stored in little-endian order.

Storage layout ​

A database named <name> lives in two stores:

IndexedDB"opfs-lsm-wal/<name>"
  • wal
    seq → bytesone record per acked batch
  • meta
    "ingestedThrough" → seqno record at or below it is read
    "generation" → nthe manifest tabs read
    "manifest" → bytesa copy of the manifest last flushed or compacted
    "topGeneration" → nhighest manifest number recovery has seen
    "destroyedTop" → nmanifests numbered up to this predate a destroy
IndexedDB"opfs-lsm-destroyed" one per origin
  • destroyed
    <name> → { head, top }a database destroyDb removed, until <name> opens again
OPFSopfs-lsm/<name>/
  • m/<generation, 16 digits>.mft
    manifests
  • l0/<firstSeq>-<lastSeq>.sst
    flushed runs, may overlap
  • l1/c<generation>.<i>.sst
    compacted runs, disjoint within a level
  • l2/...
  • reserve
    bytes the host gives back when a write is refused
  • A seq is the position of a batch in the log. Seqs start at 1 and have no gaps, except where a power loss lost them from both stores. A seq is never handed out twice.
  • A run is one SST file. A run path is written once and never rewritten, so a tab caches a parsed run by its path with no invalidation.
  • A generation is one numbered manifest that lists the live runs. A manifest number never names two different manifests.
  • The recorded generation is the one in meta.generation. Tabs read it, and not the newest file in m/.

Write-ahead log ​

WAL records ​

Each acked put, delete or batch with ops is one record in the wal store. An update is at most two (see Append). A batch with no ops writes nothing and resolves with the appliedThrough of its tab. The key is the seq. The value is one ArrayBuffer: an optional header, then the ops of the batch back to back:

u84the header: the seq the row is valid at optional
u64seq
u8type0 = put, 1 = delete, 3 = range delete
u32key length
keythe start key, for a range delete
u32value lengthputs only
valueputs only
u8has endrange deletes only
u32end lengthif has end
end
u64throughas the writer asked range deletes only

A writer that gives no through stores 2^53 − 1. The record's seq bounds it (see Range deletes), so the stored value never needs the seq the record will get.

A row with a header has its ops at the seq the header names, and none at any other: its bytes and its key decide, the same for every reader. A row that is not an ArrayBuffer, that ends inside an op, that holds a header after its first byte, or that holds a range delete whose start is not below its end, fails with CommitError, whatever its header names.

Append ​

put, delete and batch append by group commit. A tab has at most one group-commit transaction open. The append that opens it and the appends issued synchronously after it join it, and appends that arrive while it commits form the next group. A group is one readwrite transaction over wal:

  1. add each record of the group, in call order, with no key: the store's key generator assigns its seq.
  2. Commit in a microtask, without waiting for the results of the adds.

The records are the only writes. A group commits or aborts as a whole, and a failed group fails every write in it. A group the browser refuses for space is added once more (see Reserve). IndexedDB serializes readwrite transactions that share a store, so two tabs cannot take the same seq. An aborted transaction reverts the key generator, so committed seqs stay gapless.

Nothing stores the head, the seq of the last committed batch. It is the last key in wal, or ingestedThrough when no record is past it. Only recovery and destroy move the head past the last key: they add and delete a record at the new head, which moves the key generator to head + 1. A power loss that loses commits also loses what they did to the key generator, and this is what keeps the next append from taking a seq that a manifest already holds.

update(keys, body) runs the synchronous body on what its tab reads and appends, by group commit, a row whose header names appliedThrough + 1. The row takes that seq only if no write committed since the read. Failing that, the update runs in one transaction that reads the tail, applies it to the memtable, runs body and adds the batch at head + 1, which no writer can beat. So does an update issued while an append of its handle is in flight, or whose body wrote nothing or threw. After a row loses, the handle appends no such row until one of those transactions writes with an empty tail. A handle runs its updates one at a time, in call order.

The commit point is the complete event of the transaction, at the default IndexedDB durability. The writes of a group commit in seq order. A commit survives a tab crash. It may not survive a power loss. The caller's promise resolves with its seq, after the record joins the memtable and is announced. If its seq is not the next one, another tab appended first, and the tab reads the tail before that. At the promise, the writer sees its own write and every earlier one.

Reading the tail ​

openDb, sync and a catch-up after an append read the same way. One transaction reads ingestedThrough, then the head, then every record in (after, head], where after is max(since, ingestedThrough) and since is the appliedThrough of the caller. An open starts at 0, so it replays the whole uningested WAL; the host flushes at maxWalBytes, so that replay is normally near the limit, but the tab's read path truncates nothing.

Seqs are gapless above ingestedThrough, and no tab has applied a seq past the head, so the head is past after only when after + 1 is a key. One point read answers that, and the last key is read only when it is there. In Chrome a range read past the last record steps over every row deleted since IndexedDB last compacted. The position of a record in its range gives its seq. A range that returns fewer records than it spans throws CommitError (wal gap).

Truncation ​

An ingest sets ingestedThrough and generation and deletes every record at or below the previous ingestedThrough, in one transaction. The WAL therefore holds the uningested seqs plus the seqs the last ingest folded. Recovery needs the second group when a power loss keeps this commit and loses the new run. No read touches them.

Memtable ​

Each tab holds one memtable. It holds the WAL records in (ingestedThrough, appliedThrough], where ingestedThrough is that of the installed generation, folded to one row per key:

MemRow = { key, seq, kind: "put" | "del", value? }

Rows are kept in key order, in chunks of up to 1024 rows, split at 512. Records apply in seq order with no gaps. A record that skips a seq is refused, and the tab reads the WAL tail instead. The memtable is therefore always one exact prefix of the log. Every read depends on this.

The memtable also holds the marks of the range deletes in its records. Applying a range delete removes the rows it covers at once, so a row the memtable holds is never covered.

A view pins the memtable without copying it. The pin copies the array of chunk references and marks every chunk as shared. The live table copies a shared chunk before its next write to it, and a range delete rebuilds the table from the rows it keeps.

When the installed generation moves forward, the memtable drops the rows that the newly ingested seqs wrote, and the marks of the newly ingested records.

Backpressure ​

bytes is the sum over live rows of the key bytes, the value bytes and 256 bytes for the row. openDb({ memtableBytes }) bounds it, 16 MiB by default, with two thresholds:

StateEnteredEffect
belowUnder 7/8 of the limitNone.
requestedAt 7/8The tab asks the host for one flush and keeps writing.
waitingAt the limitA write waits for that flush before it appends. A put, delete or batch called while one waits goes after it, so they append in call order.

One flush is in flight per tab. If the flush fails, or returns without moving the generation, the write goes on, and the tab asks again after the memtable grows by another 1/8 of the limit. A host that never answers holds writes at the limit. The thresholds are checked only on a write.

SST file format ​

A run is one SST file: sorted data blocks, a bloom filter, a block index and a footer. Its byte layout is in sst-format.md.

Reading a run ​

A tab holds each run of its installed generation open and reads it on demand. The first read loads the footer, the bloom filter and the block index. Each later read loads the 32 KB page of whole blocks that it needs. Reads of one run issued in one turn share one file read, unless they are over 128 KiB apart or the read would pass 1 MiB. Pages that fill three quarters of a file read share its buffer, so the cache can hold a third more than it counts. A scan past its first page reads ahead toward its bound: when at most half a window is asked past the page it enters, it doubles the window, from 1 page up to 32, and asks for every page up to a window past that page. All of it lives in one page cache per tab, capped by openDb({ cacheBytes }), 256 MiB by default.

A read is synchronous while its bytes are cached. Otherwise the caller awaits the load and reads again, keeping what it read outside the cap. A value over the cap is never cached. A point get:

  1. Rejects the key if it falls outside the first and last keys of the run.
  2. Rejects it if the bloom filter says no.
  3. Binary-searches the block index for the one block that could hold the key.
  4. Binary-searches the offset table of the block, then walks at most 4 records in place.

Tabs do not check the CRC. The host checks it when it reads a run as a compaction input.

Manifest format ​

A manifest, m/<generation>.mft, lists the runs of one generation. Its byte layout is in manifest-format.md.

through is the seq the runs reach. The runs hold the fold of every seq up to it and no seq past it. An ingest sets it to the last seq it folded. A compaction keeps the value of its base.

A manifest also holds the marks of the range deletes up to through that its runs may still hold versions for, and for each run its marksThrough (see Range deletes).

A new manifest takes a number one past the highest in use: the newest file in m/, the recorded generation and meta.topGeneration. Numbers can skip.

Reads ​

get reads the memtable, then the installed levels newest first, up to the first that holds the key; each L0 run is a level, and a deeper one asks the run whose range holds the key. It goes on past a run whose layout is not cached, so those layouts load together, and waits at one that may hold the key. It touches neither IndexedDB nor the host. getMany reads many keys at once, and with decode copies no value.

range merges one cursor per source: the memtable, each L0 run, and each deeper level as a whole. For each key the newest source wins, and tombstones are dropped. The waiting sources sit in a list sorted by key and then by age, which a source enters from the front, so one that keeps winning costs one comparison per key, and two that tie on a key are compared once. A level cursor opens one run at a time, in key order, and only the runs the scan reaches. reverse returns the same keys in descending order. Bloom filters play no part in a scan.

range({ valueContains }) keeps the live puts whose current value holds every pattern. Each source filters on its own, one block at a time, and only the hits are copied out. A newer source that holds the key with a non-matching value or a tombstone drops the older hit.

A key and a value stay in place in the block bytes, which are never written once read, until the scan yields their entry. One it drops, counts or passes over for offset copies no value, and its key only if it waits through several compares. count(range) runs the same scan.

Every read judges the versions it finds in runs against one read point: the marks of the installed generation joined with those of the memtable, taken in the same turn as the layers it reads. A version from a run is skipped when a mark covers it (see Range deletes), and then an older source does not win in its place. A scan skips a run unread when one mark holds all its keys within the scan's bounds, with through at or past the run's marksThrough.

A view pins appliedThrough, the installed generation, the memtable chunks and the read point. Writes that commit during the callback are invisible to it. snap.rangeJoin scans a range and point-reads one key per entry under that pin.

Range deletes ​

A range delete removes every row in [start, end), where start may be empty and end absent, in one op. A delete whose resolved through is 0 keeps no mark and removes nothing. It covers a version of a key in the range when the version's seq is at or below its through. A writer may ask for a through; the record at seq s takes effect as min(asked, s − 1), so a range delete never covers its own batch and a later write into the range is read as usual.

The range deletes in effect form the marks, an unordered list of (start, end, through, at), where at is the seq of the record that holds it. The highest through among the marks that hold a key judges it, so joining is concatenation. A read checks every live mark, so its cost grows with their number until compaction retires them.

A version is judged in the layer that holds it:

  • The memtable removes covered rows when it applies the record, so its rows need no check.
  • A flush drops the ops its own records' range deletes cover, then joins those marks into the manifest's.
  • A merge drops a winning version that a mark of its base manifest covers, tombstones included, at any level: every older version of the key has a smaller seq, so the mark covers it too.
  • A run records marksThrough: it holds no version past it, nor one that a range delete from a record at or below it covers. A flushed run takes its last seq, a compaction its base's through.

A mark retires when every run that overlaps it has marksThrough at or past its at: no run left can hold a version it covers. Each flush and each compaction install retires the manifest's marks against its new runs, and a mark step (see Planning) rewrites the runs that hold a mark back, so its rows leave the disk.

Reserve ​

openDb({ reserveBytes }) sets the size of reserve, 24 MiB unless given, and 0 keeps no file. When the browser refuses a write, the host removes the file, the write runs again, and db.onStorageFull asks a tab to free space. kv never removes a row itself. The steps are in reserve.md.

Multi-tab coordination ​

Seeing other tabs' writes ​

After an append commits, a tab posts { kind: "rows", writerId, rows, bytes } on the BroadcastChannel opfs-lsm-layers/<name>: the WAL rows it appended, each { seq, record }, and the key and value bytes of their ops. A row is posted when it commits, unless the tab posted in the last 4 ms. Then it waits for the first commit past that time, a timer, or close, and one message carries every row that waited: a post costs per message, not per row. A hidden page posts every row when it commits, and what waits when it becomes hidden, because browsers slow and stop its timers. Every other tab applies the records in the order given (Memtable).

A tab therefore sees the write of another tab a moment after its ack, and a few milliseconds later during a burst. db.sync() closes the gap: it reads the WAL tail and applies everything acked before the call. The broadcast is an optimization. The WAL tail is the source of truth.

Installing a generation ​

A tab installs a generation only when the WAL tail tells it to, during sync or an append. The installed generation never holds a seq past appliedThrough. If the tail names a generation the tab has not loaded, the tab loads the manifest and opens its runs outside the transaction, then reads the tail again. An open starts that load when the transaction names the generation, before it reads the records. A flush or a compaction records the manifest's bytes in meta.manifest with its generation, and such a tail reads them: when the copy decodes to that generation, the tab opens the runs from it while it reads the manifest file. The load still fails without the file: a power loss can keep the copy and lose the file and its runs. Recovery never reads it.

After a flush or a compaction step, the host posts { kind: "ingest" } on the channel, and tabs call sync.

Loading a generation under churn ​

The host removes the runs of a replaced generation once no tab holds them open. A tab holds a run open by taking a shared Web Lock opfs-lsm:<name>:run:<path> before it checks that the file exists, and releases it on close; the host removes a run only under that lock, taken exclusively with ifAvailable. A slow tab could therefore lose every load to a newer generation. The tab and the host share the Web Lock opfs-lsm-reclaim/<name> to prevent this:

  • The first try of a tab takes no reclaim lock. After a try finds a file missing, every later try holds it shared, from the tail read to the last run open.
  • The host removes files only while it holds the reclaim lock exclusively, and it asks with ifAvailable. When a tab holds the lock, the host skips the removal and tries on a later pass.

Under the lock, no removal can run, so the manifest and every run of the recorded generation are on disk and the load succeeds. The host never waits for the lock, so no tab can stall a flush or a compaction. A tab can only delay the removal of garbage.

A try that finds a file missing under the lock has the host reconcile (Recovery). After 8 such tries the tab throws CorruptDatabaseError.

A tab keeps its generation when a tail has a lower ingestedThrough than the installed one, or names a lower generation and is not ahead of its memtable: it was read before that generation was recorded. A lower generation ahead of the memtable follows a destroy or a repair, and is installed.

Ingest ​

Ingest moves WAL records into L0 runs. It runs in the host.

Trigger ​

Per database, the host keeps pendingBytes, the key and value bytes of the ops that are not yet folded. Each rows message adds its bytes. When it reaches maxWalBytes, 1 MiB by default, the host flushes. The limit is the smallest any tab asked for until the last one closes, and each tab asks for at most 7/8 of its memtableBytes. Once an eighth of the limit waits, the host also flushes 2 s after the last rows message, or 5 s after the first since a flush began or the last 5 s wait ended, so an open replays a short tail.

openDb registers the tab with the host. The host then measures the uningested records, so a database left over the limit catches up on open. The count only decides when to flush. Every flush reads the WAL, so a missed broadcast delays a flush and loses nothing. After a failed flush, the host waits for another maxWalBytes of writes or the next open.

ingest(db) from @opfs-lsm/kv/testing flushes through the end of the log and waits for the compaction it starts.

Flush ​

A flush notes the head when it starts, then folds the WAL from ingestedThrough into one L0 run per flushRunBytes of op bytes, oldest first (see Memory budget). One flush runs at a time per database. A record acked after the start can join a later run of the same flush, because each run reads the WAL as it stands; the rest wait for the next flush.

For each run, under the exclusive section for the database, the host:

  1. Reconciles (see Recovery). The recorded generation is G, and the highest manifest number in use is top.
  2. Reads the WAL records above ingestedThrough, oldest first, up to flushRunBytes. A run takes at least one record, and an op counts as at least 32 bytes.
  3. Folds them to the last op per key, in key order, keeping the seq of each op, and drops each op that a range delete of the same records covers.
  4. Writes l0/<first>-<last>.sst, unless no op is left.
  5. Writes manifest top + 1 with through = <last>, listing the new run in front of the runs of manifest G, and the marks of G joined with those of the records (see Range deletes).
  6. In one IndexedDB transaction, sets ingestedThrough = <last>, raises generation to top + 1 and truncates the WAL.
  7. Deletes the manifests older than the recorded generation, unless a tab holds the reclaim lock.

The exclusive section is a promise chain in the host plus the Web Lock opfs-lsm-ingest/<name>, which covers two SharedWorkers that serve the same database. A compaction install can take the section between two runs.

L0 stop ​

At l0StopRuns L0 runs, a flush publishes nothing and waits for the next compaction step to install. The stop is one less than the source limit of a merge, so one step can take all of L0. If the compaction pass ends without an install, the flush publishes its run anyway. A compaction that cannot help delays a flush by one pass and never blocks it.

Compaction ​

Compaction keeps a leveled layout.

LevelRunsBudget
L0Overlap, newest first4 runs
L1Disjoint, sorted by key40 MiB
LnDisjoint, sorted by key40 MiB × 10^(n−1)

Levels are created as they fill, with no maximum depth. Budgets count bytes on disk.

Planning ​

The planner reads only the manifest. It scores each level and serves the highest score. On a tie the shallower level wins.

  • L0 scores its run count over 4, and reports at 4 runs. Its step merges the oldest L0 runs, at most l0StopRuns, with the L1 runs whose ranges overlap them.
  • A deeper level scores its bytes over its budget, and reports past 1. Its step picks the run whose overlapping bytes in the next level are the smallest fraction of its own size, and merges it with those runs into the next level.
  • When no level reports, a mark step takes the first run that keeps a range delete from retiring: the L0 step for an L0 run, otherwise that run alone, rewritten into its own level.

Scoring lets L0 pass 4 runs while a deeper level is further over budget. If L0 always went first, L1 would never be pushed down.

A plan is bottom when no run below the output level overlaps the inputs. Only a bottom merge drops tombstones.

Merging ​

A step reads its inputs as sources, newest first. Each L0 run is one source. The overlapped runs of the next level, which are disjoint, are one source together. A step has at most maxSources sources.

The merge is a session that the host pumps. The session owns every offset. Each pump stops between two keys and asks the host for one thing:

StopThe host
NEEDreads the listed byte ranges of the inputs and feeds them in
WRITEwrites the bytes to the open output run
RUN_ENDfinishes that file and records its size and key range
YIELDgives the event loop a turn
DONEinstalls the outputs

For a key, the newest source wins, and is dropped when a mark covers it. The session checks the CRC of every input run before it uses the last entries of that run. It cuts the output into runs of about 4 MiB of records, named c<top + 1>.<i>.

The memory a step holds does not depend on the size of its inputs: about one read window of blocks per source, plus the open output block and its bloom and index rows. If any input is corrupt, or any read or write fails, the host deletes every output and installs nothing.

Memory budget ​

openDb({ compactionMemoryBytes }), 32 MiB by default and at least 8 MiB, is the memory the host may spend on flushing and compacting one database. It covers the wasm heap and the run data in flight. The host uses the smallest value any tab passed, until the last tab closes the database. The other figures follow from it:

BudgetflushRunBytesmaxSourcesl0StopRunsRead windowRecycle at
16 MiB0.875 MiB444364 KiB8 MiB
32 MiB1.75 MiB4948128 KiB16 MiB
64 MiB3.5 MiB4948256 KiB32 MiB

Past 64 MiB only the recycle threshold grows. The budget counts live memory. Garbage that the browser has not collected yet comes on top of it.

Merges take turns across the databases of one SharedWorker, because the wasm module holds one merge session. A flush does not wait for a merge. It runs between the pumps of the session.

Wasm memory never shrinks. After a flush run or a compaction step, if no merge session is open and the instance holds more than the recycle threshold, the host replaces the instance.

Installing ​

The merge holds the Web Lock opfs-lsm-compact/<name> and its turn among merges, and not the exclusive section, so flushes go on while it runs. A flush adds L0 runs in front of the inputs, which leaves the plan valid. To install, under the exclusive section, the host:

  1. Reconciles, and checks that every input is still in the recorded manifest G.
  2. Writes manifest top + 1, with the inputs replaced by the outputs, and the through and marks of G, retired against the new runs.
  3. Raises meta.generation to top + 1.
  4. Sweeps: deletes the older manifests, and every run outside top + 1 that no tab holds open. While a tab holds the reclaim lock, it deletes nothing and tries again on the next pass.

A pass runs up to 8 steps, and sweeps if it installs none. A request during a pass starts another, and so does a pass that used all 8.

Destroy ​

Seen from the log, a destroy is one entry that deletes every key: the writes acked before it are gone, and the writes after it land in the empty database. db.dangerousDestroy() empties the database and keeps it. destroyDb(name) removes it, without opening it, so it also removes one that openDb refuses as corrupt.

Emptying ​

For dangerousDestroy, the host:

  1. Takes the compaction lock, then the ingest lock: the order a compaction pass takes them in. No flush or merge publishes while it holds them, and a merge already running stops after its current step.
  2. Commits in one IndexedDB transaction at durability "strict", which completes only once it is on disk. It drops every WAL record and records generation 0, with ingestedThrough one past every seq a manifest on disk names and past the head the transaction reads, so a tab that keeps writing never delays it, and topGeneration and destroyedTop at the top manifest number.
  3. Removes every manifest, then sweeps: against generation 0, every run goes. Both skip while a tab holds the reclaim lock, and the sweep skips each run a tab still holds open. A tab holds its runs until it installs generation 0, or until a view that started before the destroy ends.
  4. Posts { kind: "ingest" }. Each tab installs generation 0 at its next sync or append, and its memtable drops every row. Handles stay open, and each reports a gap change event.

dangerousDestroy then syncs its tab and asks for a flush, whose pass sweeps the runs it let go.

The transaction is the commit point. After it, recovery adopts no manifest on disk: rule 1 needs a through past head, rule 2 keeps the recorded generation, and rule 3 skips every manifest numbered up to destroyedTop. Since the commit is on disk before step 3 starts, no power loss keeps a remove and loses the commit.

Removing ​

destroyDb runs in the calling page and starts no SharedWorker. It:

  1. Takes the Web Lock opfs-lsm-open/<name> exclusively, then the compaction and ingest locks. openDb holds the open lock shared until it resolves, so no open is half done, and an open that starts meanwhile waits, then opens an empty database.
  2. Opens opfs-lsm-wal/<name> one version up, which closes every other connection first (assumption 7). Each handle closes, with a closed event whose reason is "destroyed", and no write by an earlier connection commits after this step. No other open names a version. If neither store of the database exists, it stops here and creates nothing.
  3. Commits as in Emptying, step 2.
  4. Writes that ingestedThrough and destroyedTop under <name> in opfs-lsm-destroyed, as head and top, at durability "strict", never below a row already there.
  5. Removes m/, then the folder opfs-lsm/<name>/.
  6. Deletes opfs-lsm-wal/<name>.

With opfs-lsm-wal/<name> gone already, it skips steps 3 and 6, and step 4 takes head one past the highest through and top at the highest number of the manifests on disk. With no manifest, it writes no row. The row is on disk before step 5 starts, so a power loss that keeps any remove keeps the row, and the next open starts past it (rule 0).

Only openDb creates either store. The host opens each only if it exists, at the start of every operation, and stops when either is gone.

Change events ​

db.changes(listener) reports each WAL record that a handle applies to its memtable, with its ops, whichever path brought it: its own commit, a broadcast or a catch-up read.

  • Every applied seq is announced once, in seq order, after reads can see it.
  • An append can carry no ops: the row of an update that took another seq than its header names.
  • gap replaces the records that a handle skipped because a flush folded them before it read them, or because a repair recorded another generation. A listener reads again.
  • closed is the last event. Its reason is "destroyed" when destroyDb, the browser or DevTools deleted the handle's WAL database, or the browser closed its connection by force.

Recovery ​

Writes go to two stores, and nothing orders one against the other on disk. No OPFS close and no IndexedDB commit is an fsync, except a commit at durability "strict". After a power loss, each store keeps a prefix of its own completed writes, and the two prefixes are independent. Acked writes may be lost. The database must still open, and read the fold of one prefix of the log.

The invariant ​

A manifest is intact when every run it lists is on disk. The write order keeps two facts true at every prefix of each store:

  1. Every intact manifest is a log prefix. Its runs hold the fold of exactly the seqs 1..through. A run is written before any manifest lists it, and run paths are never reused.
  2. WAL records are log entries. head never moves down, and recovery and destroy move it past every seq that any manifest on disk names. New manifests number past topGeneration.

So any intact manifest, followed by the WAL records through + 1..head with no gap, is a log prefix. Without those records, the manifest alone is one.

The rule ​

reconcile picks the manifest to record:

  1. Nothing recorded, and opfs-lsm-destroyed has a row for the name. destroyDb removed a database of this name. Record generation 0 as a destroy does, at durability "strict", with ingestedThrough at least the row's head and destroyedTop at least its top, then delete the row. A manifest numbered past the row's top was written by a database born after the removal, whose WAL database was then lost: record generation 0 at the row's own head and top instead, delete the row, and go on to rules 1 to 3, which recover that database. While opfs-lsm-wal/<name> records a generation, the row is ignored.
  2. OPFS kept seqs that IndexedDB lost. The newest intact manifest that is numbered past the recorded one and whose through is past head. It is a longer prefix than the WAL.
  3. Otherwise the recorded manifest, if it is intact.
  4. Otherwise IndexedDB recorded a manifest that OPFS lost. The newest intact manifest numbered past destroyedTop, or the empty generation 0. A manifest file that is missing or empty counts as lost.

In a running database only rule 2 applies. A manifest newer than the recorded one is a leftover of a crash between a publish and its IndexedDB commit. Its seqs are still in the WAL, so it is ignored.

Recording a manifest ​

Recording is one IndexedDB transaction. It writes only if meta still reads what reconcile read. It pairs the manifest with the WAL:

  • With head unchanged, ingestedThrough becomes through when through is at or past it, and the seqs above through are uningested again when the WAL holds all of them.
  • Otherwise every record is dropped, head moves up by at least one, and ingestedThrough moves to it. The database is the manifest alone, and every tab still open is behind it and follows.

The same transaction moves head past the highest through of any manifest on disk, and topGeneration past every manifest number seen.

Corruption is not a power loss ​

OPFS publishes a file whole, and the host removes a run only after the recorded manifest stops listing it. A manifest numbered past the recorded one is a crash leftover, and its runs may go. A power loss therefore never leaves a manifest that fails to decode, or the recorded manifest on disk with a run missing. Those states are corruption. Recovery throws CorruptDatabaseError and writes nothing, so the database stays as it is on disk. An openDb that throws closes everything it opened, so destroyDb can run next.

  • The recorded manifest does not decode: refuse.
  • The recorded manifest lists a run that is gone: an intact manifest whose through is at or past ingestedThrough may stand in. Otherwise refuse.
  • Rule 3 meets a manifest that does not decode before it meets an intact one: refuse.

Who reconciles ​

  • The host, under the exclusive section: at each flush and compaction install, when a tab asks, and before a sweep, except one in a pass that installed nothing: that sweep only runs for the generation the host last checked.
  • openDb checks while it reads the tail and loads its generation. It records generation 0 for a database with nothing stored, and asks the host for every other write. It applies that tail only when nothing was written, and reads again otherwise. A tab writes only after this check.

Crash behavior ​

Each step writes new files before anything points at them, and deletes files only after nothing points at them.

A process crash keeps every completed write of both stores. Every acked write survives.

Crash afterState on reopen
Append, before completeThe batch is not in the WAL. The caller got no ack.
L0 run written, before its manifestThe run is garbage. The records are in the WAL.
Manifest written, before the IndexedDB commitThe manifest is ignored. The records are in the WAL, and the next flush folds them again.
IndexedDB commit, before reclaimOld manifests and runs stay until a later pass removes them.
Compaction outputs written, before installThe outputs are garbage.
A destroy's transaction, before its removes finishThe database is empty. A sweep, or the next destroyDb, removes what is left.

A sweep lists the run files and removes those the recorded manifest lacks and no tab holds open.

A power loss keeps a prefix of the commits of IndexedDB and a prefix of the file operations of OPFS, independently.

IndexedDB keptOPFS keptReopen
The commit of a flushNot its run or manifestRule 3. The previous manifest is intact, and the WAL still holds the seqs that flush folded. Nothing is lost. If OPFS lost more than one flush, the WAL is dropped.
Not the commit of a compactionIts manifest and its removalsRule 3. The new manifest is intact and has the same through. Nothing is lost.
Some appends, not the flush after themThe manifest of that flushRule 1. head moves to its through.
NothingSome manifestsRule 1 records the newest intact one, and head moves past its seqs.
A destroy's transactionAny prefix of its removes and of later opsNo manifest from before the destroy is adopted. The database holds a prefix of the writes after it, or none.
Not a destroy's transactionNone of its removesThe commit was not on disk, so no remove had started. As if the destroy had not run.
The deletion of a destroyDbAny prefix of its removesRule 0. No manifest from before it is adopted.

Limits ​

LimitValue
Key8 KiB
Batch8 MiB, counted as the key bytes, the value bytes, a range delete's bounds, and 256 bytes for each op. A put is a batch of one op, so this is also the limit of a value.
Database name[A-Za-z0-9_-]{1,64}

Where code runs ​

WorkThreadLanguage
Append, memtable, point get, range merge, bloom checksTab main threadTypeScript
Filter a scan inside a blockTab main threadwasm
Fold the WAL into L0, encode SSTsSharedWorkerTypeScript applies range deletes, wasm sorts and encodes
Compaction merge, CRC checkSharedWorkerwasm session, pumped by TypeScript

A tab reads in TypeScript so that a get never posts a message. The wasm module is required: openDb rejects with StorageUnavailableError when it does not load.

Assumptions about the platform ​

  1. IndexedDB serializes readwrite transactions that share a store, across tabs and workers. An aborted transaction reverts the key generator of the store. An add at an explicit key moves the generator past that key, and deleting the record does not move it back.
  2. An OPFS createWritable().close() publishes the whole file atomically.
  3. Each store keeps the order of its own completed writes across a power loss, so a prefix of them survives. Nothing orders IndexedDB against OPFS, or two IndexedDB databases, except that an IndexedDB transaction at durability "strict" completes only once it is on disk. A recursive OPFS removal is a series of removes in no promised order.
  4. A SharedWorker with the same URL and name is shared by every tab of the origin.
  5. Web Locks are shared by the tabs and workers of an origin, and the browser releases the locks of a context when it goes away.
  6. BroadcastChannel delivers the messages of one sender in order. Messages may arrive late or not at all.
  7. An IndexedDB open at a higher version sends versionchange to every other connection and waits until each has closed.