legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation

legit-hamming

Exact search within a Hamming radius over 64-bit and 256-bit hashes held in memory: every stored record within distance d of a query, with its distance, and never a match missed. It is a Rust library, and a program, legit-hamming, that serves named indexes as a search service, on the command line and, with the serve feature, as a worker on Redis Streams.

A record is a fixed-width value, u64 or [u64; 4], with an application's 64-bit id or without one. Each query is answered by a vectorised scan or by multi-index hashing, whichever is expected to cost less, and every way of answering is checked against one plain reference scan. The library has no framework dependency.

When to use it

Use it when a query needs every stored hash within a Hamming distance, exactly and fast, from a set that fits in memory: perceptual hashes of images or video frames, SimHash fingerprints of text, binary codes from a model. Over about 90 million real 64-bit perceptual hashes of one image collection, it answers a query at radius 5 in about 0.7 ms on one core, and a scan of the whole set takes about 42 ms.

It is not for:

  • approximate search: it never trades recall for speed. If approximate answers will do, an approximate nearest-neighbour index (HNSW, IVF, product quantisation) is smaller and faster;
  • real-valued vectors: it is not a vector database, and has no other distance than Hamming;
  • values that are not 64 or 256 bits: those are the two widths it holds. A shorter hash can be padded with zeros to 64 bits, which leaves its distances unchanged; a longer one can't be held;
  • sets that don't fit in memory, or that must change transactionally with other data: a database holds those better. A B-tree on the value finds exact duplicates only; a database extension for Hamming distance (a BK-tree or a bit-vector index) answers the same question with the database's durability, more slowly;
  • radii so large, or data so uniform, that most queries match much of the set: every exact method then reads most records, and a scan is the best there is. This crate does that scan, but nothing does better.

Installation

[dependencies]
legit-hamming = "0.1"

The program, with the worker:

cargo install legit-hamming --locked --features serve

It needs Rust 1.99 or newer. The library depends on memmap2, serde, serde_json and sha2; the serve feature adds legit-streams (and through it the redis client), signal-hook, tracing and tracing-subscriber; --locked builds with the dependency versions the release was tested with. Those are version ranges: a worker you deploy is best built from a lock file you have tested.

Example

use std::sync::Arc;

use legit_hamming::{Isa, Options, Planned, Records, Strategy, search, search_batch};

fn main() -> Result<(), legit_hamming::Error> {
    // Records in rising id order: the id is the application's own, such as a row's key.
    let mut records = Records::with_ids();
    records.push(17, 0x9f3a_0000_0000_00ffu64)?;
    records.push(90_211_344, 0x9f3a_0000_0000_00fe)?;
    for id in 100_000_000..100_100_000u64 {
        records.push(id, id.wrapping_mul(0x9e37_79b9_7f4a_7c15))?;
    }

    // The records and, within 1 GiB, multi-index tables over them, built on 4 threads.
    let index = Planned::new(Arc::new(records), 1 << 30, 4);

    let found = search(&index, 0x9f3a_0000_0000_00ff, &Options::new(5).threads(4));
    for m in &found.matches {
        println!("{:?} {:016x} at distance {}", m.id, m.value, m.distance);
    }
    assert_eq!(found.matches.len(), 2);
    assert!(found.is_complete());
    // A near query reads a few table entries rather than every record...
    assert_eq!(found.plan.map(|plan| plan.strategy), Some(Strategy::MultiIndex));

    // ...and a batch with a limit keeps the nearest matches of each query.
    let batch = search_batch(&index, &[0, u64::MAX], &Options::new(8).limit(50));
    assert_eq!(batch.len(), 2);
    println!("paths here: {} at 64 bits, {} at 256", Isa::best_for::<u64>(), Isa::best_for::<[u64; 4]>());
    Ok(())
}

The variants

Every variant implements one trait, Search, and search and search_batch run any of them.

Variant What it is Memory per record beyond the records
Planned The records and, within a memory budget, multi-index tables; each query scans or probes, whichever its estimate says costs less 16 bytes at 64 bits, 64 at 256, plus 256 KiB a table, if the tables fit the budget; 0 without them
Scan A flat scan of the value columns in tiles of 16,384 records, every query of a batch on a tile before the next, on a code path chosen at run time 0
MultiIndex Multi-index hashing alone: the value in 16-bit chunks (4 at 64 bits, 16 at 256), a table per chunk, probed with every key within the chunk's radius; it scans only where its keys outnumber its records as Planned with tables
Reference Every record against the query, one at a time, with nothing but count_ones: what every other variant is checked against 0
Mapped A snapshot file scanned in place from a memory map 0 in the heap; the files in the page cache

The records are structure-of-arrays: a column of ids and one column per 64-bit word of the value, most significant word first. A 64-bit record takes 16 bytes with its id and 8 without; a 256-bit record 40 and 32. So 90 million 64-bit records with ids take 1.34 GiB, and their tables 1.34 GiB more; 90 million 256-bit records 3.35 GiB, and their tables 5.37 GiB. A set holds at most 2³² − 1 records, so a position fits in a u32, and the tables index positions, which map back to ids through the id column. Records that share a value are each held and each returned: thousands of ids can share one value in real data, and nothing deduplicates by value.

search and search_batch return a Found per query: the matches sorted by distance and then id, or for a set without ids by position in the set, the candidates the query cost, the plan it ran with, and cut_by. A result is complete unless cut_by says what cut it: the caller's limit (keeps the nearest by distance, never the first found), a size budget max_matches (the same, set by a service), or a time_budget. Whatever cut it, every record nearer than the farthest match returned is returned. A limit or size budget also bounds the memory a search holds, not only the list it returns: each variant trims its hits as it goes, at least every 1,024 records compared (TRIM_RUN), so a list that keeps k never holds more than max_hits(k) = 2k + 5,119 hits of 8 bytes, its capacity included, for each query and each thread: a million records at distance 0 cost about five thousand hits held, not a million. The time budget is a search budget: the search stops collecting candidates once it has passed, looking at the clock about every thousand records' work, and the result follows as soon as what was collected is merged; merging, sorting and building the result aren't within it. A search cut by time hasn't reached every record, and any it didn't reach could be nearer than a match it found, so it returns only its matches at distance 0, which nothing is nearer than. Nothing is cut silently. exclude_zero leaves the all-zero value out, dropping those records as the search goes. search_batch_excluding leaves out any records a caller names by position the same way, where the hits are kept and before a limit trims them, so a set that masks some of its records, as the search service masks a snapshot's changed records, still gets the nearest limit of the rest.

neighbour_table samples an index's own records with a seed and counts, for each distance up to a bound, the other records at exactly that distance: the measured floor of unrelated neighbours, run on whatever variant is given. It counts each match into the table as the search finds it, so a cluster of millions of identical records costs no match list.

Exactness

Every variant returns exactly the reference's result set, on every code path, at every radius, and Planned does whichever way it runs: the plan changes the cost, never the answer. The test suite runs each variant on each path the CPU has against the reference over random and adversarial data: exact duplicates, a heavy cluster of near copies, all-zero and all-one values, values at exactly distance d and d + 1 from the queries, and, at 256 bits, values whose every difference is in the first word. Planned is checked at every radius from 0 to one past the width, with tables and without, choosing and forced each way. Breaking the AVX-512 compare, a byte of the nibble lookup table or the multi-index deduplication each fails it.

  • Multi-index radii. m chunks probed within r bits each find every value within m(r + 1) − 1 (guaranteed_radius). For a radius d = m·q + s with 0 ≤ s < m, chunk_radii probes the first s + 1 chunks within q and the rest within q − 1 (or not at all when q is 0): a value escaping every probe differs in at least m·q + s + 1 = d + 1 bits. Four 16-bit chunks probed exactly find every pair to distance 3, and with radii 2, 1, 1, 1 every pair to 8. A record reached from two tables is kept only from the first that reaches it.
  • Every record is in every table. A table holds every position under its chunk's key, so records with equal values are separate entries, each compared and each returned.
  • The plan only chooses. A scan compares every record and a probe every record its keys hold; both are exact on their own, and Planned runs one or the other per query.

Scan or index: how Planned chooses

For each query, Planned counts what a probe of its tables would read: the keys within each chunk's radius, and the entries those keys hold, summed from the tables' own bucket sizes for that query's keys. That sum is exact, not a model, and it costs a lookup of two offsets a key, no posting read. It compares the probe's cost with a scan's:

  • a probe costs its keys plus CANDIDATE_COST times its candidates, in records scanned;
  • a scan costs its records;
  • the cheaper runs, and a tie scans.

Counting stops as soon as the probe is sure to cost more, and doesn't start where the keys alone outnumber the records, the rule MultiIndex scans by (scans_at). Without tables, every query scans. A batch scans its scanning queries together, in one pass over the records, and probes the rest.

CANDIDATE_COST is 32: a candidate costs 32 records scanned. It comes from radius sweeps on an Intel Xeon Gold 5412U, one thread, on 2 December 2026, as the time a multi-index query took per candidate over the time the best scan (avx512) took per record, at the radii where candidates dominate:

Records Scan, ns a record Multi-index, ns a candidate Ratio
1 million synthetic, 64-bit, radius 12 and 16 0.22 8.9 to 10.6 40 to 48
10 million synthetic, 64-bit, radius 8 to 16 0.41 19.5 to 21 47 to 51
1 million synthetic, 256-bit, radius 48 to 96 0.8 31 to 36 39 to 45
10 million synthetic, 256-bit, radius 48 to 96 1.7 53 to 54 31 to 32
About 90 million real, 64-bit, radius 8 0.43 7.3 17

The real values are about 90 million real 64-bit perceptual hashes of one image collection (see Which plan wins). 32 is the low end of the synthetic range and within twice both its high end and the real values, whose near neighbours sit closer together in the tables, so a plan chosen on the wrong side of the line costs at most about twice the other. On the real values, swept from radius 0 to 16, the plan took the faster way at every radius, so they need no constant of their own.

Threads follow the same estimate. A call gets one thread for every WORK_PER_THREAD (250,000) 64-bit words of work it expects, at least 1 and at most the threads given; a probe's work is its cost times the value's words. 250,000 words is about 0.11 ms of AVX-512 scanning on one core of the benchmark host, so a single query expected to finish in well under a millisecond runs on one thread, and a scan of millions of records, or a large batch, on every thread given. The rule comes from this thread sweep on that host (16 threads, 24 GiB):

Workload, one query at a time 1 thread 2 4 8 16 Rule
multi-index, 1 million, radius 8 (0.04 ms) 22,639 13,921 11,408 7,046 3,756 1
multi-index, 1 million, radius 5 (0.009 ms) 111,146 16,219 11,419 6,755 3,828 1
scan, 1 million, radius 8 (0.18 ms) 5,588 6,722 8,058 5,755 3,704 4
multi-index, about 90 million real, radius 5 (0.74 ms) 1,290 1,546 1,744 1,699 1,662 4
multi-index, about 90 million real, radius 8 (2 ms) 484 712 1,144 1,192 1,168 4
scan, about 90 million real, radius 8 (39 ms) 25.8 40.7 88.6 140 185 16

Queries a second, medians of 3 runs; the 1 million records are synthetic. A probe of one query splits its tables between threads, so it never gets more threads than tables it probes: 4 at 64 bits. Two rows of the 90-million sweep where Planned on 16 threads ran slower than the plain tables are in Which plan wins.

The plan chosen at each radius of the sweep, on synthetic records on the same Xeon, limited to 2 threads and 7 GiB, one thread, queries a second (medians of 3 runs; the tables have 16-bit chunks):

