Skip to content

ADR-00049: Per-directory lookup index fed lazily from ChainLog

Field Value
Status accepted
Date 2026-12-02

Context and Problem Statement

State stores each directory's children as a singly-linked sibling chain across NodeBlocks. That layout keeps node records compact and makes single-node mutations O(1) under per-block locks (ADR-00028), but every State::find_subnode, find_live_subnode, and locate_node walks the chain linearly. Batch operations that repeatedly probe a wide directory (such as merging or syncing 100,000 files into one directory) therefore scale quadratically in directory width.

How should unserved States accelerate repeated lookups in wide directories without adding a tree-wide lock, duplicating the write-side mutation hooks, or growing State::find_subnode futures?

Decision Drivers

  • No tree-wide lock on probes or chain updates. ADR-00028 rules out a lock that serializes lookups or mutations across unrelated directories.
  • No manual write-side hooks on every chain writer. Every writer already appends ordered ChainPatch records to a directory's ChainLog under its block write lock; duplicating that feed invites missed call sites and out-of-order lag.
  • Bounded memory and zero overhead for small or served states. Small directories and served (VFS) states, which maintain their own listing caches, must pay no index memory and near-zero probe overhead.
  • No future-size regression. State::find_subnode_in runs on hot paths; cold index builds and non-resident block loads must not bloat its future.

Considered Options

  • Lazy per-directory LookupIndex fed from ChainLog, published via ArcSwap
  • Write-side note_* hooks on every chain writer feeding a single State-wide RwLock
  • Replace the sibling chain with an on-block hash table or B-tree

Decision Outcome

Chosen option: "Lazy per-directory LookupIndex fed from ChainLog, published via ArcSwap", because it keeps hot probes lock-free across directories, reuses ChainLog's ordered change feed with no changes to attach.rs, detach.rs, relocate.rs, pending.rs, or sweep.rs, and leaves the stored block layout untouched.

Design and contracts

  • Lazy activation and build trigger. State::lookup_index is an OnceLock<Box<LookupIndex>> allocated only after an unserved directory crosses INDEX_STEP_THRESHOLD (32 sibling steps) on a lookup. A directory must cross the threshold twice (seen_slow ring of 32) before build_lookup_index runs, avoiding full listings on one-off cold lookups. This two-scan trigger intentionally trades a single full listing (bounded by MAX_INDEXED_ENTRIES) for fast ramp-up on batch merges and syncs.
  • Publication and lock hierarchy. Active directories are published as an immutable IndexedSnapshot via ArcSwap (promoted to a cross-platform dependency in lore-revision/Cargo.toml). Each indexed directory owns an Arc<IndexedDirectory> holding its own parking_lot::RwLock<DirectoryMap> and a strong Arc<NodeBlock> pinning its ChainLog. The cold LookupIndex::table lock is taken only on first slow scan, build coordination, insert, eviction, and reclaim clear. Lock order (documented in state/node/mod.rs C13) is strictly IndexedDirectory::map -> NodeBlock::read, never inverted and never held across .await; table is never acquired under map or a block lock.
  • Ordered lazy catch-up. build_lookup_index installs or grows the directory's ChainLog via NodeBlock::watch_chain, reads (parent_node, chain_changes, log_seq) under one lock (C6), and walks children up to MAX_INDEXED_ENTRIES. If log_seq moved during the walk, the snapshot is discarded before constructing the HashMap and parent is removed from seen_slow to back off. On lookup, probe_fast compares log.seq() against map.log_seq; only when patches arrived does it take entry.map.write() to copy and apply unseen patches in exact sequence order (with no block lock held during hash-map updates). A HashBucket::One/Many lookup in LIVE mode that would answer with a deleted node rechecks log.seq() and reclaims before returning so a concurrent reattach + delete-mark cannot be missed.
  • Exclusive discards without global invalidation. detach_exclusive appends a PatchKind::Detached patch when the parent has an installed ChainLog, and ChainLog::forget() advances seq (and sets floor = seq) when a directory slot is freed. Exclusive discards therefore neither bump State::reclaims nor invalidate unrelated indexed directories or ChainMarks.
  • Budgets and reclaim. Up to MAX_INDEXED_DIRS (32) directories and MAX_INDEXED_ENTRIES (262,144) total child entries per State (~20 MiB peak map memory), with LRU eviction, MAX_CONCURRENT_BUILDS (2) bounding transient build memory, and a bounded FIFO too_wide list (16) suppressing repeated re-lists of over-cap directories within a reclaim count. Quiescent reclaims (State::reclaims bump on sweep / pending drain) and mark_served() clear the index, too_wide, and seen_slow (a reclaim can shrink a previously over-cap directory). Cold async paths (resolve_lookup_index_slow, build_lookup_index) are boxed behind #[cold] #[inline(never)].

Consequences

  • Good, because wide-directory lookups drop from O(N) to O(1) per lookup (5x-114x faster across 1-8 threads; merging 100,000 files into one directory drops from ~193 s to ~0.35 s) with ~parity on small unindexed directories.
  • Good, because all chain writers remain untouched except exclusive discard's optional ChainLog append and ChainLog::forget().
  • Bad, because watching an unserved wide directory retains its ChainLog ring on the resident NodeBlock until the block is evicted or the State is dropped, and State carries a OnceLock check on every lookup.
  • Bad, because a directory wider than MAX_INDEXED_ENTRIES falls back to linear scans (and is re-checked once after a reclaim).

Pros and Cons of the Options

Lazy per-directory LookupIndex fed from ChainLog, published via ArcSwap

  • Good, because hot probes take no State-wide lock and distinct directories never contend on map locks or rehashes.
  • Good, because ChainLog delivers patches in exact sequence order, avoiding lag windows and manual hook drift.
  • Neutral, because LookupIndex adds a cold metadata lock (table) for build/evict transitions outside the hot probe path.
  • Bad, because in-place renames onto an already-occupied hash bucket cannot be distinguished from same-parent reattach order in ChainLog alone and conservatively evict that directory's entry.

Write-side note_* hooks feeding a single State-wide RwLock

  • Good, because it avoids installing ChainLog rings on unserved directories.
  • Bad, because every chain writer must manually call hooks outside block locks, producing out-of-order arrivals that leave entries lagging behind the chain.
  • Bad, because a single State-wide RwLock serializes finds and mutations across unrelated directories and pauses all readers during a hash-map rehash.

On-block hash table or B-tree

  • Good, because lookups need no auxiliary in-memory structure.
  • Bad, because it changes the stored node-block format and complicates every block write and diff path.

More Information

  • Extends the concurrency contracts in ADR-00028 and lore-revision/src/state/node/mod.rs (C3, C5, C13, C15).
  • Validated by unit tests (lore-revision/tests/unit/state/lookup_index.rs, lore-revision/tests/unit/file/dirty.rs), deterministic state-hooks scenarios (lore-revision/tests/state_scenarios/lookup_index.rs), the wide-lookup chaos mix (lore-revision/examples/state_stress/harness/mixes.rs), type-size checks, and allocation/throughput benchmarks.