---
title: "14.3 million files in RAM: how I built local hybrid search in Rust"
subtitle: "24-byte entries, 64-bit bitmasks, Tantivy BM25, int8 Model2Vec vectors, and why I refused to write a root daemon"
url: https://blog.cloudwerxlab.com/post/fourteen-million-files-in-milliseconds
author: "Ty"
published: 2026-11-29T10:31:43.517Z
updated: 2026-11-29T10:34:50.982Z
category: systems
tags: ["cloudwerx-os", "rust", "search", "linux", "tantivy", "embeddings", "cachyos", "wayland"]
summary: "My desktop launcher indexes 14.3 million file entries in RAM, runs BM25 across 41k docs, and searches 483k passages by meaning in milliseconds with no cloud and no root daemon. Here's how cloudwerx-searchd works."
---

# 14.3 million files in RAM: how I built local hybrid search in Rust

If you ever used Voidtools Everything on Windows and then moved to Linux, you probably felt the same itch I did. On Windows, you open a box, type half a filename, and it knows where every file on your drives lives before your finger even leaves the key. On Linux, half the time you're either waiting on `find`, kicking `locate` after an `updatedb` cron job missed the file you just saved ten minutes ago, or watching a desktop indexer chew through a CPU core in the background while your fans spin up.

When I built [CLOUDWERX OS](https://blog.cloudwerxlab.com/post/how-i-built-my-own-os), I wanted my launcher (`Super+Space`) to do three things from the exact same text box without leaving my machine or needing a root daemon.

First, fuzzy name search across the entire filesystem, live as I type. Second, full-text search inside my documents, PDFs, Office files, and code. Third, search by meaning, so when I remember what a document is *about* instead of what words I used in it, I still find it in a few dozen milliseconds.

Right now, my laptop has **13,923,933 files** and **407,002 folders** indexed in memory. That's **14,330,935 entries** sitting in RAM, plus **41,195 documents** in a full-text index and **483,857 text passages** turned into vectors for semantic search. The entire daemon (`cloudwerx-searchd`, written in Rust) sits around **930 MiB RSS** (`975,601,664` bytes) and takes roughly **742 MiB** on disk.

![Cycling through Files, Folder Browse, Inside Files, and Meaning modes in the CLOUDWERX OS launcher](/media/posts/2026-11-29-fourteen-million-files-in-milliseconds/launcher-modes.gif)

I want to walk through how it actually works under the hood, because almost every speed win came from a handful of very simple data layout choices rather than anything fancy.

## Three indexes behind one Unix socket

The launcher itself (a Quickshell QML panel), the `cloudwerx search` CLI, and the Settings page all speak one line-delimited JSON protocol over `$XDG_RUNTIME_DIR/cloudwerx-search.sock` (mode `0600`). None of them touch indexes directly.

```mermaid
flowchart TD
    UI["Launcher (Super+Space) / CLI / Settings"] -->|JSON lines over 0600 Unix socket| S["cloudwerx-search.sock"]
    S --> D["cloudwerx-searchd (Rust user service)"]
    D --> N["Tier 1: NameIndex in RAM (14.3M entries)"]
    D --> T["Tier 2: Tantivy BM25 (41,195 docs)"]
    D --> M["Tier 3: Model2Vec int8 Store (483,857 passages)"]
    W["inotify watcher (140,346 dirs)"] -->|live deltas + debounce| D
    T --> RRF["Reciprocal Rank Fusion (k = 60)"]
    M --> RRF
```

One tiny detail in `server.rs` makes typing feel way snappier than raw query times suggest. Every socket client gets a reader thread feeding a channel to a worker loop. When a burst of keystrokes arrives faster than a query finishes, the worker drains the channel and drops every older `"op": "search"` request in the queue, replying with `"skipped": true` to all of them except the last one. You never burn CPU finishing a query for `"se"` when the user already typed `"semantic.rs"`.

| Prefix | Mode | Engine | What it searches |
|---|---|---|---|
| *(none)* | All | Apps + `NameIndex` | Launches apps first, then top file matches |
| `/` | Files | `NameIndex` (`nucleo` + `u64` mask) | Every file and folder by name or path |
| `/~/Code/` | Browse | `NameIndex` child list | Instant folder listing and tab completion |
| `#` | Inside files | `Tantivy` BM25 + `Model2Vec` RRF | Words inside files blended with meaning |
| `~` | Meaning | `Model2Vec` (`potion-retrieval-32M`) | Passages by conceptual similarity |

You can stack filters in every mode (`ext:pdf`, `size:>10mb`, `mod:week`, `in:~/Documents`, `is:code`), and if you hit `Tab` on any result, [QuickView](https://blog.cloudwerxlab.com/post/quickview-space-to-preview) pops open right on top of the launcher so you can inspect a PDF, Markdown file, or 3D model without closing your search.

## Tier 1: Packing 14.3 million entries into RAM

If you try to store 14.3 million `PathBuf` strings in Rust, you will hate your life. Every `PathBuf` is a heap allocation, most path prefixes repeat thousands of times across deep trees like `~/.cargo` or `node_modules`, and iterating 14 million scattered heap pointers trashes your L3 cache before you even compare a single character.

Instead, `names.rs` splits the whole filesystem into two flat arrays and one giant contiguous string buffer:

```rust
#[derive(Clone, Copy, Debug)]
pub struct Entry {
    pub parent: u32,
    name_off: u32,
    name_len: u16,
    pub kind: u8,
    pub flags: u8,
    pub mtime: u32,
    pub size: u64,
}
```

Count those bytes: $4 + 4 + 2 + 1 + 1 + 4 + 8 = 24$ bytes per entry, `Copy`, zero pointers, and zero heap allocations per file. Only the basename is stored, appended into one big `names: String` arena. If a folder has 400 files inside it, the parent folder path isn't duplicated 400 times. It's just `parent: u32`.

Even better: when the parallel filesystem walker (`scan.rs`) builds the tree and hands it to `NameIndex::add_tree`, it inserts children **breadth-first**. Every sibling in the same folder ends up sitting right next to each other in `entries: Vec<Entry>`. When a query does need a full path (like `in:work` or `code/srch`), the hot loop keeps a one-entry `ParentCache` holding the last `parent` ID and its string path. Because siblings are adjacent in memory, `parent_path.id == e.parent` hits almost every single time without climbing the tree.

> [!NOTE] Why not store one `u64` inside `Entry`?
> `masks: Vec<u64>` lives in its own parallel `Vec` instead of inside `Entry`. During the hot scan, threads read `masks[id]` sequentially (8 bytes per item, 8 items per 64-byte cache line) and only touch the 24-byte `Entry` struct or the `names` string arena if the bitmask passes.

### The 64-bit character mask prefilter

Before Helix's fuzzy matcher (`nucleo-matcher`) ever sees a filename, `score_entry` checks a single 64-bit integer.

When an item is added to `NameIndex`, `char_mask()` folds its basename into a bitset: bits `0..25` for `a..z` (case-folded), `26..35` for `0..9`, `36..39` for `.`, `-`, `_`, and space, bit `40` for other ASCII, and bit `63` (`NON_ASCII`) if any non-ASCII character appears.

At query time, `needle_mask()` computes the bitset $M_{\text{query}}$ of required characters in your search words once. Then for each entry $i$ with mask $M_i$, the rejection test is literally one bitwise operation:

$$
(M_{\text{query}} \land \neg M_i) \neq 0 \quad \text{and} \quad (M_i \land 2^{63}) = 0
$$

In Rust:

```rust
let have = self.masks[id as usize];
if p.mask & !have != 0 && have & NON_ASCII == 0 {
    return None;
}
```

Think about what that does when you type `/semantic.rs`. Every filename in the entire OS that lacks an `s`, `e`, `m`, `a`, `n`, `t`, `i`, `c`, `.`, or `r` gets tossed out in a couple of CPU cycles without decoding UTF-8, without touching `names`, and without calling `nucleo`. Only entries containing `NON_ASCII` bypass the mask (because Unicode smart normalization might fold `é` to `e`).

Once an entry clears the mask and metadata filters (`ext:`, `size:`, `mod:`), Rayon splits `entries` into chunks of `8192` items (`par_chunks(8192)`) across all cores. Each worker grabs a thread-local `nucleo_matcher::Matcher` and keeps a tiny min-heap (`BinaryHeap<Reverse<(i32, u32)>>`) of the top candidates in its chunk. Then a small bonus function breaks ties:

- Exact filename match: `+90`, exact stem match: `+70`, prefix match: `+25`
- Inside `$HOME`: `+30`
- Hidden file (unless you typed a dot or `hidden:yes`): `-45`
- Noisy system or build folders (`/usr/lib`, `/var/lib`, `target`, `node_modules`): `-30`
- Modified in the last 24h / 7d / 30d: `+18` / `+12` / `+6`
- Shallower paths beat deeply nested ones (`-(depth - 3).clamp(0, 10) * 2`)
- Frecency boost from `~/.local/share/cloudwerx/search/usage.json` for files you actually opened before

![Searching 14.33 million indexed items for /semantic.rs with live Rust preview](/media/posts/2026-11-29-fourteen-million-files-in-milliseconds/launcher-names.png)

## Why I refused to use fanotify

People always ask why a Linux desktop search tool doesn't just use `fanotify` to watch the whole disk instead of `inotify`.

On Linux, `inotify` isn't recursive. You have to walk your directory tree and call `inotify_add_watch` on every single folder, one inode at a time. Right now `cloudwerx-searchd` holds **140,346** active `inotify` watches against a kernel limit (`fs.inotify.max_user_watches`) of `1,048,576`. `fanotify`, by contrast, has `FAN_MARK_MOUNT` and `FAN_MARK_FILESYSTEM`, which watch an entire mount point recursively with zero races.

So why not use `fanotify`? Because mount-wide `fanotify` requires `CAP_SYS_ADMIN` (root), since `fanotify` can observe and even intercept file opens across every user on the system.

I refuse to put a root daemon on a desktop search bar. `cloudwerx-searchd` runs strictly as an unprivileged systemd user service (`cloudwerx-search.service`). Your home folder and content roots get live `inotify` updates within milliseconds of saving or renaming a file, and the rest of `/` (`/usr`, `/etc`, mounted drives) rescans in parallel every 20 minutes. A full walk of all **14,330,935** entries across `/` took **36,121 ms** on last scan, running at `nice 15` and `IOPRIO_CLASS_IDLE` so you never feel it.

Here's `prio.rs` if you want to steal those two Linux syscalls for your own background Rust indexers:

```rust
pub fn lower_current_thread() {
    unsafe {
        let tid = libc::syscall(libc::SYS_gettid) as libc::id_t;
        libc::setpriority(libc::PRIO_PROCESS, tid, 15);
        const IOPRIO_WHO_PROCESS: libc::c_long = 1;
        const IOPRIO_CLASS_IDLE: libc::c_long = 3;
        libc::syscall(libc::SYS_ioprio_set, IOPRIO_WHO_PROCESS, tid as libc::c_long, IOPRIO_CLASS_IDLE << 13);
    }
}
```

And one subtle glibc detail in `prio.rs`: after a big full-disk rescan swaps out the old 14.3M-entry `NameIndex` for a fresh one, the watcher calls `libc::malloc_trim(0)`. Without that, glibc holds onto freed heap arenas and RSS stays inflated by hundreds of megabytes after every rebuild.

## Tier 2: Full-text search without Tantivy's QueryParser

For `#` searches (words inside files), `cloudwerx-searchd` embeds **Tantivy** (`0.26`), the Rust full-text engine inspired by Lucene. It extracts text from plain text, Markdown, HTML (stripped cleanly), source code, PDFs (via `pdftotext -l 300` with a 30-second timeout), and zipped XML office documents (`.docx`, `.xlsx`, `.pptx`, `.odt`, `.ods`, `.odp`, `.epub`).

> [!WARNING] Zip bomb protection
> Cracking open `.docx` and `.xlsx` files inside a background indexer means parsing untrusted archives from `~/Downloads`. `extract.rs` caps any single decompressed zip member at `32 MiB` (`MAX_ZIP_MEMBER`) and stops reading extracted text per file at `1,000,000` characters (`MAX_TEXT`), while skipping lockfiles and `.min.js` / `.min.css` / `.map` bundles completely.

Here's the interesting part in `content.rs`: I did **not** use Tantivy's built-in `QueryParser`.

Standard query parsers expect complete words and choke on partial syntax while someone is mid-word. If you type `#deduc`, you want `Deductible` to pop up right now, before you finish typing `tion`.

Because Tantivy stores each field's term dictionary as a Finite State Transducer (FST), `content.rs` builds queries by hand. For the word you're actively typing (or any word of 3+ chars, or 2+ chars if it's the trailing partial word), `expand_prefix` opens a byte range stream `[prefix, prefix + 1)` on the inverted index across segments, reads up to 4,000 matching terms, sorts by document frequency, and expands the top `24` most common completions (`PREFIX_TERMS = 24`) as `0.7x`-weighted `Should` clauses alongside the exact term (`1.0x`). Matches in the filename (`name` field) also get a `2.0x` `BoostQuery` over `body`.

```rust
let mut upper = prefix.as_bytes().to_vec();
if let Some(last) = upper.last_mut() {
    *last = last.saturating_add(1);
}
for seg in searcher.segment_readers() {
    let Ok(inv) = seg.inverted_index(field) else { continue };
    let Ok(mut stream) = inv.terms().range().ge(prefix.as_bytes()).lt(&upper).into_stream() else { continue };
    // collect top 24 completions by doc_freq
}
```

No regex scans, no slow wildcards. Just an FST range walk, BM25 scoring, exact `"quoted phrases"`, `-negation`, and `SnippetGenerator` highlights.

## Tier 3: Semantic search with Model2Vec and int8 quantization

Full-text search fails the second you forget what words you wrote. Maybe your note says *"CachyOS Btrfs snapshots with Snapper and Limine"*, and three weeks later you search *"roll back operating system update snapshot"*. None of `"roll"`, `"operating"`, `"system"`, or `"update"` show up cleanly together.

Usually, local semantic search means running a transformer model (ONNX, llama.cpp, or a Python server), waiting seconds per file during indexing, and chewing through battery.

Instead, `cloudwerx-searchd` uses **Model2Vec** (`model2vec-rs`) with MinishLab's `minishlab/potion-retrieval-32M`. Model2Vec distills a sentence transformer (`BAAI/bge-base-en-v1.5` in this case) down into a **static token embedding table** of **512-dimensional** vectors (~32.3M parameters). There is no attention layer and no transformer forward pass at runtime. Embedding a passage is literally tokenizing, looking up each token's 512-float vector in a table, and averaging them. It scores `35.06` on MTEB Retrieval (over 81% of `all-MiniLM-L6-v2`) at hundreds of times the speed on plain CPU.

### Filtering junk before it pollutes the vector store

Source trees and home folders are full of garbage that looks like text: SHA-256 hashes, base64 blobs, JWTs, lockfiles, minified bundles. Embed those and your vector space fills up with junk.

`semantic.rs` splits prose into roughly `700`-character passages (`CHUNK_CHARS = 700`, capped at `200` passages per file) along paragraph, line, sentence, and word boundaries, prepends a cleaned filename title (`tax_return-2025.pdf` becomes `tax return 2025`), and runs `is_prose()` on every chunk before embedding:

- At least 4 whitespace-delimited words and 12 alphanumeric characters
- Average word length $\le 14.0$ characters
- At least 50% of words must be at least half alphabetic letters
- At most 20% of words can exceed 30 characters

That simple five-line heuristic deletes base64, hex dumps, and minified JS before they ever reach the embedder.

### 4x smaller vectors with scalar int8 quantization

Right now the semantic store holds **483,857 passages** across **37,245 files** at **512 dimensions**.

If you keep `483,857` 512-dim vectors in `f32`, the raw vectors alone eat:

$$
483{,}857 \times 512 \times 4\text{ bytes} \approx 990.9\text{ MB}
$$

Instead, `semantic.rs` quantizes each passage vector independently to signed 8-bit integers (`i8`) with a single `f32` scale factor per passage:

$$
s = \frac{\max_i |v_i|}{127.0}, \qquad q_i = \text{clamp}\!\left(\text{round}\!\left(\frac{v_i}{s}\right), -127, 127\right)
$$

At query time, the query vector $u$ stays in `f32`, and scoring a passage is an integer-to-float multiply-accumulate scaled once at the end:

$$
\text{score}(q, u) = s \sum_{i=1}^{512} q_i \, u_i
$$

That drops the raw vector array from **990.9 MB** down to **247.7 MB** (`483,857 * 512` bytes, plus ~1.9 MB for scales), and the entire `vectors.bin` file on disk (including all 37,245 file paths and 280-char passage previews) is `414,332,427` bytes (~395 MiB). And because it's one flat contiguous `Vec<i8>` chunked in parallel via `vecs.par_chunks(dim * 1024)`, an **exhaustive exact search** across all 483,857 passages finishes in **21 to 45 ms** with zero approximate-nearest-neighbor index (no HNSW graph RAM overhead, no stale deletions, exact top-k).

![Meaning search finding SNAPSHOTS.md from a conceptual description in 59 ms](/media/posts/2026-11-29-fourteen-million-files-in-milliseconds/launcher-meaning.png)

## Blending words and meaning with Reciprocal Rank Fusion

When you use `#` mode (`Inside files`), `engine.rs` runs **both** Tantivy BM25 and the Model2Vec vector search, then combines them using **Reciprocal Rank Fusion (RRF)** from Cormack, Clarke, and Büttcher's 2009 SIGIR paper.

The whole reason RRF works so well in hybrid search is that BM25 scores (unbounded positive floats like `14.8`) and cosine similarities (`0.0` to `1.0`) are on completely incomparable scales. RRF ignores raw scores and fuses by rank position $r(d)$ with smoothing constant $k = 60$:

$$
\text{RRF}(d) = \frac{1}{60 + r_{\text{BM25}}(d)} + \frac{0.9}{60 + r_{\text{sem}}(d)}
$$

If a document ranks near the top in **both** keyword matching and meaning, it jumps straight to the top (`source: "text+meaning"`). If it matches only your words (`"text"`) or only your intent (`"meaning"`), it still gets a fair shot.

### The static-embedding trap (and the 0.45 gate)

Here is something you learn fast when shipping static embeddings in a real app: **every vector store always has a nearest neighbor**.

Type total nonsense like `asdfqwer` into a pure vector search and it will happily compute cosine similarities across 483,857 passages and return the "closest" 20 files with confidence. On `potion-retrieval-32M`, real semantic matches usually land between `0.50` and `0.75`, while unrelated noise clusters around `0.30` to `0.47`.

So `engine.rs` enforces two gates on semantic results:
1. An **absolute score floor**: `0.45` (`HYBRID_FLOOR`) when mixing into `#` keyword search, or `0.30` (`MEANING_ONLY_FLOOR`) in `~` meaning-only mode.
2. A **relative cutoff**: every hit must stay within `75%` of the top hit's score in hybrid mode (`HYBRID_REL = 0.75`), or `70%` in meaning mode (`MEANING_ONLY_REL = 0.70`).

It also tracks the running mean $\mu$ and standard deviation $\sigma$ across all 483,857 passages during every scan so each hit carries its $z$-score ($z = (\text{score} - \mu)/\sigma$) for diagnostics.

![Hybrid # search blending Tantivy BM25 snippets and semantic matches with RRF](/media/posts/2026-11-29-fourteen-million-files-in-milliseconds/launcher-hybrid.png)

## Real numbers on my actual laptop

Numbers from unit tests on 50 synthetic files lie. Here are real timings measured directly against my running `cloudwerx-search.sock` across **14,330,935** name entries, **41,195** Tantivy documents, and **483,857** quantized passages:

| Mode | Query | Cold (ms) | Warm (ms) | What actually happened |
|---|---|---|---|---|
| Names | `changelog in:~/Code/cloudwerx-os` | 16.09 | **11.54** | Resolved folder to `u32`, walked subtree only |
| Names | `semantic.rs` | 26.06 | **16.40** | Global 14.3M scan, `u64` mask + `nucleo` |
| Names | `changelog` | 113.67 | **30.19** | Global 14.3M scan across all mounts |
| Names | `ext:frag in:~/Code/cloudwerx-os` | 53.77 | 74.26 | No name word -> mask is `0`, tests every extension |
| Meaning | `how do I make the desktop look different` | 40.56 | **21.84** | Exhaustive dot product over 483,857 `int8` vectors |
| Meaning | `roll back operating system update snapshot` | 31.19 | 31.19 | Returned `docs/SNAPSHOTS.md` #1 without keyword match |
| Hybrid `#` | `shader transition` | 350.76 | **67.89** | Tantivy BM25 + FST prefix + `int8` RRF fusion |
| Hybrid `#` | `reciprocal rank fusion` | 451.58 | 391.31 | Multi-term BM25 + snippet generation over 41k docs |

Look at row 4 (`ext:frag`): it's actually *slower* than searching `"semantic.rs"` across 14.3 million files! Why? Because without a filename pattern, `needle_mask` is `0`, so the 64-bit bitmask shortcut passes everything and `score_entry` has to inspect extensions across entries. That one measurement immediately shows why the bitmask does almost all the heavy lifting.

> [!INFO]- Live daemon stats (`cloudwerx search status --json`)
> ```json
> {
>   "memory": 975601664,
>   "disk": 778281021,
>   "names": {
>     "files": 13923933,
>     "folders": 407002,
>     "scan_ms": 36121,
>     "watched": 140346,
>     "watch_limit": 1048576
>   },
>   "content": { "documents": 41195, "state": "ready" },
>   "meaning": {
>     "model": "potion-retrieval-32M",
>     "files": 37245,
>     "passages": 483857,
>     "bytes": 414332427
>   }
> }
> ```

## Live config and Settings integration

The Settings UI (`cloudwerx desktop search`) writes straight to `search` in `~/.config/cloudwerx/settings.json`, and the same `inotify` watcher monitors that config file for `CLOSE_WRITE`. Save a change in Settings (turn off PDF indexing, add an exclusion folder, swap from `potion-retrieval-32M` to `potion-base-8M` or `potion-multilingual-128M`) and `cloudwerx-searchd` diffs the scope string and rebuilds *only* the affected index without restarting the service.

It also keeps a `manifest.json` mapping each file path to `(mtime, size, flags)` where the bit flags track whether it was embedded or failed extraction. On restart, it skips everything unchanged, commits incremental batches every `800` files or `20` seconds (newest files first!), and checks its live-event channel *between* batches (`interleave_live`) so a file you edit while a big sync is running still shows up immediately.

![CLOUDWERX Settings File Search configuration page](/media/posts/2026-11-29-fourteen-million-files-in-milliseconds/settings-search.png)

If you're building a local search tool in Rust, here's the cheat sheet I wish I had on day one: pack metadata into flat `Copy` structs with a shared string arena, put a character bitmask in front of your fuzzy matcher, skip `QueryParser` in favor of FST prefix expansion if you care about search-as-you-type, quantize static Model2Vec embeddings to `i8`, and gate your semantic floor hard before fusing with RRF. You get Windows Everything speed, Lucene-grade text matching, and offline conceptual search in one tiny binary, and nothing ever leaves your laptop.

If you want to see how this ties into the rest of the desktop, check out [the Btrfs snapshot rollback stack](https://blog.cloudwerxlab.com/post/undo-for-your-whole-os) (the same docs `~roll back operating system update snapshot` surfaced in 31 ms) or [my theme engine](https://blog.cloudwerxlab.com/post/one-palette-every-app).

## Sources

- [CLOUDWERX OS (`apps/search`)](https://github.com/CLOUDWERX-DEV)
- [helix-editor/nucleo (parallel fuzzy matcher)](https://github.com/helix-editor/nucleo)
- [quickwit-oss/tantivy (Rust full-text search engine)](https://github.com/quickwit-oss/tantivy)
- [MinishLab/model2vec (static embedding distillation)](https://github.com/MinishLab/model2vec)
- [minishlab/potion-retrieval-32M on Hugging Face](https://huggingface.co/minishlab/potion-retrieval-32M)
- [Cormack, Clarke, Büttcher (SIGIR 2009): Reciprocal Rank Fusion](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf)
- [Linux `fanotify(7)` manual page](https://man7.org/linux/man-pages/man7/fanotify.7.html)
- [Linux `inotify(7)` manual page](https://man7.org/linux/man-pages/man7/inotify.7.html)
- [voidtools Everything](https://www.voidtools.com/)