64 bits, radius 0 2 3 5 8 10 12 16
1M: best scan 4,149 4,254 4,074 4,734 4,361 4,202 3,741 3,996
1M: multi-index 1,353,125 743,423 650,682 104,505 19,383 11,072 5,157 1,449
1M: Planned 988,777 587,579 536,968 90,870 21,737 12,095 5,249 3,916
1M: its plan index index index index index index index scan
10M: best scan 261 253 235 222 224 225 241 227
10M: multi-index 186,058 74,194 57,668 7,046 1,557 704 249 64.4
10M: Planned 169,039 71,733 57,574 6,901 1,453 685 266 231
10M: its plan index index index index index index index scan
256 bits, radius 8 16 31 48 64 80 96
1M: best scan 1,163 1,150 1,170 1,156 1,201 1,245 1,143
1M: multi-index 90,046 30,800 3,924 588 140 43.9 17.6
1M: Planned 96,077 34,064 4,953 1,118 1,223 1,097 1,092
1M: its plan index index index scan scan scan scan
10M: best scan 57.4 59.2 57.3 58.3 57.5 56.8 57.1
10M: multi-index 11,254 3,384 419 42.6 9.27 2.72 1.01
10M: Planned 11,254 3,606 421 61.3 60.4 61.7 60.2
10M: its plan index index index scan scan scan scan

It takes the faster way at every radius; where the two are close, at radius 12 on 64 bits, either is within a few percent. Planning costs a few hundred nanoseconds a query, which shows only on queries that finish in a microsecond or two (989,000 a second against 1,353,000 at radius 0 on 1 million records). On 2 threads the thread rule shows: a query at radius 0 on 1 million records ran 2,480,774 times a second through Planned, which keeps it on one thread, against 18,259 through a multi-index split across both.

Code paths

Isa::best_for::<V>() picks the path for a width at run time, from what the CPU has and the measurements below; Cpu::detect() reports the instruction sets found, the paths available, the best at each width and the thread count. Every path has a scalar fallback, and asking for a path the CPU lacks is an error.

Path Technique
scalar count_ones per word as the build target compiles it (a software routine on a baseline x86-64 build, a vector count on Arm), four records unrolled
popcnt the same code compiled with the popcnt instruction enabled, under run-time detection
avx2 the per-lane nibble lookup of Muła, Kurz and Lemire: vpshufb on each nibble, then vpsadbw against zero for one count per 64-bit lane; four records a vector at either width, because the 256-bit columns are separate and the four words' byte counts are summed before vpsadbw
avx512bw the same nibble lookup on 512-bit vectors, for AVX-512 CPUs without VPOPCNTDQ (Skylake-X and Cascade Lake servers); eight records a vector, compared with the radius to a mask
avx512 vpopcntq per 64-bit lane and a compare to a mask against the radius, which gives the survivors directly; eight records a vector
neon vcntq_u8 then vpaddlq widening adds to a count per 64-bit lane, two records a vector
neon-wide 64 bits: four vectors, eight records, a step; three rounds of vpaddq_u8 narrow their byte counts into one byte a record, compared with the radius in the vector unit, so only a step with a survivor leaves it. At 256 bits it runs the neon kernel

What Isa::best_for picks:

  • x86-64, either width: avx512, then avx512bw, then avx2, then popcnt, then scalar. On an Intel Xeon Gold 5412U, one thread, 10 million synthetic records, avx512bw ran 179 single 64-bit queries a second against 128 for avx2 and 228 for avx512, and 484 against 276 and 738 in a batch of 1,000; at 256 bits, radius 31, the three tied on single queries (47.7, 48.1 and 50.7, all held up by memory), and avx512bw ran batches at 133 against 88.8 for avx2. It beat avx2 on every subset too, so it ranks ahead of avx2.

  • aarch64, 256 bits: neon. On an Apple M2 Pro (10 cores), one thread, radius 31, on 2 December 2026: 148 queries a second against 92.9 for scalar at 10 million synthetic records (1.6 times), 1,492 against 939 at 1 million, and 654 against 403 on a 2.3-million subset.

  • aarch64, 64 bits: neon-wide. On the same CPU, radius 8, it ran 1.4 to 1.6 times scalar on every workload measured: 671 single queries a second against 466 at 10 million records on one thread, 7,205 against 4,658 at 1 million, 763 against 477 in batches of 1,000 (4,286 against 3,015 on 8 threads), and 3,101 against 2,005 on a 2.3-million subset. The compiler already turns count_ones into a vector count there, so the neon kernel, which tests two records at a time, ran 0.68 times scalar (319 a second at 10 million, 3,155 at 1 million); it stays selectable by name, for comparison.

  • Anything else: scalar.

Stable Rust (1.100) has no SVE intrinsics (std::arch::aarch64 offers NEON only), so there is no SVE path.

The 512-bit kernels at 256 bits prefetch each of the four columns 128 records (1 KiB) ahead. Measured on the Xeon, limited to 2 threads, at 10 million synthetic records, radius 31, one thread, that ran single queries 14% faster and batches of 1,000 29% faster than no prefetch; prefetching 64 to 512 records ahead was within 3% of that, and 2,048 gave back half the gain. Three other layouts of the 256-bit scan, measured the same way, lose to the one used:

  • the four words of a record side by side in one 32-byte stream: batches of 1,000 26% faster (190 against 151 a second), but single queries 7% slower (46 against 49.9);
  • the columns on transparent huge pages (madvise): 49.8 against 49.9, no change, though the machine granted huge pages to only 40 MiB of the 640 MiB advised;
  • the batch tile size, 4,096 to 262,144 records: 16,384 and 32,768 within each other's spread, 8,192 and 4,096 3% and 12% slower, 65,536 and over 24% to 47% slower. It is 16,384.

The paper's Harley-Seal adder tree isn't used: it sums across a stream and can't give the count per record that a radius test needs. unsafe code lives in three modules only, kernel/x86.rs, kernel/arm.rs and mapped.rs, each block with a SAFETY: comment. The kernels are behind safe wrappers that check the CPU before every call; the map's constructors are unsafe fns whose caller promises the files don't change while mapped (see Snapshots). The rest of the crate denies unsafe.

Snapshots

A snapshot is a directory of part files and a MANIFEST.json. A part is fixed-width little-endian records with no header: 8 bytes of id then the value (16 bytes a record at 64 bits, 40 at 256), or the value alone for a set without ids. The value is an unsigned little-endian integer. The manifest gives the width, whether ids are present, the record size, the counts, the first and last id, and each part's size and SHA-256, as sha256sum prints it. The snapshot module's documentation has the full format. snapshot::write refuses to overwrite one; snapshot::load reads one into memory, checking every checksum, that ids rise and that the first and last are the manifest's, and snapshot::load_counting does the same while counting the bytes read, so a service can report how far a load has got. A manifest may carry covers_seq, the position of a change log the snapshot reflects every change to (snapshot::write_covering writes it): the library reads and keeps it, and the search service replays the changes above it (Changes). snapshot::verify checks one as load does, reading each part once through a buffer of 4,096 records, without holding its records; the verify command and the service's checks use it or load, never a map.

A manifest is read once, and at most 16 MiB of it (snapshot::MANIFEST_MAX_BYTES). It lists at most 65,536 parts (snapshot::MAX_PARTS), each named by 1 to 128 bytes of A-Z, a-z, 0-9, ., _ and -, not starting with .; a manifest that lists one name twice, or two names of one file (a hard link, the same device and inode), is refused, so no part is counted or read twice. A snapshot directory that is a symbolic link is refused by every reader, the library's included. The manifest and each part are opened once, a symbolic link or anything but a file in their place is refused, and the size and, on Unix, the identity of the handle opened are checked against the name looked at. Memory for the records and the tables is reserved fallibly: a snapshot too large for the allocator is a typed error (Error::OutOfMemory), and to the service a refused snapshot, not an abort. No file makes a reader panic or set aside more memory than the files hold: a damaged or hostile snapshot gives a typed error, and a mutation test in the suite damages manifests and parts thousands of ways to check it.

Mapped::open maps one, checking every byte (Verify::Full) or only the sizes (Verify::SizesOnly, instant), and is an unsafe fn. A map reads the files as they are on disk for as long as it lives, and a check made at open, a full SHA-256 included, says nothing about what a later search reads: a part truncated in place while mapped ends the process with a bus error, and one rewritten in place breaks the rule that borrowed bytes don't change. The caller of Mapped::open promises that no process, through any name or descriptor, truncates or writes the part files while the map lives. Replacing a snapshot by writing a new directory and renaming it into place, or unlinking an old directory, keeps that promise, since the old files live on until the map is dropped; truncating, rewriting or recycling a part in place does not. Every safe path in the crate (load, verify, the service, query, stats and serve) copies the records into memory it owns, and needs no such promise.

A set in memory doesn't change: changes to an index are the search service's, which holds them in a log and a table over the snapshot until a newer snapshot covers them.

Errors

Every failure is an Error, each variant documented: records out of id order or of the wrong shape, a set past 2³² − 1 records, a chunk count that doesn't split the value into chunks of at most 16 bits, a code path the CPU lacks, bad hex, a forced probe with no tables, and for snapshots a manifest or part that doesn't add up, a checksum that doesn't match, or a file that can't be read. Nothing a query or a snapshot file holds makes the crate panic.

Which plan wins

From measurements, and nothing else. "Real" means about 90 million real 64-bit perceptual hashes of one image collection, held without ids; every other set is synthetic, from a generator that imitates their duplicates, clusters and near-duplicate families but not well enough to stand in for them. Queries a second are medians of 3 runs, one thread unless marked; the queries are 80% a stored value with 0 to radius + 2 bits flipped and 20% uniform. Every figure here was measured on 2 December 2026.

Intel Xeon Gold 5412U, 16 threads, 24 GiB, AVX-512:

Workload Records Best scan (avx512) Multi-index (16-bit chunks) Multi-index candidates a query
single, 64-bit, radius 5 90M real 25.5 (39 ms) 1,290 to 1,533 54,829
single, 64-bit, radius 8 90M real 25.5 481 283,898
single, 64-bit, radius 8, 16 threads 90M real 181 1,131 283,898
batch of 1,000, 64-bit, radius 8, 16 threads 90M real 894 4,003 290,548
batch of 100,000, 64-bit, radius 8, 16 threads 90M real 947 5,039 286,639
single, 64-bit, radius 8 90M synthetic 25.7 166 266,209
single, 64-bit, radius 8 180M synthetic 12.7 85.5 539,610
single, 256-bit, radius 31 90M synthetic 6.0 (166 ms) 47.4 384,399
single, 256-bit, radius 31, 16 threads 90M synthetic 46.2 350 384,399
batch of 1,000, 256-bit, radius 31, 16 threads 90M synthetic 254 501 385,698

The tables took 1,374 MiB over 686 MiB of real values and were built in 0.64 s; at 256 bits, 5,497 MiB over 2,747 MiB, in 1.29 s. The real values ran about three times faster through the index than synthetic ones of the same size (481 against 166 a second at radius 8), because real hashes cluster: in this set a typical value had 1.03 others at distance 0 and 12.8 at distance 8, where as many uniform values would have 0.02. Synthetic numbers are no stand-in in either direction.

The radius sweeps at 90 million records, on the same Xeon (16 threads, 24 GiB), 100 single queries at each radius, Planned with its tables and each way alone; queries a second, its plan below. The tables were built on 16 threads in about 0.8 s at 64 bits and 1.3 s at 256.

