Every near hash, from millions held in memory
Exact search within a Hamming distance 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.
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. The 64-bit and 256-bit hashes of legit-hashes, such as perceptual-v1, simhash-v1 and pdq-v1, fit the two widths it holds. A legit-hashes value prints as its definition, a colon and the hex (pdq-v1:…); the hex alone, which to_hex gives, is what a snapshot or a query takes. 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. 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, and an approximate nearest-neighbour index is smaller and faster where approximate answers will do. It has no distance but Hamming, holds no width but 64 and 256 bits (a shorter hash can be padded with zeros to 64 bits, which leaves its distances unchanged), and holds only sets that fit in memory. A set that must change transactionally with other data is better held by a database. And where a radius is so large, or the data so uniform, that most queries match much of the set, every exact method reads most records: this crate then scans, and nothing does better.
- Version
- 0.1.0, on crates.io
- Reference
- docs.rs/legit-hamming
- Source
- github.com/mferrara/legit-rs
- Licence
- MIT
- Needs
- Rust 1.99 or newer. The library depends on
memmap2,serde,serde_jsonandsha2, and has no framework dependency. - Feature
serve, off by default: the worker. It adds legit-streams (and through it theredisclient),signal-hook,tracingandtracing-subscriber.
A first search
[dependencies]
legit-hamming = "0.1"
A record is a fixed-width value, u64 or [u64; 4], with an application's 64-bit id or without one. This builds a set of 100,002 records, indexes it, and asks for everything within 5 bits of one value:
use std::sync::Arc;
use legit_hamming::{Options, Planned, Records, search};
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());
Ok(())
}
search returns a Found: the matches sorted by distance and then id, the candidates the query cost, the plan it ran with, and cut_by. search_batch takes many queries at once. A result is complete unless cut_by says what cut it: the caller's limit, which keeps the nearest by distance, never the first found; a size budget; or a time budget. Whatever cut it, every record nearer than the farthest match returned is returned, and nothing is cut silently. 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.
The records are held as columns: a column of ids and one column per 64-bit word of the value. 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 232 − 1 records.
Exact, whichever way it runs
Every way of searching returns exactly the reference scan's result set, on every code path and at every radius: the plan changes the cost, never the answer. The tests run each way, on each code 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, and values at exactly distance d and d + 1 from the queries.
Multi-index hashing, from Norouzi, Punjani and Fleet, splits a value into 16-bit chunks, four at 64 bits and sixteen at 256, with a table for each chunk, and probes each table with every key within that chunk's radius. The radii are chosen so that a value escaping every probe differs from the query in at least d + 1 bits: four chunks probed exactly find every pair to distance 3, and probed within 2, 1, 1 and 1 bits, every pair to distance 8. Every record is in every table, so records with equal values are separate entries, each compared and each returned.
Scan or index
Planned holds the records and, within a memory budget, the multi-index tables. For each query it counts what a probe of the tables would read, exactly, from the tables' own bucket sizes for that query's keys, and compares the two costs:
- a probe costs its keys plus 32 times its candidates, in records scanned;
- a scan costs its records;
- the cheaper runs, and a tie scans. Without tables, every query scans.
The factor of 32 comes from radius sweeps on an Intel Xeon Gold 5412U on 2 December 2026, as the time a multi-index query took per candidate over the time the best scan took per record. A wrong choice near the line costs at most about twice the other way. Threads follow the same estimate: a 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.
| Radius | Best scan | Multi-index | Planned |
Its plan |
|---|---|---|---|---|
| 0 | 23.1 | 110,788 | 138,616 | index |
| 2 | 23.7 | 11,200 | 12,034 | index |
| 3 | 23.7 | 7,948 | 9,555 | index |
| 5 | 23.7 | 1,354 | 1,504 | index |
| 8 | 23.8 | 410 | 466 | index |
| 10 | 23.9 | 102 | 110 | index |
| 12 | 23.8 | 61.4 | 66.8 | index |
| 16 | 23.8 | 12.7 | 25.2 | scan |
On these values Planned took the faster way at every radius: the tables to radius 12, the scan at 16. On a synthetic 256-bit set it took the tables through radius 31 and the scan from 48. The rest of the sweeps, on synthetic sets and on 16 threads, are in the README.
Code paths
The scan's kernel is picked at run time for each width, from what the CPU has and what was measured: on x86-64, avx512 (a vector population count), then avx512bw and avx2 (the per-lane nibble lookup of Muła, Kurz and Lemire), then popcnt, then scalar; on Arm, neon at 256 bits and neon-wide at 64; anything else, scalar. Every path has a scalar fallback, and Cpu::detect() reports what was found. unsafe code lives in three modules only, each block with a SAFETY: comment; the kernels are behind safe wrappers that check the CPU before every call, and the rest of the crate denies unsafe. No CPU with AVX-512 BW but no VPOPCNTDQ, and none with AVX2 but no AVX-512, has been measured.
As a search 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 on the command line, and serve, built with the serve feature, as a worker on the Redis Streams work contract of legit-streams. 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, so an application can test its reader without a Redis. stats prints each set's state and measured neighbour table, verify checks one snapshot, and info prints the code paths, the formats and the versions.
cargo install legit-hamming --locked --features serve
--locked builds with the dependency versions the release was tested with. Its dependencies are version ranges: a worker you deploy is best built from a lock file you have tested.
A first run
A set is a directory holding snapshot directories and a one-line file, CURRENT, naming the one to serve. From Rust, inside a function that returns a Result:
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",
)?;
Check it, and search it within 31 bits 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
The answer, written on one line, is shown here broken over several, with the middle of each 64-digit value shortened by …:
{"format":1,"index":"images-pdq","snapshot":"2026-12-02T12-00-00Z","seq":0,
"exact":true,"queries":[{"matches":[
{"id":17,"value":"9f3a0000000000ff…0000000000000001","distance":3},
{"id":40,"value":"0000000000000007…0000000000000007","distance":22}],
"complete":true,"plan":"scan"}]}
Then the same as a worker: a throwaway Redis, 6.2 or newer, in one terminal; the worker in a second; and in a third, one task and its result.
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
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.
Searching
| 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} |
A task is the legit-streams envelope, which the worker echoes, with one payload field, options, a JSON object as text. Its task_name says what to do: search, stats, or, with changes on, append, replace and remove. A search names the index, its width (64 or 256), the radius, and one or more query values as hex, most significant digit first; it may also name a subset to search instead, a limit that keeps only the nearest matches of each query, and exclude_zero, which leaves the all-zero value out. No other key is taken: a misspelt one is invalid_options, not ignored.
The result has one entry in queries for each value, in order. Each match carries the stored value, its distance, and its id unless the set has none. complete says whether the list is every match within the radius; when it is not, cut_by says what cut it (limit, size or time) and the list still holds the nearest. exact is always true; snapshot names the snapshot searched, seq the last change applied over it, and plan says whether the query was a scan or multi-index. An error carries an error_type, such as unknown_index, radius_too_large, too_many_values or not_ready, while a set has no snapshot loaded yet; a reader treats a code it does not know as a failure a retry will not fix.
The fast lane takes one value a request, for a caller that waits: its reply goes to a key the caller names, and on a timeout the caller falls back. A bulk search is the same task with many values, read from the application's result stream with a consumer group. Results arrive at least once: handle a repeated task_id once.
Snapshots on disk
A snapshot is a directory of part files, fixed-width little-endian records with no header, and a MANIFEST.json that gives the width, whether ids are present, the counts, and each part's size and SHA-256, as sha256sum prints it. Another language can write one: the README has an exporter in PHP with no library.
- Handing over. The exporter writes the parts, then the manifest, into a new directory, then writes
CURRENTlast, as a new file renamed over the old, so a reader never sees half of one. A snapshot is never changed onceCURRENThas named it; the next export is a new directory. - Loading. A new snapshot is loaded beside the one served, with every part's size and checksum checked and its ids checked to rise, then its tables are built and it is swapped in in one step. Searches already running finish on the one they started on, and each reply names the snapshot it searched.
CURRENTis read again 30 seconds after each check ends, by default. - Refusals. A snapshot that fails to load is logged with its reason and never replaces one that is served. A symbolic link in place of
CURRENT, a snapshot directory, a manifest or a part is refused. - Joining the group. At start,
serveloads every set that has a snapshot before its workers take a task, so a restarting worker never takes a task it could only answernot_ready. - Tables. By default they are built when they fit in the memory left once the records are loaded, keeping back a quarter of it and at least 512 MiB; without them every query scans.
Changes
With --state-dir, serve also takes changes, on the bulk stream only: append adds records and refuses the whole task, with the ids at fault, when an id is held with another value; replace sets each id's value; remove removes ids. Each applied change is written to an ordered log for its index, each record at the next position, seq, and its result is written only after its entries are on disk and applied in memory, so once a result can be read, its records are searchable. A snapshot's manifest may carry covers_seq, the exporter's statement that every change up to that position is in it; when the snapshot is swapped in, the changes logged above it are replayed over it.
- One process serves an index once changes are on: a lock on its state directory refuses a second. Without changes, several workers may serve the same set directories.
- A
task_idis unique per index for all time. A task whosetask_idthe log holds is answered as it was the first time and changes nothing. Afterinternalormax_deliveries_exceeded, or no answer, the outcome is unknown: send the same task again under the sametask_id. The same goes for a refusal that may pass later (not_ready,log_full,unknown_index): keep thetask_id, or a copy still in the stream can land an older value after a newer one. - Send an id's current value, not its history. The README has a feeder in PHP that keeps each record to one task in flight, and the cases it is built for.
On the storage model the README sets out, a local filesystem with a working fdatasync among its conditions, a change whose result was written stays applied across a clean stop, a kill at any moment, a machine failure and any number of swaps. Damage inside the last task of a log cannot be told from an unfinished write and is cut; damage before it refuses the index rather than guessing. A network filesystem, or a state directory moved, replaced or shared while serve runs, is outside what is promised.
Limits
Every request's cost is bounded before it runs. Each limit is a flag of query, stats and serve, and is in every stats result:
| Flag | Default |
|---|---|
--max-values-fast | 1 value a quick request |
--max-values | 5,000 values a bulk task |
--max-options-bytes | 1 MiB of options |
--max-radius-64 | 16 |
--max-radius-256 | 96 |
--max-matches | 10,000 matches a query |
--fast-query-time | 2 s of collecting a quick request's candidates |
--query-time | 30 s of collecting a bulk task's, all its values together |
--max-result-bytes | 32 MiB of result object |
--max-change-records | 1,000 records an append or replace |
--max-remove-ids | 10,000 ids a remove |
--max-log-bytes | 256 MiB of an index's change log |
The two times are search budgets: a search stops collecting candidates once one has passed and keeps only its matches at distance 0, since a record it did not reach could be nearer than a match it found. They do not bound how long a task takes from the caller's side. Each query's share of the result bound is fixed before the search: at the defaults, a bulk task of 5,000 values keeps at most 91 matches a query at 64 bits and 55 at 256. Use limit, or smaller tasks, to choose. None of the limits bounds the process's memory: that is the snapshots served, two copies of a set during a swap, their tables and the changes held over them.
Under a supervisor
On SIGTERM or SIGINT, serve 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. Standard error carries JSON log lines and a heartbeat with counts, and the service never logs a query value, an id or a match. With --stats-file PATH the worker also writes what it has done and what it serves to a file, as one JSON document rewritten whole at every heartbeat, for a collector on the same machine: counts and rates for each lane and each task name, the median and the 95th and 99th percentiles of its processing time, the records served and the stream's backlog. The file holds numbers and fixed words only: never an index, stream or host name, a path, a value or an id. Give a Redis URL that holds a password in LEGIT_HAMMING_REDIS_URL. The README has a systemd unit.
Security
- Anyone who can write to the task stream can search any index the worker serves and read the ids and values that match, and, with
--state-dir, change an index. 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. Do not serve an index to a stream more people can write to than may read it. - Apart from Redis, the worker opens no network connection, fetches nothing a task names and starts no program. It writes files only inside the state directory and at the stats file's path, each when its flag is given.
- The set directories and the state directory are trusted configuration. Its checks catch mistakes and stray links; they are not a defence against a local party who can write those directories while it runs. Snapshots and logs are checked for consistency, not authenticity: a checksum catches damage, not a writer who rewrites both.
From PHP
No client library is needed. The README shows, in PHP: an exporter that writes a snapshot and its manifest; a quick search with plain Redis commands, XADD on the fast stream and XREAD on the reply key; and a feeder that sends an application's changed records in batches and clears each mark when its result confirms it. PHP's integers are signed 64-bit, so an id at or above 263 needs a decoder that keeps it whole, such as json_decode with JSON_BIGINT_AS_STRING.
What was measured
These figures are the crate's own, from its README, measured on 2 December 2026. "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, and the queries are 80% a stored value with 0 to radius + 2 bits flipped and 20% uniform.
| Workload | Records | Best scan | Multi-index |
|---|---|---|---|
| One query at a time, 64-bit, radius 5 | 90M real | 25.5 (39 ms) | 1,290 to 1,533 |
| One query at a time, 64-bit, radius 8 | 90M real | 25.5 | 481 |
| The same, on 16 threads | 90M real | 181 | 1,131 |
| Batches of 100,000, 64-bit, radius 8, 16 threads | 90M real | 947 | 5,039 |
| One query at a time, 64-bit, radius 8 | 90M synthetic | 25.7 | 166 |
| One query at a time, 256-bit, radius 31 | 90M synthetic | 6.0 (166 ms) | 47.4 |
| The same, on 16 threads | 90M synthetic | 46.2 | 350 |
The tables took 1,374 MiB over 686 MiB of real values and were built in 0.64 s. The real values ran about three times faster through the index than synthetic ones of the same size, 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. On an Apple M2 Pro, one thread, the index won every workload measured: 2,618 queries a second against 671 for the best scan at 10 million synthetic 64-bit records and radius 8.
Checked against real data
On the same Xeon, while it carried other load, 8,000 quick lookups went 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, and each reply was compared with an independent brute-force search that shares no code with the 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, holding the nearest by the count at each distance. Round trips from a client on the same machine, the client included, were a median of 0.87 ms at radius 5 on the 64-bit set, and 1.05 ms at radius 31 on the 256-bit set. In the same check, three swaps to a new snapshot ran while four callers sent quick lookups back to back, with no failed, not_ready or missing reply in 214,843 calls; and a worker was killed with SIGKILL while 300 append tasks were being sent: after the restart every acknowledged record was there, and the tasks not yet acknowledged were each applied exactly once.
Sizing
Measured on 2 December 2026 with the worker running as a separate process against Redis 8.0.5 on the same machine, in a container limited to 2 cores of the same Xeon and 8 GiB, one worker, on synthetic records with ids. 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).
| Records | Width | Resident at rest | Peak of a swap | Quick path, median / 99th percentile | Bulk, queries a second |
|---|---|---|---|---|---|
| 1 million | 64 | 36 MiB | 68 MiB | 0.27 / 0.54 ms | 35,405 |
| 1 million | 256 | 109 MiB | 211 MiB | 0.47 / 0.70 ms | 8,707 |
| 10 million | 64 | 314 MiB | 619 MiB | 0.96 / 1.19 ms | 2,814 |
| 10 million | 256 | 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, 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. On the same 2 cores, with 10 million 64-bit records, change tasks of 1,000 records, each written and synced before its result, ran at 555 tasks a second, and 1,010,000 changes held over the snapshot moved the quick path's median from 0.88 to 1.25 ms.
Testing
The tests need no network and no service. Every way of searching is checked on every code path the running CPU has against the reference, so on a CPU with no vector instructions they still pass, on the scalar path. The change log is checked against a model, through random interleavings of changes, repeats, swaps and restarts compared with a plain map and a brute-force search after every step, and a log is cut at every byte offset and damaged at every byte, and must recover to exactly its whole tasks or refuse. The service is tested in process, and its worker on the in-memory Redis double of legit-streams, with every error type and each limit at and just over its bound; query and serve are checked to give the same bytes. The measurements above were made with a separate harness, not published.
What it does not do
- It finds no approximate neighbours and computes no distance but Hamming, over values of 64 or 256 bits.
- It holds a set in memory, not on disk: a set larger than memory, or one that must change in a transaction with other data, belongs in a database.
- It computes no hashes. legit-hashes and legit-hasher do that.
- It does not authenticate a snapshot or a log, or tell a directory rolled back to an older, consistent state.
- With changes on, it does not replicate an index: one process serves it.
The README has the rest: every variant and code path, the snapshot format, every option, state and error code, the stats file's fields, the change log's rules and recovery, the PHP exporter, quick path and feeder, a systemd unit, and every measurement.
The drawing above the crate's name is a search, drawn from real perceptual-v1 hashes, compared bit by bit by this site, not by this crate. In the gauge is View of Rome's hash, from the legit-hashes Try it page. On the belt, the spur and the racks are twelve others: the five changed copies of View of Rome that the legit-hashes pages show, and the other seven pictures of the Try it page. The three within 8 bits of it, in pencil on the spur, are the copies shrunk to half the size (0 bits), saved as a JPEG at quality 30 (2) and cut by a twentieth at every edge (8); every other is 16 bits or more away. They were computed by this site with legit-hashes.