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
ChainPatchrecords to a directory'sChainLogunder 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_inruns on hot paths; cold index builds and non-resident block loads must not bloat its future.
Considered Options¶
- Lazy per-directory
LookupIndexfed fromChainLog, published viaArcSwap - Write-side
note_*hooks on every chain writer feeding a singleState-wideRwLock - 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_indexis anOnceLock<Box<LookupIndex>>allocated only after an unserved directory crossesINDEX_STEP_THRESHOLD(32 sibling steps) on a lookup. A directory must cross the threshold twice (seen_slowring of 32) beforebuild_lookup_indexruns, avoiding full listings on one-off cold lookups. This two-scan trigger intentionally trades a single full listing (bounded byMAX_INDEXED_ENTRIES) for fast ramp-up on batch merges and syncs. - Publication and lock hierarchy. Active directories are published as an immutable
IndexedSnapshotviaArcSwap(promoted to a cross-platform dependency inlore-revision/Cargo.toml). Each indexed directory owns anArc<IndexedDirectory>holding its ownparking_lot::RwLock<DirectoryMap>and a strongArc<NodeBlock>pinning itsChainLog. The coldLookupIndex::tablelock is taken only on first slow scan, build coordination, insert, eviction, and reclaim clear. Lock order (documented instate/node/mod.rsC13) is strictlyIndexedDirectory::map->NodeBlock::read, never inverted and never held across.await;tableis never acquired undermapor a block lock. - Ordered lazy catch-up.
build_lookup_indexinstalls or grows the directory'sChainLogviaNodeBlock::watch_chain, reads(parent_node, chain_changes, log_seq)under one lock (C6), and walks children up toMAX_INDEXED_ENTRIES. Iflog_seqmoved during the walk, the snapshot is discarded before constructing theHashMapandparentis removed fromseen_slowto back off. On lookup,probe_fastcompareslog.seq()againstmap.log_seq; only when patches arrived does it takeentry.map.write()to copy and apply unseen patches in exact sequence order (with no block lock held during hash-map updates). AHashBucket::One/Manylookup inLIVEmode that would answer with a deleted node recheckslog.seq()andreclaimsbefore returning so a concurrent reattach + delete-mark cannot be missed. - Exclusive discards without global invalidation.
detach_exclusiveappends aPatchKind::Detachedpatch when the parent has an installedChainLog, andChainLog::forget()advancesseq(and setsfloor = seq) when a directory slot is freed. Exclusive discards therefore neither bumpState::reclaimsnor invalidate unrelated indexed directories orChainMarks. - Budgets and reclaim. Up to
MAX_INDEXED_DIRS(32) directories andMAX_INDEXED_ENTRIES(262,144) total child entries perState(~20 MiB peak map memory), with LRU eviction,MAX_CONCURRENT_BUILDS(2) bounding transient build memory, and a bounded FIFOtoo_widelist (16) suppressing repeated re-lists of over-cap directories within a reclaim count. Quiescent reclaims (State::reclaimsbump on sweep / pending drain) andmark_served()clear the index,too_wide, andseen_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
ChainLogappend andChainLog::forget(). - Bad, because watching an unserved wide directory retains its
ChainLogring on the residentNodeBlockuntil the block is evicted or theStateis dropped, andStatecarries aOnceLockcheck on every lookup. - Bad, because a directory wider than
MAX_INDEXED_ENTRIESfalls 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
ChainLogdelivers patches in exact sequence order, avoiding lag windows and manual hook drift. - Neutral, because
LookupIndexadds 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
ChainLogalone and conservatively evict that directory's entry.
Write-side note_* hooks feeding a single State-wide RwLock¶
- Good, because it avoids installing
ChainLogrings 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-wideRwLockserializes 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), deterministicstate-hooksscenarios (lore-revision/tests/state_scenarios/lookup_index.rs), thewide-lookupchaos mix (lore-revision/examples/state_stress/harness/mixes.rs), type-size checks, and allocation/throughput benchmarks.