Real, 64 bits, radius 0 2 3 5 8 10 12 16
best scan 23.1 23.7 23.7 23.7 23.8 23.9 23.8 23.8
multi-index 110,788 11,200 7,948 1,354 410 102 61.4 12.7
Planned 138,616 12,034 9,555 1,504 466 110 66.8 25.2
its plan index index index index index index index scan
best scan, 16 threads 178 177 178 177 177 176 177 169
multi-index, 16 threads 3,405 3,560 3,563 1,459 1,006 190 172 36.0
Planned, 16 threads 184,339 33,390 16,315 1,612 1,124 198 180 169
Synthetic, 64 bits, radius 0 2 3 5 8 10 12 16
best scan 25.2 24.7 25.1 25.3 25.3 25.2 25.2 24.9
multi-index 22,579 8,679 6,403 796 168 72.6 28.1 6.80
Planned 22,862 9,102 7,386 812 169 72.9 28.1 24.8
its plan index index index index index index index scan
Synthetic, 256 bits, radius 8 16 31 48 64 80 96
best scan 6.75 6.81 6.84 6.89 6.82 6.90 6.75
multi-index 1,319 398 46.8 4.71 1.01 0.295 0.111
Planned 1,368 406 48.7 6.74 6.73 6.76 6.75
its plan index index index scan scan scan scan
best scan, 16 threads 47.7 47.4 47.0 47.6 47.5 47.6 46.0
multi-index, 16 threads 3,127 683 356 15.7 4.29 1.51 0.687
Planned, 16 threads 2,783 674 260 46.0 46.2 46.1 45.2

On the real values, Planned took the faster way at every radius: the tables to radius 12, the scan at 16. On the synthetic 256-bit set it took the tables through radius 31 and the scan from 48; at radius 80 a query through the tables alone took 3.4 s, and a lookup is the scan, 147 ms on one thread and 21.7 ms on 16. Batches of 1,000 on 16 threads ran 3,701 queries a second through Planned on the real values at radius 8, against 3,682 through the tables alone and 671 through the scan.

Two rows went the other way, on 16 threads at 256 bits, and the thread rule doesn't account for either. At radius 31 Planned ran 260 single queries a second against 356 through the tables alone, and 280 batch queries against 484, on the same 16 threads as they: it chose all 16. At radius 8 it chose 6 threads and ran 2,783 against 3,127. A probe at radius 8 reads 9 of the 16 tables; on 6 threads the longest share is 2 tables, as on 8, where the tables alone ran 3,888, and the fastest of Planned's three 6-thread runs reached 3,740. At these radii Planned's runs on 4, 8 and 16 threads spread far more than the tables' (161 a second at radius 31 on 4 threads, with a slowest run of 71), so the difference is from run to run as much as from the plan. On one thread, where the plan alone decides, Planned ran at least as fast as the tables alone at every radius of every set, single queries and batches.

Apple M2 Pro, 10 cores (radius 8 at 64 bits, 31 at 256, one thread; its memory wasn't recorded): the index won every workload measured, 2,302 queries a second against 466 for the best scan at 10 million synthetic 64-bit records, and 702 against 148 at 256 bits. A second run with neon-wide kept that: 2,618 against 671 at 64 bits.

The same Xeon, limited to 2 threads and 7 GiB (the radius sweep in Scan or index, and the code-path and scan measurements): the index won at 64 bits to radius 12 at both sizes, and at 256 bits to radius 31; past that the scan won, and at 256 bits, radius 96, by 57 times at 10 million records.

Not measured: any CPU with AVX-512 BW but no VPOPCNTDQ, and any CPU with AVX2 but no AVX-512.

Ways not taken, and why:

  • A 256-bit prefilter, a scan of the first 64-bit word and the other 192 bits only for the records within the radius on it: at radius 31 about 46% of records pass the first word alone (459,011 of a million), so it reads most of the rest anyway, and it ran 0.3 to 0.7 times the plain scan on the same path.
  • Multi-index tables of 32-bit chunks: they read far fewer candidates but probe so many keys that they lose to the scan at radius 8 (64 bits) and 31 (256 bits), and to 16-bit chunks even at radius 5: 1,312 queries a second at 10 million 64-bit records against 5,686.

Running it as a service

The legit-hamming program puts named indexes behind a search service. An application exports its hashes as snapshots, and the program loads them and answers searches. query answers them on the command line. serve (built with the serve feature) answers them as a worker on the Redis Streams work contract of legit-streams, which defines the task and result envelopes, the streams and the delivery rules. Both write the same result object, byte for byte, for the same options and snapshot, unless a search is cut by time or the two have different room for the result (see Limits), so an application can test its reader without a Redis. With --state-dir, serve also takes changes to an index, append, replace and remove, through an ordered log it replays over each new snapshot (Changes), and query reads that log and answers for the snapshot with its changes. The other commands are stats, which loads the sets and prints each one's state and measured neighbour table, verify, which checks one snapshot, and info, which prints the code paths, the formats and the versions.

cargo install legit-hamming --locked --features serve

A first run

A set is a directory holding snapshot directories and a one-line file CURRENT naming the one to serve. From Rust, with this crate:

use legit_hamming::{Records, snapshot};

let records = Records::from_records([(17, [0x9f3a_0000_0000_00ff_u64, 0, 0, 1]), (40, [7, 7, 7, 7])])?;
snapshot::write("/srv/hamming/images-pdq/2026-12-02T12-00-00Z".as_ref(), &records, 1_000_000)?;
std::fs::write("/srv/hamming/images-pdq/CURRENT.new", "2026-12-02T12-00-00Z\n")?;
std::fs::rename("/srv/hamming/images-pdq/CURRENT.new", "/srv/hamming/images-pdq/CURRENT")?;
# Ok::<(), Box<dyn std::error::Error>>(())

Check it, and search it from the command line:

legit-hamming verify /srv/hamming/images-pdq/2026-12-02T12-00-00Z
echo '{"format":1,"index":"images-pdq","width":256,"radius":31,"values":["9f3a0000000000ff00000000000000000000000000000000000000000000000f"]}' \
  | legit-hamming query --index images-pdq=/srv/hamming/images-pdq
{"format":1,"index":"images-pdq","snapshot":"2026-12-02T12-00-00Z","seq":0,"exact":true,"queries":[{"matches":[{"id":17,"value":"9f3a0000000000ff000000000000000000000000000000000000000000000001","distance":3},{"id":40,"value":"0000000000000007000000000000000700000000000000070000000000000007","distance":22}],"complete":true,"plan":"scan"}]}

Then the same as a worker. In one terminal, a throwaway Redis (6.2 or newer), and in a second, the worker:

docker run --rm -p 6379:6379 redis:8
legit-hamming serve --redis redis://127.0.0.1:6379 --index images-pdq=/srv/hamming/images-pdq

In a third, send a task and read its result:

redis-cli XADD hamming_tasks '*' task_id app_1 model_type photo model_id 42 task_name search \
  model_name '' source app v 1 \
  options '{"format":1,"index":"images-pdq","width":256,"radius":31,"values":["9f3a0000000000ff00000000000000000000000000000000000000000000000f"]}'
redis-cli XRANGE hamming_results - +

The result's result field holds the line query printed. model_type and model_id are required by the legit-streams envelope and echoed in the result; they mean nothing to this service, so any non-empty value will do.

Indexes, subsets and snapshots on disk

  • --index NAME=DIR serves an index; --subset INDEX.NAME=DIR serves a subset of one, a list of values the application searches on its own, such as values flagged for review. Both repeat. A name is 1 to 32 of a-z, 0-9, _ and -. One process serves the set of indexes it was started with.
  • A snapshot is the format of Snapshots: parts of little-endian records in id order and a MANIFEST.json of checksums. A subset's snapshot has its index's width, and may be exported with ids or without: a subset exported with ids returns them; one without returns values only; what a subset reveals is the exporter's choice. Either way it takes no changes. The manifest may carry covers_seq: with changes on, the changes logged above it are replayed over the snapshot when it is swapped in (see Changes); without, it is only reported by stats.
  • CURRENT is one line naming a snapshot directory directly inside DIR: 1 to 128 of A-Z, a-z, 0-9, ., _, : and -, not starting with ., so the name can be logged and returned as it is. A CURRENT that is a symbolic link, that names anything else, or that names a symbolic link, a missing directory or anything that isn't a directory is refused and logged once, and what is served stays. A manifest or part that is a symbolic link is refused too, and so is a manifest whose parts break the rules of Snapshots. CURRENT, the manifest and each part are opened once, and their type, size and identity are checked on the handle read.
  • Handing over a snapshot. The exporter writes the snapshot's parts, then its manifest, into a new directory, then writes CURRENT last, by writing a new file and renaming it over the old, so a reader never sees half a CURRENT. A snapshot is never changed once CURRENT has named it; the next export is a new directory. Old directories can be deleted once CURRENT names a newer one and the swap is logged. The same holds for every program that maps a snapshot with Mapped, for as long as it keeps the map: deleting or renaming a directory is safe, but a part must never be truncated, rewritten or reused in place, through its name or any other.
  • Loading. At start the worker reads each CURRENT. A new name is loaded beside the snapshot served, one set at a time: every part's size and SHA-256, and that ids rise, are checked as it is read. Then the multi-index tables are built, and the new snapshot is swapped in in one step. Searches already running finish on the one they started on, and each reply names the snapshot it searched. The old one is freed when the last of them ends. Then its neighbour table is measured (see stats). The next check starts --reload-seconds (30) after that one ended, and a check that loads a snapshot includes its load, its tables and its neighbour table. So a new CURRENT is served within about --reload-seconds, plus the time of whatever load and neighbour table was under way when it was written, plus its own load and tables.
  • Joining the group. At start, serve loads every set whose CURRENT names a snapshot before its workers join the consumer group, so a restarting worker never takes a task it could only answer not_ready while another worker of the group could answer it. A set with no CURRENT yet, or whose first load failed, doesn't hold the others back: it is empty, and its searches not_ready, until a snapshot of it loads.
  • A snapshot that fails to load (a checksum, the manifest, ids out of order, a file it can't read, not enough memory for its records, or a width other than the one served) is logged with its reason and never replaces one that is served. While CURRENT still names it, it is tried again after 300 s; a new name is tried at the next read.
  • Tables. --table-memory bounds the tables: auto (the default) builds them when they fit in the memory available once the records are loaded, less a quarter of it and at least 512 MiB, reading MemAvailable and the cgroup's limit; a number of bytes (with k, m or g) builds them within it; 0 scans every query. Without tables every query scans, and stats says "tables": false with the bytes they would have taken and the budget.

A PHP exporter, for a 256-bit index with ids, with no library:

<?php
function exportSnapshot(string $setDir, string $name, iterable $rows): void
{
    // $rows yields [id, hex] in rising id order, such as a query ordered by the primary key.
    $dir = "{$setDir}/{$name}";
    mkdir($dir, 0755, true);
    $parts = [];
    $total = 0;
    $first = $last = null;
    $part = null;
    foreach ($rows as [$id, $hex]) {
        if ($part === null || $part['records'] === 1000000) {
            if ($part !== null) { $parts[] = closePart($part); }
            $file = sprintf('part-%05d.bin', count($parts));
            $part = ['file' => $file, 'handle' => fopen("{$dir}/{$file}", 'xb'), 'hash' => hash_init('sha256'), 'records' => 0];
        }
        // 8 bytes of id, then the value as a little-endian integer: its hex's bytes reversed.
        $record = pack('P', $id) . strrev(hex2bin($hex));
        fwrite($part['handle'], $record);
        hash_update($part['hash'], $record);
        $part['records']++;
        $total++;
        $first ??= $id;
        $last = $id;
    }
    if ($part !== null) { $parts[] = closePart($part); }
    file_put_contents("{$dir}/MANIFEST.json", json_encode([
        'format' => 'legit-hamming-snapshot', 'version' => 1, 'width' => 256, 'ids' => true,
        'record_bytes' => 40, 'records' => $total, 'first_id' => $first, 'last_id' => $last,
        'parts' => $parts,
    ]));
    // CURRENT last, replaced in one step...
    file_put_contents("{$setDir}/CURRENT.new", "{$name}\n");
    rename("{$setDir}/CURRENT.new", "{$setDir}/CURRENT");
}

function closePart(array $part): array
{
    fflush($part['handle']);
    fsync($part['handle']);
    fclose($part['handle']);
    return ['file' => $part['file'], 'records' => $part['records'], 'bytes' => $part['records'] * 40,
            'sha256' => hash_final($part['hash'])];
}

The task kind hamming

What Name
Bulk task stream hamming_tasks
Worker group, both lanes hamming_workers
Result stream of a task that names no reply_to hamming_results
An application's result stream results:{app}:hamming
Fast task stream hamming_tasks:fast
A fast task's reply key results:{app}:hamming:rpc:{task_id}

--kind changes hamming to another name and --key-prefix puts a prefix before every key. A task is the legit-streams envelope, which the worker echoes, and one payload field, options, the JSON object below as text. model_name is empty or legit-hamming; any other is unsupported_model. task_name says what to do:

  • search, or default (legit-streams' builder default). An empty task_name is refused by the transport before it reaches the service (invalid_task). Its options:

    Key Meaning
    format 1.
    index The index to search.
    width 64 or 256; must be the index's.
    radius Every stored value within this Hamming distance is a match: 0 to the bound for the width.
    values One or more query values as hex, most significant digit first: 16 or 64 digits, either case.
    subset Optional: search this subset of the index instead.
    limit Optional: keep only the nearest limit matches of each query, by distance. At least 1.
    exclude_zero Optional: leave the all-zero value out.

    No other key is taken: a misspelt one is invalid_options, not ignored. An optional key given as null counts as absent. The result's result:

    {"format":1,"index":"images-pdq","snapshot":"2026-12-02T12-00-00Z","seq":0,"exact":true,
     "queries":[
       {"matches":[{"id":90211344,"value":"<hex>","distance":0},{"id":17,"value":"<hex>","distance":4}],
        "complete":true,"plan":"multi-index"},
       {"matches":[{"id":5,"value":"<hex>","distance":2}],"complete":false,"cut_by":"limit","plan":"scan"}
     ]}
    
    • One entry in queries per value, in order. matches are sorted by distance, then id, or for a set without ids (a subset exported without them) by position in the snapshot; each carries the stored value, and its id unless the set has none (a subset exported without ids). Every record of a value is returned: thousands of ids may share one, and nothing deduplicates by value.
    • complete: true means the list is every match within the radius. Otherwise cut_by says what cut it, and the list still holds the nearest: limit, the caller's; size, the service's bound on matches a query (see Limits); or time, the search budget, after which the search collects no more candidates. A search cut by time hadn't reached every record, and any it hadn't reached could be nearer than a match it found, so it keeps only the matches at distance 0 it found. A search whose budget ran out after its last candidate was collected but before its result was merged is cut by time too. Nothing is cut silently. The more values a task holds, the fewer matches each may keep before size cuts it: see Limits.
    • exact: true always: every list is exact for the snapshot named, whole or cut as it says.
    • snapshot names the snapshot directory searched, the subset's when a subset was given, and then subset names it too. seq is the last change applied over the snapshot: 0 until the service keeps a change log. plan says how the query ran, scan or multi-index.
  • stats, with options {"format":1,"index":"images-pdq"} and optionally subset. Its result is the set's state and what it serves:

    {"format":1,"index":"images-pdq","state":"ready","seq":1204331,
     "snapshot":{"name":"2026-12-02T12-00-00Z","width":256,"ids":true,"records":90000000,
                 "loaded_at":"2026-12-02T12:01:40.512Z","covers_seq":1198200,"tables":true,
                 "table_bytes":5764194304,"table_budget":20401094656,"load_ms":41200,"build_ms":9800,
                 "replayed":6131,"replay_ms":4},
     "loading":{"snapshot":"2026-12-02T13-00-00Z","fraction":0.412,"bytes_read":1483200000,"bytes":3600000000},
     "last_failure":{"snapshot":"2026-12-02T11-00-00Z","code":"covers_seq",
                     "reason":"its covers_seq is 1300000, past 1204331, the last change this service logged: it claims changes this service never saw",
                     "at":"2026-12-02T11:02:13.004Z"},
     "changes":{"log":{"tasks":61,"entries":6131,"bytes":431200,"first_seq":1198201,"last_seq":1204331,"base_seq":1198200},
                "held":{"values":5170,"removals":402,"bytes":210112},"writer":"ok","remembered":61},
     "neighbours":{"state":"measured","sample":2000,"seed":0,"max_distance":96,"counts":[2062,0,0,1,4],"ms":95000},
     "memory":{"records":3600000000,"tables":5764194304,"process_rss":9400000000,"process_peak_rss":9500000000,"available":21000000000},
     "limits":{"max_values_fast":1,"max_values":5000,"max_options_bytes":1048576,"max_radius_64":16,
               "max_radius_256":96,"max_matches":10000,"query_time_fast_ms":2000,"query_time_ms":30000,
               "max_result_bytes":33554432,"max_change_records":1000,"max_remove_ids":10000,
               "max_log_bytes":268435456},
     "threads":16}
    

    (counts is shortened here: it holds one count for each distance from 0 to max_distance.) snapshot, loading and last_failure appear when there is one; last_failure carries a reason for a snapshot refused by its covers_seq or by its index's change log (code log). An index whose change log is refused has state: "refused", the reason in refused and its code in refused_code: damaged, invalid, no_header, other_index, too_large, unreadable, symlink or sync_failed. changes appears for an index with a state directory: the log's whole tasks, entries and bytes, its first and last seq, and base_seq, up to which it has dropped every change; held, the changes held in memory over the snapshot, ids with a value and ids removed, and the bytes they take (live, a removal of an id the snapshot doesn't hold counts until the next replay, which drops it, so held can fall at a swap or a restart with no change made); remembered, the change tasks whose answers are kept for a repeat; and in serve, writer: ok, or broken once the process has stopped writing the log, with the code in writer_reason (see What happens when a write fails). snapshot.replayed is the changes replayed over the snapshot when it was swapped in, and replay_ms the time it took. neighbours is the measured floor of unrelated neighbours: from a sample of the snapshot's own records, drawn with the seed, the count of other records at each distance from 0 to max_distance, summed over the sample, so counts[d] / sample is how many unrelated records a typical one has at exactly distance d. It is a property of the snapshot alone: the changes over it don't count, and it is measured again only when a new snapshot is swapped in. Its state is measuring until the count is done. memory is the set's records and tables, and the process's resident memory, its peak and the memory available, in bytes. The limits are the service's settings, not memory or time set aside.

  • append, replace and remove, on the bulk stream only, with --state-dir: see Changes.

A task of any other task_name is invalid_task.

States and errors

State Meaning A search gets
empty The set has no CURRENT yet, or none it could load not_ready, state: "empty"
loading Its first snapshot is loading not_ready, state: "loading", fraction
ready A snapshot is served an answer
ready with loading A snapshot is served and a newer one is loading beside it an answer from the one served
refused Its change log can't be used as it stands: damaged before its last task, a whole record that breaks the format's rules, another index's, or longer than the bound read. stats gives the reason in refused and its code in refused_code not_ready, state: "refused"

An error result is the envelope's error_type and error, a result field holding the error object, and the fields some codes carry, which are also in the object:

{"format":1,"error_type":"radius_too_large","error":"radius 120 is above 96, the largest this service searches at 256 bits","max_radius":96}
error_type When Also carries
invalid_options options missing, over the byte bound, not JSON, not an object of the keys above with their types, another format, a value that isn't hex of the width
unknown_index No index of that name is served. The message quotes the name, shortened to 64 characters
unknown_subset The index has no subset of that name, quoted the same way
width_mismatch width isn't the set's
too_many_values More values than the lane takes, or than the room the task's echoed metadata leaves in its result entry
radius_too_large A radius above the bound for the width max_radius
not_ready The set is served but no snapshot is loaded yet: fall back for a minute state, fraction while loading when known
conflict An append met an id the index holds with another value; nothing was applied ids (at most 100, rising), count
log_full The change log would pass --max-log-bytes; the change was refused, not dropped
internal A fault in the worker that the request didn't cause. On a change it means unknown: the change may stand; send it again under the same task_id
invalid_task A task_name other than those above; a change on the quick path, or to a service without --state-dir; a change whose task_id isn't 1 to 64 of A-Z, a-z, 0-9, _ and -; a change or stats whose echoed fields leave too little room in its result entry for its result (nothing was applied). Also written by the transport for an envelope it can't read
unsupported_model A model_name other than empty or legit-hamming supported_models, a list: ["legit-hamming"]
max_deliveries_exceeded Written by the transport, not the service: the task was delivered more than 3 times, or set aside by whoever operates the Redis instance. On a change it means unknown, as internal does

The checks run in that order of cost, before any search: the size of options; that it is JSON, an object, each key given once (a key given twice is invalid_options, not the last one taken); its keys, then each key's type, limit and exclude_zero included; the number of values; the radius bound for the requested width; each value's hex; then whether the set is served, loaded and of the request's width. The values are counted as the JSON is read, and only as many as the lane takes are held: a task of a million values is answered too_many_values without a million values in memory. A change task is checked the same way, its records or ids in place of the values. query writes the same error object as its line: a set that didn't load is told on standard error, and each search of it is answered not_ready, as the stream answers it, while the other sets are searched as usual.

The service's own error results carry the error object in result. The transport, legit-streams, writes some error results itself, and those need not carry a result field: max_deliveries_exceeded, invalid_task for an envelope it can't read, unsupported_version for a v other than 1, internal when a handler panics, and result_too_large for a successful reply over its limits, which the service's sizing (see Limits) keeps from happening. A quick request whose reply_to doesn't match its task_id, or that is read after its deadline_ms, gets no reply at all: its caller times out and falls back. A reader treats an error code it doesn't know as a failure that a retry won't fix.

Limits

Each limit is a flag of query, stats and serve, and is in every stats result. Each is checked before a search starts, but the two time budgets, which are search budgets: the search stops collecting candidates after one has passed, and the reply follows as soon as what was collected is merged and written. Parsing the options, merging the lists, building the result and writing it to Redis come before or after the budget, not within it; it doesn't bound how long a task takes from the caller's side.

Flag Default Over it
--max-values-fast 1 value a quick request too_many_values
--max-values 5,000 values a bulk task too_many_values
--max-options-bytes 1 MiB of options invalid_options, before parsing
--max-radius-64 16 radius_too_large with max_radius
--max-radius-256 96 radius_too_large with max_radius
--max-matches 10,000 matches a query the nearest kept, cut_by: "size"
--fast-query-time 2 s of collecting a quick request's candidates cut_by: "time"
--query-time 30 s of collecting a bulk task's, all its values together cut_by: "time"
--max-result-bytes 32 MiB of result object fewer matches kept a query, cut_by: "size"
--max-change-records 1,000 records an append or replace too_many_values
--max-remove-ids 10,000 ids a remove too_many_values
--max-log-bytes 256 MiB of an index's change log log_full

The result bound keeps a reply within the stream's entry bound (64 MiB; serve refuses a --max-result-bytes above it, less 64 KiB for the envelope) after the work is done. Before the search, each query's share of it is worked out: --max-result-bytes (or, on a stream, the room below if that is less), less 512 bytes for the result's own fields and 96 bytes a query, divided among the queries by the widest a match can be (72 bytes at 64 bits with an id, 120 at 256; 46 and 94 without ids). A query keeps at most that many matches, or --max-matches if fewer. At the defaults, a bulk task of 5,000 values keeps at most 91 matches a query at 64 bits and 55 at 256, and a task keeps the full 10,000 a query up to 46 values at 64 bits and 27 at 256. A query is cut by size at its share even when the whole result is far under the bound: the share is fixed before the search, whatever the other queries turn out to need. Use limit, or smaller tasks, to choose. The limits are checked together at start, so a result can always hold one match for every value of the largest request.

On a stream the result shares its entry with what the task echoes back: metadata and embedder_key as legit-streams asks, and the identities. serve sizes each search to the entry's bound less 64 KiB for the envelope and less the bytes of those echoes, whichever is smaller than --max-result-bytes, before it searches. A task whose echoes leave too little room for even an empty entry for each of its values is answered too_many_values without a search. A result is never replaced by result_too_large after its search has run, and an error keeps its own code even when the task's echoes leave it no room: the transport drops the echoes, not the code. serve refuses to start on transport limits that can't carry every result it writes: fewer than 15 fields an entry, field names shorter than 16 bytes, or entries smaller than 64 KiB and the 4 KiB a change's result takes.

Threads. A quick request runs its query on one thread. --fast-jobs (2) is how many quick requests run at once, and callers beyond it wait their turn: in the check on real data under Sizing, 16 callers at once saw a median of 1.97 ms with --fast-jobs 8 and 6.82 ms at the default 2. Raise it toward the number of callers that query at once, up to the cores. The thread table in Scan or index shows a query that takes well under a millisecond loses when split. A bulk task is one batch search across --threads (the available cores), in turns of 256 values, with --jobs (1) at a time. Within a search, Planned still uses fewer threads for a short one.

Memory

The limits bound what one request holds at each stage, as below, with k the matches a query keeps: the smallest of its limit, --max-matches, and its share of the result bound. None of them is a bound on the process's memory. That is the snapshots served (two copies of a set during a swap: see Sizing), their tables, the changes held over them and the tasks the log remembers, plus one request's worth of the stages below for each task running at once (--jobs bulk tasks and --fast-jobs quick ones), plus what Redis's client and the allocator keep. Size a worker for that sum, not for any line of this table.

Stage Bound, for one request
The raw task The transport admits a stream entry of up to 256 fields and 64 MiB, read whole before anything else; options past --max-options-bytes (1 MiB) is refused before it is parsed. query reads a line at most that many bytes at a time.
The parsed JSON The text of options, at most 1 MiB, and of its keys only those the request takes, each a plain value; of its list (values, records or ids) only as many elements as the request may hold, each held as a JSON value of at most three plain values. The rest is counted or skipped as it is read.
The accepted list Up to --max-values (5,000) values of 8 or 32 bytes a bulk task, --max-values-fast (1) a quick request; up to 1,000 records of 16 or 40 bytes a change, or 10,000 ids of 8.
The search working set For each turn of up to 256 values, one hit list a value and a thread, each at most max_hits(k) = 2k + 5,119 hits of 8 bytes, its capacity included; then each value's k nearest as matches of 32 bytes (56 at 256 bits), and with changes held, the matches of the snapshot and each level merged one part at a time into one list, at most 2k a value between parts. The tables a multi-index probe reads were built at load, not per query.
The serialized result At most --max-result-bytes (32 MiB) of JSON, and on a stream at most the entry's room left by the envelope and the task's echoes, whichever is smaller: k is chosen before the search so that every value's matches fit. The result's objects before they are written take about two to three times their JSON.
The result envelope The stream entry: the result, the task's echoes (metadata, embedder_key and the identities) and 64 KiB kept for the envelope's own fields, within the entry bound of 64 MiB.

The quick path from PHP, with plain Redis commands

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$taskId = 'app_' . bin2hex(random_bytes(12));
$replyKey = "results:app:hamming:rpc:{$taskId}";
$entryId = $redis->xAdd('hamming_tasks:fast', '*', [
    'task_id' => $taskId, 'model_type' => 'photo', 'model_id' => '90211344', 'task_name' => 'search',
    'model_name' => '', 'source' => 'app', 'v' => '1',
    'reply_to' => $replyKey,
    'deadline_ms' => (string) ((int) (microtime(true) * 1000) + 2000), // the caller waits 2 s
    'options' => json_encode(['format' => 1, 'index' => 'images-pdq', 'width' => 256, 'radius' => 31,
        'values' => [$pdqHex], 'limit' => 50, 'exclude_zero' => true]),
]);
$reply = $redis->xRead([$replyKey => '0'], 1, 2000);
$redis->del($replyKey);
if (!$reply) {
    $redis->xDel('hamming_tasks:fast', [$entryId]); // no worker answered in time: fall back
} else {
    $fields = reset($reply[$replyKey]);
    if ($fields['status'] === 'success') {
        $query = json_decode($fields['result'], true)['queries'][0];
        foreach ($query['matches'] as $match) {
            // $match['id'] is within $match['distance'] bits of the query...
        }
        if (!$query['complete']) {
            // $query['cut_by'] says what cut the list: 'limit', 'size' or 'time'...
        }
    } else {
        // The service's own errors carry the error object in `result`; one the transport wrote
        // may have none, so the envelope's `error_type` and `error` are read first...
        $error = isset($fields['result']) ? json_decode($fields['result'], true) : null;
        if ($fields['error_type'] === 'not_ready') {
            // The index is loading or empty: fall back, and try again in a minute...
        }
    }
}

A bulk search is the same task with many values on hamming_tasks, reply_to set to results:{app}:hamming, read with a consumer group (XREADGROUP, then XACK once a result is handled), as legit-streams' result reader does. Results are at least once: a reader handles a repeated task_id once.

The examples here use PHP's integers, which are signed 64-bit: they hold ids and seqs below 2⁶³, as an application's row keys are. An id at or above 2⁶³ needs a decoder that keeps it whole, such as json_decode with JSON_BIGINT_AS_STRING.

Changes: append, replace and remove

serve --state-dir DIR takes changes to an index. Each index keeps an ordered log of every change in DIR/<index>/changes.log, beside a LOCK file; the state directory is the only place the program writes but for a stats file (see Security), and the set directories stay read-only to it. Without --state-dir every change task is invalid_task, with a message saying so, and the service is the snapshot-only one above. Subsets take no changes: a subset is replaced by its next export.

The rule. A snapshot doesn't hold "everything up to an id": values arrive for old ids long after the row, a value can change for an id that has one, a remove can race an export, and an export is many reads over minutes, not one consistent read. So:

  • Each applied change task is written to the log, each of its records an entry at the next position, seq. Its result gives the seq of its last entry. seq starts at 1 and never repeats or goes back, across restarts and shortening of the log.
  • A snapshot's manifest may carry covers_seq: the exporter's statement that every change with a seq at or below it is reflected in the snapshot.
  • When a snapshot is swapped in, the service replays every logged change above its covers_seq, in order, over it, and then drops from the log what the snapshot covers. A change the snapshot already reflects replays to nothing. A snapshot without covers_seq is replayed against from the start of the log, which is correct but slower, and the log is then not shortened.
  • A snapshot is refused, with code covers_seq and its reason in stats (last_failure), when it can't be made exact: when its covers_seq is above the log's last seq (it claims changes this service never saw), or below what the log has already dropped, or absent once the log has dropped any (the changes it misses could no longer be replayed). One without ids, or of another width than the log, is refused too (ids, width). The snapshot served stays.

The tasks, on the bulk stream only (the quick path answers them invalid_task). options take format, index and width, and then:

  • append: "records": [[id, "<hex>"], ...], at most --max-change-records (1,000), ids rising within the task. An id not held is added; an id held with the same value is unchanged; an id held with another value is a conflict. A task with any conflict applies nothing and is answered conflict, with the conflicting ids in ids (at most 100, rising) and their number in count: a useful alarm.
  • replace: the same shape. Each id's value is set, whatever it was, held or not.
  • remove: "ids": [...], at most --max-remove-ids (10,000), rising. Each id is removed; an id not held isn't an error. An id removed can be appended again later.

A task with no records or ids, ids that don't rise, or a subset is invalid_options; more than the bound is too_many_values. A change's task_id is 1 to 64 of A-Z, a-z, 0-9, _ and -, as legit-streams requires of every task, and is checked by the library too: any other is invalid_task, before anything is planned or written. A change whose echoed fields (metadata and the rest) leave less than 4 KiB of its result entry for its result is invalid_task before it is applied, so a change that stands is never reported as an error the transport made of a reply too large.

redis-cli XADD hamming_tasks '*' task_id app_2 model_type photo model_id 0 task_name append \
  model_name '' source app v 1 reply_to results:app:hamming \
  options '{"format":1,"index":"images-pdq","width":256,"records":[[41,"9f3a0000000000ff000000000000000000000000000000000000000000000001"],[90211345,"0000000000000007000000000000000700000000000000070000000000000007"]]}'
{"format":1,"index":"images-pdq","seq":2,"added":2,"changed":0,"removed":0,"unchanged":0}
{"format":1,"error_type":"conflict","error":"1 of the task's records give an id the index holds with another value; nothing was applied","ids":[41],"count":1}

added, changed, removed and unchanged count the task's records against what the index held when it was applied. Every record of an applied task is logged, one that changes nothing included, and so is the remove of an id not held: a later snapshot may have been read before the change was made, and replaying the log over it must make the change again.

When a change counts. The result is written only after the task's entries are on disk (fdatasync) and applied in memory: once a result can be read, its records are searchable and its removed ids are gone from every reply. A search's seq is the last change applied when it began, and its reply is exact for (snapshot, seq): every match within the radius over that snapshot with every change to that seq applied, whole or cut as it says, under limit, the size bound and the time bound. Changed records are masked inside the snapshot's search, where its hits are kept, so a limit still keeps the nearest limit of what the index holds. plan still says how the snapshot's part ran; the changes are always scanned.

Order and repeats. Change tasks are applied one at a time, in the order the worker takes them: with --state-dir, --jobs is 1, because a worker runs the tasks it takes together on threads of their own, in no order between them, and two changes to one id could land the other way round. A bulk search still runs across --threads. Results are at least once, so tasks are too: a worker can die after logging a change and before its result is written, and the task is delivered again, maybe after later changes to the same id. The log keeps each task's task_id and answer, so a task whose task_id it holds is answered as it was the first time, byte for byte, conflicts included, and changes nothing. task_ids are remembered per index, and a repeat is recognised by its task_id alone, not its content. A task refused before it was applied (invalid_options, log_full, not_ready, invalid_task) isn't remembered.

What the code does to forget a task, exactly: a remembered task is dropped only when a snapshot that covers its changes is swapped in and the log is shortened, and only if the task was applied more than --repeat-window (1 hour) before that, by the wall clock. Nothing expires on a timer: a task is remembered until such a shortening, however long that is. A conflict, which has no changes, is dropped at the first shortening after the window. The wall clock is read when the task is applied and when the log is shortened, so a clock stepped forward can drop receipts early, and one stepped back keeps them longer.

For callers, the rule that follows: a task_id is unique per index for all time, and a caller never relies on a repeat's expiry for ordering. Send an id's current value, not its history, and send each change under a new task_id only once its previous task has been applied or refused for what it holds. After internal or max_deliveries_exceeded, when no answer comes, and after a refusal that may pass later (not_ready, log_full, unknown_index), which isn't remembered, send the same task again under the same task_id. A caller that sends a change again under a new task_id after newer changes to the id can undo them, and the service can't tell; one that reuses a task_id for other work gets the first task's answer.

One writer. With changes on, one process serves an index: a consumer group hands each change to one worker, so a second worker would hold changes the first never saw. serve takes an exclusive lock on each index's state directory, and a second process naming the same index and state directory refuses to start. The lock is waited for up to a second before another holder counts: a child process holds a copy of every open file from its fork to its exec, so a program that embeds the library, spawns processes and opens a writer again at once could otherwise find the lock it just released still held. Several workers may share the same set directories only when none of them takes changes (see Running it under a supervisor). query and stats read a state directory without the lock: the snapshot CURRENT names and the log as they are on disk at that moment, once per run, not the live writer's acknowledged state. A task the writer has written but not yet synced, or will roll back, can be in what they read. For an authoritative answer, ask the running serve.

An exporter notes the highest seq its feeder has had confirmed, then starts reading, and writes that number as the manifest's covers_seq. Every change at or below it was made in the application's database before it was sent, so the export reads it or a newer value; a change it reads that came later is replayed over it and replays to nothing. In the PHP exporter above, that is one more key in the manifest:

$coversSeq = (int) $db->query("SELECT value FROM settings WHERE name = 'hamming_confirmed_seq'")->fetchColumn();
// ...then read the rows and write the parts, and in the manifest:
//     'covers_seq' => $coversSeq,

A feeder. The application's write path doesn't touch this Redis. The SQL here and in the exporter's snippet above is PostgreSQL's; another database needs its own upsert and interval syntax. The application marks a changed record in its own database, in the same transaction as the hash; a feeder sends the marked records in batches and clears a mark when its result confirms it. The protocol below keeps three promises: a record has at most one task in flight, so its changes are sent in the order they were made; a task is recorded with its marks before it is sent, so a crash or a Redis outage between the two only delays it; and a task is sent again under its own task_id, never under a new one, until it is applied or refused in a way every copy of it would be: after no answer, after internal or max_deliveries_exceeded, whose outcome isn't known, and after a refusal that may pass later, such as not_ready, which applies nothing but isn't remembered, so a copy still in the stream would be applied when it came:

<?php
// hamming_marks(record_id PRIMARY KEY, version, sent_version NULL, task_id NULL)
// hamming_outbox(task_id PRIMARY KEY, task_name, options, enqueued, sent_at NULL)
//
// The application's write, in the transaction that writes `images.pdq_hex` or deletes the row; it
// never touches `task_id`, so a mark in flight stays claimed by its task:
//   INSERT INTO hamming_marks (record_id, version) VALUES (?, 1)
//     ON CONFLICT (record_id) DO UPDATE SET version = hamming_marks.version + 1;

function feed(PDO $db, Redis $redis): void
{
    // First, every task whose outcome isn't known: recorded but not known to be sent (a crash
    // before XADD, or XADD failed), answered `internal` or `max_deliveries_exceeded` (see
    // `confirmed`), or sent 10 minutes ago and not answered, as when Redis lost the entry or its
    // result. Each goes again under its own `task_id`: if the service applied it, it answers the
    // copy as a repeat, with the same bytes; if not, it applies it now. 10 minutes is well within
    // the service's `--repeat-window`, so a repeat is always recognised. Nothing new is claimed
    // while one can't be sent.
    $unknown = $db->query("SELECT task_id, task_name, options FROM hamming_outbox
        WHERE NOT enqueued OR sent_at < now() - interval '10 minutes'");
    foreach ($unknown as $task) {
        enqueue($db, $redis, $task['task_id'], $task['task_name'], $task['options']);
    }
    // Claim: the marks with no task in flight, locked, so a write waits until the claim commits and
    // then raises `version` past `sent_version`. The values are read under the same locks...
    $db->beginTransaction();
    $marks = $db->query('SELECT record_id FROM hamming_marks WHERE task_id IS NULL ORDER BY record_id LIMIT 1000 FOR UPDATE')
        ->fetchAll(PDO::FETCH_COLUMN);
    if (!$marks) { $db->commit(); return; }
    $in = implode(',', array_map('intval', $marks));
    // The current value of each, not its history; a row gone, or without a hash, is a removal...
    $values = $db->query("SELECT id, pdq_hex FROM images WHERE id IN ($in) AND pdq_hex IS NOT NULL")
        ->fetchAll(PDO::FETCH_KEY_PAIR);
    $records = $gone = [];
    foreach ($marks as $id) {
        isset($values[$id]) ? $records[] = [(int) $id, $values[$id]] : $gone[] = (int) $id;
    }
    $tasks = [];
    foreach (['replace' => ['records' => $records], 'remove' => ['ids' => $gone]] as $name => $list) {
        if (!reset($list)) { continue; }
        $taskId = 'app_' . bin2hex(random_bytes(12));
        $ids = $name === 'replace' ? array_column($records, 0) : $gone;
        $options = json_encode(['format' => 1, 'index' => 'images-pdq', 'width' => 256] + $list);
        $db->prepare('UPDATE hamming_marks SET task_id = ?, sent_version = version WHERE record_id IN (' . implode(',', $ids) . ')')
            ->execute([$taskId]);
        $db->prepare('INSERT INTO hamming_outbox (task_id, task_name, options, enqueued) VALUES (?, ?, ?, FALSE)')
            ->execute([$taskId, $name, $options]);
        $tasks[] = [$taskId, $name, $options];
    }
    $db->commit();
    foreach ($tasks as [$taskId, $name, $options]) {
        enqueue($db, $redis, $taskId, $name, $options);
    }
}

function enqueue(PDO $db, Redis $redis, string $taskId, string $name, string $options): void
{
    // An outage throws, and a refused XADD returns false: either way the task stays in the
    // outbox, not enqueued, for the next run...
    $entryId = $redis->xAdd('hamming_tasks', '*', [
        'task_id' => $taskId, 'model_type' => 'image', 'model_id' => '0', 'task_name' => $name,
        'model_name' => '', 'source' => 'app', 'v' => '1', 'reply_to' => 'results:app:hamming',
        'options' => $options,
    ]);
    if (!is_string($entryId)) {
        throw new RuntimeException("XADD of {$taskId} wasn't accepted");
    }
    $db->prepare('UPDATE hamming_outbox SET enqueued = TRUE, sent_at = now() WHERE task_id = ?')->execute([$taskId]);
}

// The codes of a change refused for what it holds, which every copy of the task gets while the
// service keeps its settings: nothing was applied, and nothing will be. `conflict` is remembered
// too, so a copy gets the same answer.
const REFUSED = ['conflict', 'invalid_options', 'invalid_task', 'too_many_values', 'width_mismatch',
    'unsupported_model', 'unsupported_version'];

// The result reader, on `results:app:hamming` with a consumer group (XREADGROUP, then XACK once
// this has committed), for each result entry read...
function confirmed(PDO $db, array $fields): void
{
    $taskId = $fields['task_id'];
    $error = $fields['error_type'] ?? '';
    $db->beginTransaction();
    if ($fields['status'] !== 'success' && !in_array($error, REFUSED, true)) {
        // `internal`, `max_deliveries_exceeded`, a refusal that may pass later (`not_ready`,
        // `log_full`, `unknown_index`) or a code this reader doesn't know: the change may stand, or
        // a copy of the task may still be applied. Its marks stay claimed and the task goes again
        // under the same `task_id` at the next run. A task answered this way run after run is an
        // alarm...
        $db->prepare('UPDATE hamming_outbox SET enqueued = FALSE WHERE task_id = ?')->execute([$taskId]);
        $db->commit();
        return;
    }
    if ($fields['status'] === 'success') {
        // A mark still at the version sent is done; one written again since is freed, and its new
        // value goes in a later task...
        $db->prepare('DELETE FROM hamming_marks WHERE task_id = ? AND version = sent_version')->execute([$taskId]);
        $result = json_decode($fields['result'], true);
        $db->prepare("UPDATE settings SET value = GREATEST(value, ?) WHERE name = 'hamming_confirmed_seq'")
            ->execute([$result['seq']]);
    }
    // Applied, or refused for what it holds (`conflict` is an alarm): the marks are freed, and a
    // later run sends their records under a new task, with their values then...
    $db->prepare('UPDATE hamming_marks SET task_id = NULL, sent_version = NULL WHERE task_id = ?')->execute([$taskId]);
    $db->prepare('DELETE FROM hamming_outbox WHERE task_id = ?')->execute([$taskId]);
    $db->commit();
}

The interleavings it is built for:

  • A record written again while its task is in flight. The write waits for the claim's lock if the claim is running, then raises version past sent_version; it doesn't free the mark. When the task is confirmed, that mark doesn't match version = sent_version, so it isn't deleted: it is freed, and the next run sends the record's value as it is then, or its removal. A record never has two tasks in flight, so an older value can't land after a newer one.
  • A crash, or a failed XADD, after the claim commits. The task is in the outbox with its marks claimed, and enqueued false. The next run sends it again, same task_id and options, before it claims anything; if the first send did reach the stream, the service answers the second as a repeat. A crash after XADD and before enqueued is set does the same.
  • No answer. A task sent and not answered within 10 minutes, because Redis lost the task or its result, or a worker is down, is sent again under the same task_id. If both copies are answered, the second is a repeat with the same bytes, and the reader handles one of them.
  • An answer that doesn't say. internal and max_deliveries_exceeded leave the outcome unknown: the marks stay claimed by the task, which goes again under the same task_id.
  • A refusal that may pass later. not_ready, log_full and unknown_index apply nothing, and the service doesn't remember them, so a copy of the task still in the stream (one sent again after no answer, or after internal) is applied when it comes. Were the marks freed and the record's newer value sent in a new task, that copy could land the older value after it. So the marks stay claimed and the task goes again under the same task_id; once it is applied, every copy is a repeat. Only a success, or a refusal every copy gets, frees the marks, and only then can their records go in a new task.
  • A result read twice, as results are at least once: the second finds no mark and no outbox row for its task, and changes nothing. An internal read again after its task's success likewise finds no row.

Recovery. A task's entries and its closing record are written in one call and made durable (fdatasync) together before its result is written. When serve opens a log it reads it to the end of its last whole task, cuts what follows (an unfinished task, whole records or torn; the log line says how many bytes and entries), and then always syncs the file and its directory before a task in it can be answered as a repeat: a task a process wrote before it died, and that a restart reads whole, is made durable before anything is answered from it. A failure there refuses the index. A cut task may still have been answered by nobody, and its redelivery applies it. Damage before the last task (a record that is torn or fails its checksum with whole records of a later task after it), or a whole record that breaks the format's rules (a seq that doesn't follow, counts that don't add up, a task_id twice), refuses the index rather than guessing: it serves nothing, stats says refused, why, and its code, searches get not_ready with state: "refused", and the other indexes are served. Damage inside the last task can't be told from a task that never finished, and is cut: the log trusts that what fdatasync made durable reads back. The format is in the service::log module's documentation.

What happens when a write fails. A write or fdatasync that fails is answered internal, which on a change means unknown: the file is cut back to its last whole task if it can be, but whether the task's bytes reached the disk isn't known, and a restart that finds the task whole applies it (in its place in the log, below anything sent later). That index then takes no change until the program restarts and reads its log again; searches go on, and stats says changes.writer: "broken" with writer_reason: write_failed, sync_failed (the cut back worked), rollback_failed (it didn't), create_failed, shorten_failed, panicked (a change unwound between the log and memory), or for a swap that found the log not as this process left it, log_missing, log_replaced, log_changed, log_cut, log_appeared, log_too_large or log_unreadable. At a swap the writer reads its log through the file it appends to and checks it against what it made durable: the same header, the same end and last seq, no cut, and the log's name still naming that file. A log deleted, cut, rewritten or replaced under a running serve refuses the swap (last_failure code log), the snapshot served stays, and the writer stops: nothing confirmed is lost by the swap, and no change is written to a file the directory no longer names. A swap while the writer is broken is refused the same way.

The state directory. serve makes STATE/<index> and any missing directory above it one level at a time, then syncs every directory on that path that holds the next one's name, so the log is durable from the first change. It does so on every start, not only when it made a directory: one found may be what a start that stopped before its sync left visible but not durable. A symbolic link where STATE/<index>, LOCK, changes.log or changes.log.new is expected is refused, by query and stats as by serve; they look at changes.log's name before opening it, so a link to a missing file is refused rather than read as no log, and a pipe is refused rather than waited on. The temporary log of a shortening is created afresh (O_EXCL) after a stale one is removed.

The bound. --max-log-bytes (256 MiB, about 3.5 million changes at 256 bits and 5 million at 64) bounds each index's log: past it a change is refused with log_full, never dropped. Whether a task fits, its exact bytes and its seqs, is decided before any work is done for it: a refused task builds no level and encodes nothing. A seq past 2⁶⁴ − 1 is refused the same way, with a message that the sequence is exhausted. A snapshot that covers the log's changes lets the next swap shorten it. A log is read only up to the bound and one largest change task: a longer one, left by a run with a larger bound, refuses its index (too_large) without being read into memory; to recover, start with --max-log-bytes raised to hold it, and export a snapshot that covers it so it is shortened.

Memory. The changes over a snapshot are held as a table keyed by id, in a few immutable levels a search reads without a lock: a value costs 16 bytes at 64 bits and 40 at 256 (its id and value), a removal 8, and an id changed again is held once in each level that has it until the levels are merged, so ids changed often cost more. A day of 200,000 changes holds 3.2 MB at 64 bits and 8 MB at 256, and its log takes about 9 MB and 14 MB on disk (46 and 70 bytes an entry, and about 100 bytes a task); each task's task_id and answer, about 150 bytes, are kept in memory while it is remembered. Changes are scanned with every search: a million held added 0.3 ms to a quick search at 64 bits (see Sizing).

What is guaranteed, on this storage model: a local filesystem with a working fdatasync, atomic rename within one directory, and advisory file locks; no rollback of the device; not a network filesystem; a state directory that is not moved, replaced or shared while serve runs; and a process that does not fork. Then:

  • a change whose result was written is durable, and stays applied across a clean stop, a kill at any moment, a machine failure, and any number of swaps;

  • an id removed is absent from every search that began after the removal's result was written;

  • a reply is exact for the snapshot and seq it names;

  • internal or max_deliveries_exceeded on a change, or no answer, means unknown: send it again under the same task_id, and it is answered from the log if it stood or applied if it didn't;

  • damage inside the last task can't be told from an unfinished write and is cut; damage before it refuses the index.

What isn't: a change answered with any other error isn't applied by that delivery, and is the caller's to send again, under the same task_id while another copy of it may still be delivered; a repeat after it was forgotten (see above), or a change sent again under a new task_id, is applied again; covers_seq is the exporter's word, and a snapshot that claims to cover a change it doesn't reflect loses that change, as the replay skips it; and query and stats on the command line read what is on disk, not what the writer has acknowledged.

Sizing

Measured on 2 December 2026 by a harness that runs the worker as a separate process against a real Redis, on synthetic records with ids (a fifth of the values in families of near copies, the rest uniform), in a container limited to 2 cores of an Intel Xeon Gold 5412U and 8 GiB, with Redis 8.0.5 on the same machine and one worker, --threads 2. The quick path is 1,000 calls of one value one after another, timed by the caller with the Redis round trip, at radius 8 (64 bits) or 31 (256 bits), 80% of them a stored value with a few bits flipped; bulk is 50 tasks of 200 such values. Real hashes cluster differently: see Which plan wins.

Records Width Load, every checksum Tables Neighbour table, 2,000 Resident at rest Peak of a swap Quick path, median / 99th Bulk, queries a second
1 million 64 21 ms 38 ms 0.15 s 36 MiB 68 MiB 0.27 / 0.54 ms 35,405
1 million 256 58 ms 126 ms 0.46 s 109 MiB 211 MiB 0.47 / 0.70 ms 8,707
10 million 64 193 ms 322 ms 1.3 s 314 MiB 619 MiB 0.96 / 1.19 ms 2,814
10 million 256 480 ms 1,041 ms 4.2 s 1,004 MiB 1,998 MiB 2.40 / 2.87 ms 979

Peak memory during a swap is two copies of the set, records and tables: the new snapshot is loaded and its tables built beside the old one, which goes on serving until the swap, and the old one is freed when its last search ends. A set takes, at rest, its records (16 bytes a record at 64 bits with ids, 40 at 256) and its tables (16 and 64 bytes a record, when built), so 90 million 256-bit records with ids take about 8.7 GiB at rest and 17.5 GiB at the peak of a swap. The sets of one process load one at a time, so its peak is every set at rest plus one more copy of the largest. Loading reads and checks about 800 MB a second on that machine, and both the load and the table build grow with the records. The neighbour table runs after the swap, on --threads, beside the searches; at 256 bits it counts out to distance 96, a scan for every sampled record.

A run of the same harness over a million 64-bit records, with two workers of one thread each: 2,000 bulk tasks of 10 values at 11,191 queries a second; a worker killed with SIGKILL mid-run, its task claimed by another after the 300 s threshold, and every one of the 2,000 results byte for byte what the library gives, none missing or repeated; quick calls at a median of 0.37 ms and a 99th percentile of 0.56 ms; a new snapshot served 0.5 s after CURRENT changed, under 1,222 quick calls with none failed and each exact for the snapshot it named; and both workers exiting 0 on SIGTERM.

The change log, measured the same way on synthetic records, in a container limited to 2 cores of the same Xeon: 10 million 64-bit records with ids, one worker, --threads 2, the state directory on ext4 on an SSD, changes that replace distinct ids of the snapshot:

What Measured
Change tasks of 1,000 records, each written and fdatasynced before its result 555 tasks, 555,284 records a second
Change tasks of 100 records 1,024 tasks, 102,402 records a second
Quick path, radius 8, median / 99th percentile, no changes held 0.88 / 1.12 ms
The same, 10,000 changes held 0.86 / 1.04 ms
The same, 1,010,000 changes held 1.25 / 1.49 ms
1,010,000 changes held 16 MiB in memory; the log 44 MiB on disk
A swap to a snapshot covering none of them: the replay of 1,010,000 changes 72 ms
A restart, to serving at seq 1,010,000 2.5 s: the snapshot's load 214 ms, its tables 168 ms, the replay 79 ms, then its neighbour table

A run of changes against a real Redis, over a million 64-bit records: 1,500 change tasks of up to 200 records sent while quick searches ran, a snapshot covering the 501 confirmed by then swapped in mid-feed, the worker killed with SIGKILL after 1,000 results and a new one started on the same state directory, its task claimed after 300 s. Every task was answered once (1,065 applied, 435 conflicts), the applied tasks' entries tiled the log from 1 to 212,874 with no gap or overlap, and all 10,392 quick replies, 5,568 from the first snapshot and 4,824 from the second, were exact for the seq they named, as were 2,000 searches of the state directory read as query reads it.

Checked against real data on 2 December 2026, on the Xeon above while it carried other load: 8,000 quick lookups through the worker, 4,000 over about 90 million real 64-bit perceptual hashes at radius 5 and 8 and 4,000 over about 4 million real 256-bit ones at radius 31 and 72, each reply compared with an independent brute-force search that shares no code with this crate. Each of the 7,997 complete replies matched the brute-force answer match for match. The three queries with more than 10,000 matches came back cut by the size bound, as Limits says, holding the nearest by the count at each distance. Round trips from a client on the same machine, the client included: a median of 0.87 ms and a 99th percentile of 1.50 ms at radius 5 and 2.46 and 5.91 ms at radius 8 on the 64-bit set; 1.05 and 1.43 ms at radius 31 and 6.54 and 7.15 ms at radius 72 on the 256-bit set.

In the same check, one worker served the 64-bit set on all 16 threads (--threads 16 --fast-jobs 8), under the same load. It started and joined its group in 3.8 s, the load taking about 2.9 s and the tables 0.83 s, and held 2.69 GiB resident at rest. Three swaps to a new snapshot of that set ran while four callers sent quick lookups back to back, about 3,600 a second together: no failed, not_ready or missing reply in 214,843 calls, and no reply named the old snapshot after the first that named the new. With the 256-bit set of about 4 million records loaded as well, the process's resident memory went from 3.08 GiB to a peak of 5.76 GiB during a swap and back. One bulk task of 5,000 values at radius 8 took 1.38 s. With 16 callers at once the quick path's median was 1.97 ms and its 99th percentile 2.83 ms at radius 5, and 5.28 and 8.01 ms at radius 8; at the default --fast-jobs 2 the same callers saw 6.82 and 8.21 ms, and 18.99 and 24.00 ms. A worker was killed with SIGKILL while 300 append tasks were being sent: after the restart every acknowledged record was there, 29 tasks sent again were answered byte for byte as before, and the 282 tasks not yet acknowledged were each applied exactly once, with no gap in seq.

Running it under a supervisor

A systemd unit:

[Unit]
Description=legit-hamming search worker
After=network-online.target redis.service

[Service]
User=hamming
ExecStart=/usr/local/bin/legit-hamming serve --index images-pdq=/srv/hamming/images-pdq --subset images-pdq.flagged=/srv/hamming/flagged --state-dir /var/lib/legit-hamming --threads 8
Environment=LEGIT_HAMMING_REDIS_URL=redis://:password@127.0.0.1:6379
# The shutdown grace, plus a read in progress, plus a margin...
TimeoutStopSec=45
Restart=always
RestartSec=5
# Two copies of the largest set during a swap, plus its tables: see Sizing...
MemoryMax=24G
ReadOnlyPaths=/srv/hamming
# The change logs: the only place it writes, with a --stats-file the other...
StateDirectory=legit-hamming
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

SIGTERM or SIGINT stops it cleanly: it takes no new task, gives the task it runs the shutdown grace, releases the rest to other workers, and exits 0; a second signal ends it at once. A load in progress isn't waited for. After a restart the sets load again from their CURRENT before the worker takes a task, and a signal during that first load stops it at once; with --state-dir, the changes logged are replayed over the snapshot as it loads, and an unfinished task at the end of a log is cut first.

How many workers. With changes on (--state-dir), one process serves an index, and its lock refuses a second: the group hands each change to one worker, so changes can't be shared between workers, and a replica of an index would need every change delivered to it as well, which a consumer group doesn't do. Without changes, several workers may serve the same set directories, one process each, on one machine or several: the group shares the searches, and each loads the same snapshots.

Logs

Log lines are JSON on standard error: the settings at start, each set's CURRENT refused, each load begun, served (with its record count, load and table times, the snapshot it replaced, the changes replayed over it and the seq it serves) or failed (with its code and reason), each neighbour table measured; for each change log, what was read at start and how many bytes and entries of an unfinished task were cut, a log refused and why, each shortening after a swap, and a write that failed; and a heartbeat every --heartbeat seconds (30): tasks by name (append, replace and remove among them), error results by error_type, queries, candidates read, queries cut by limit, time and size, and each lane's count, median and 99th percentile since the last heartbeat. In the heartbeat line, errors is a JSON object written as a string inside the JSON line, such as "errors":"{\"not_ready\":3}", and the lane figures, fast_count, fast_p50_ms, fast_p99_ms, bulk_count, bulk_p50_ms and bulk_p99_ms, are in milliseconds, where the stats file's are in microseconds. A collector should parse the stats file, not the log. A task answered with an error is logged with its entry id, lane, task name and code. The service never logs a query value, id or match, a change's id or value, or a name a request gave. legit-streams, which reads the envelope, logs an entry it can't read as a task, and may quote the field at fault, shortened, or the task's id. A snapshot that fails to load is logged by its file and what is wrong with it, never by the record ids at fault: ids out of order, or a manifest whose first and last ids aren't the parts', are told without them. The configured directories are logged at start, and a failed load names the file.

Stats file

--stats-file PATH writes what the worker has done and what it serves to PATH as one JSON document, for a collector on the same machine to read: once when the workers start, at every heartbeat (--heartbeat, 30 s), and once more when they have stopped. Each write is whole: the document goes to PATH with .tmp added, in the same directory, with mode 0644, and is then renamed over PATH, so a reader never sees half of one. A write that fails is logged once for each kind of error, until one succeeds, and never stops the worker; the next document written covers the interval since the last one in the file. A PATH whose directory doesn't exist stops serve before it starts, with exit status 2.

{"format":1,"program":"legit-hamming","version":"0.1.1","state":"running","started_at":1796212800,
 "at":1796216400,"uptime_s":3600,"interval_s":30.001,"in_flight":1,
 "bulk":{"answered":1210,"failed":3,"rate_per_s":0.4,"median_us":48100,"p95_us":131000,"p99_us":262000},
 "fast":{"answered":902116,"failed":12,"rate_per_s":251.37,"median_us":281,"p95_us":529,"p99_us":861},
 "tasks":{"search":{"answered":903005,"failed":15,"values":1192114,"matches":2210450,"incomplete":1031},
          "stats":{"answered":120,"failed":0},"append":{"answered":61,"failed":0},
          "replace":{"answered":130,"failed":0},"remove":{"answered":10,"failed":0}},
 "totals":{"sets":2,"records":90001200,"changes_held":5572,"ready":2,"not_ready":0},
 "backlog":{"waiting":0,"pending":1}}

It is written as one line; it is broken here to be read.

Field Meaning
format 1. A change that isn't only a new field raises it.
program, version legit-hamming and its version.
state running, or stopped in the last document, written once the workers have stopped.
started_at, at When the worker started, and when the document was written, in Unix seconds.
uptime_s Seconds since the worker started.
interval_s Seconds since the previous document written; null in the first.
in_flight Tasks being handled now, on both lanes.
bulk, fast Each lane, below; fast is null with --no-fast.
tasks Each task_name, below, both lanes together.
totals What the worker serves, over every index and subset, below.
backlog The bulk group's backlog, below; null when it couldn't be read.

For each lane:

Field Meaning
answered Tasks the service answered since the start, errors included: counted when its reply is handed to the transport, before the result is written (see below).
failed Of those, the tasks answered with an error.
rate_per_s Tasks answered a second over the interval; null in the first document.
median_us, p95_us, p99_us The median, 95th and 99th percentiles of the worker's processing time for the tasks answered in the interval, in microseconds: from when the task's handler starts to when its reply is ready, not the wait in the stream or the time to write the result. null in the first document and when no task was answered.

What is counted is the service's work, not the results delivered. A reply is counted when the service hands it to the transport, before the result is written: a result whose write fails leaves the task pending, and the task is counted again when it is delivered again and answered. What the transport answers itself, without handing the task to the service, isn't counted: an envelope it can't read, a v other than 1, an empty task_name, max_deliveries_exceeded, and a quick request deleted unanswered past its deadline. While every result is written, answered is the number of results the service itself produced, and the worker's result stream can hold more than that by the transport's own refusals.

The times come from a histogram: a task's time is taken in whole microseconds, each microsecond below 8 µs has a bucket of its own, and above that each power of two is split into eight. A figure is the middle of its bucket, so it is within a sixteenth (6.25%) of the time of every task in that bucket.

For each task name, search (with default), stats, append, replace and remove: answered and failed, as for a lane. A task of any other name counts in its lane alone. search also has values, the query values looked up; matches, the matches returned; and incomplete, the values whose matches were cut, by the caller's limit, the size bound or the time bound. A search answered with an error looked nothing up.

totals is read when the document is written: sets, the indexes and subsets served, loaded or not; ready, those with a snapshot served, which searches are answered from, and not_ready, the rest (empty, loading a first snapshot, or refused); records, the records of the snapshots served; and changes_held, the changes held over them, ids with a changed value and ids removed. As with changes.held in stats, a removal of an id the snapshot doesn't hold counts until the next replay drops it, so changes_held can fall at a swap or a restart with no change made.

backlog is read with a connection of its own, never one a worker uses, and waited for at most 2 s: waiting, the entries of the bulk stream not yet delivered to the group (null when Redis doesn't say: before 7.0, or once entries the group hasn't read were trimmed), and pending, those delivered to a worker of the group and not yet acknowledged. A read still running at the next write is waited for, not started again.

The document holds numbers, those fixed words and nothing else. Never in it: the name of an index, a subset or a snapshot; a path; the name of a stream, a group or a consumer; the key prefix; a host, an application or a source; a task_id; a query value, a record's value or id; or an error's text. A test feeds distinctive values for each of those through both lanes, the changes included, and finds none of them in any document written. Whether the file leaves the machine, and where it goes, is the operator's decision: the worker only writes it. Under systemd, RuntimeDirectory=legit-hamming with --stats-file /run/legit-hamming/stats.json gives it a directory of its own.

Security

  • The set directories and the state directory are trusted configuration: only the exporter writes a set's directory, and only the service writes the state directory. The worker reads the directories it was started with and the snapshot each CURRENT names directly inside them, and refuses a symbolic link as CURRENT, as the snapshot directory, as a manifest or as a part, a part named outside the plain set or listed twice, and a file that isn't one. These checks catch mistakes and stray links; they are not a defence against a local party who can write those directories while the service runs, who can change what is read between a check and a read. Keep the directories writable only by the exporter and the service's own user.
  • Apart from Redis, the worker opens no network connection, fetches nothing a task names and starts no program. Besides its directories it reads /proc and the cgroup files for memory. It writes files in two places only, each when its flag is given: with --state-dir, inside it, each index's change log, its lock, and a shortened log beside it before it replaces it; with --stats-file PATH, PATH and PATH.tmp beside it. Give the stats file a directory of its own that only the service's user can write, as with RuntimeDirectory under systemd.
  • Anyone who can write to the task stream can ask it to search any index it serves, and read the ids and values that match, and anyone who can write to Redis can name another application's reply_to: a reply stream's name authenticates nobody. The control is the Redis instance's access rules: a dedicated instance, a password or an ACL user per application, and a private network path. Don't serve an index to a stream more people can write to than may read it.
  • Every request's cost is bounded before it runs: its bytes, its values, its radius, the matches it keeps and its time. A request can't make the worker hold more than the limits allow, and nothing a task holds makes it panic.
  • With --state-dir, anyone who can write to the task stream can change an index: add, replace and remove records. The same control applies; a change can't make the worker hold more than --max-log-bytes of log.
  • Whoever can write a set's directory chooses what is served, and whoever can write the state directory, what is changed over it. Snapshots and logs are checked for consistency, not authenticity: a checksum catches damage, not a writer who rewrites both, and nothing detects a directory rolled back to an older, consistent state.
  • A load failure is logged in fixed words, with positions and counts and at most a 64-byte label of printable ASCII for a file's name, never the text a manifest or CURRENT holds; legit-hamming verify prints the library's full message to the person who runs it.

Changes

0.1.1

Documentation only: the append example now sends 256-bit records to its 256-bit index, and the crate's manifest links its page.

0.1.0

The first release: the search library, snapshots, and the legit-hamming program with query, stats, verify, info and, with the serve feature, the worker on Redis Streams with changes through an ordered log.

Credits

  • Wojciech Muła, Nathan Kurz and Daniel Lemire, "Faster Population Counts Using AVX2 Instructions" (The Computer Journal 61(1), 2018; arXiv:1611.07612), for the per-lane nibble lookup the AVX2 and AVX-512 BW paths use.
  • Mohammad Norouzi, Ali Punjani and David J. Fleet, "Fast Search in Hamming Space with Multi-Index Hashing" (CVPR 2012), for multi-index hashing and its pigeonhole bound.
  • Guy L. Steele Jr., Doug Lea and Christine H. Flood, "Fast Splittable Pseudorandom Number Generators" (OOPSLA 2014), for SplitMix64, which draws the neighbour table's sample.
  • The hamming_rs crate, an implementation of the same paper for long byte strings, was read for its technique. It isn't used: below 1,024 bytes it counts 64 bits at a time, and our values are 8 and 32 bytes.
  • The memmap2 crate, by the memmap2 developers, for mapping snapshot files, and the sha2 crate, by the RustCrypto developers, for their checksums.

Why a crate of its own: a search service needs exact answers with record ids, a reply that says what cut it and how it ran, vector paths chosen at run time and proven equal to a scalar reference, a choice between scan and index per query, and a snapshot format another language can write. It builds those on the published techniques above.

Testing

cargo test -p legit-hamming

The change log is checked against a model: random interleavings of append, replace and remove, repeats of earlier tasks, swaps to snapshots with and without covers_seq (each row read at its own moment after the position covered), snapshots that must be refused, restarts, and searches with limits, after every one of thousands of steps at each width compared with a plain map and a brute-force search. A log is cut at every byte offset and damaged at every byte, and must recover to exactly its whole tasks or refuse; a task logged and not answered, delivered again after a later change, leaves the later value; a second writer is refused. Breaking the masking, the replay, the repeat check or the recovery rule each fails them.

The tests need no network and no service: the search service is tested in process, and its worker on legit-streams' in-memory Redis double, with every error type, each limit at and just over its bound, replies cut by limit, size and time, a swap while searches run, broken snapshots and CURRENT files, and stats in each state; the legit-hamming program is run for each command, and query and serve are checked to give the same bytes. They check every variant on every path the running CPU has against the reference, so on a CPU with no vector instructions they still pass, on the scalar path, and on Arm they check both NEON kernels. They write snapshots under the system's temporary directory and remove them. The README's example runs as a doctest, and a test checks that this README and --help name no file outside the published crate. The measurements under Sizing were made with a separate harness, not published, that runs the worker as separate processes against a real Redis.

License

MIT. See LICENSE.md.