Its last report came less than a minute and a half ago.

Hashed so far
15,041,981
A second, over the last 30 seconds
274
Being hashed right now
64

legit-hasher 0.1.1

Image and text hashes, for programs in any language

A command-line program that computes every definition of legit-hashes: write requests to it as JSON lines, and read one JSON line of results for each. Built with the serve feature, it also takes the same requests as tasks from Redis Streams.

It hashes PNG and JPEG files with PDQ, blockhash and the 64-bit image hashes, and text with SimHash and MinHash, with the index keys to store beside each hash. A program in PHP, Python or anything else gets the same bits a Rust program does, without a port, and can hand all its hashing to a larger machine. Batches of millions run on every core with flat memory, and resume where they stopped.

It reads PNG and JPEG and no other image format. It hashes text exactly as sent, and reports the quality of a PDQ hash without discarding any hash. And as a worker it is not a control plane: who may send it tasks is a matter for the Redis server's access rules.

Version
0.1.1, on crates.io
Reference
docs.rs/legit-hasher
Source
github.com/mferrara/legit-rs
Licence
MIT
Needs
Rust 1.99 or newer, to build it. Without the serve feature, nothing compiles C or downloads anything at build time.
Feature
serve, off by default: the worker. It adds legit-streams, ureq with rustls, tracing-subscriber and signal-hook. ring, the crypto provider of rustls, compiles C and assembly.

One request, one result

Install it with cargo. --locked builds with the dependency versions the release was tested with.

cargo install --locked legit-hasher

Then hand it a request on standard input, one JSON object on one line:

echo '{"id": "cat", "path": "cat.jpg", "options": {"format": 1, "definitions": '\
'[{"id": "pdq-v1"}, {"id": "perceptual-v1"}]}}' | legit-hasher run

It writes one result line, shown here broken over several lines, with long values shortened by …. The program writes each result on one line and never shortens anything.

{"format":1,"id":"cat","line":1,"status":"success","width":1024,"height":768,
 "source":{"bytes":232481,"sha1":"4f1c…"},
 "decode":{"format":"jpeg","frames":1,"orientation_tag":null,
           "orientation_applied":false,"truncated":false},
 "runner":{"name":"legit-hasher","version":"0.1.1","hashes":"0.2.1",
           "decoder":"image 0.25.10"},
 "hashes":[{"id":"pdq-v1","value":"pdq-v1:e2a1…","quality":87},
           {"id":"perceptual-v1","value":"perceptual-v1:c3f00f3c99a5a55a"}]}

Besides its id, echoed back untouched, a request has exactly one source, path (a file on the runner's machine), text or base64 (image bytes sent from another machine), and options: the format version 1, one to 16 definitions, and orientation, which by default hashes the pixels as stored. A field the format does not define is refused, so a misspelt option fails loudly rather than being ignored.

The definitions it computes
Definition Reads Hash Index keys
average-v1image, luma64 bitschunk_keys
difference-v1image, luma64 bitschunk_keys
perceptual-v1image, luma64 bitschunk_keys
pdq-v1image, RGBA256 bits, and a qualitychunk_keys
blockhash-v1image, RGBA256 bitschunk_keys
simhash-v1text64 bitschunk_keys
minhash-v1text128 values of 32 bitsband_keys
minhash-legacy-v1text128 values of 32 bitsband_keys

A text definition takes exactly one of shingle: n, every window of n characters, and tokens: "words", and has no default, because what you store depends on it. chunk_keys: n splits a hash into n index keys, and two hashes within distance d share one when n is at least d + 1. band_keys: n returns a signature's n band keys, n dividing 128. Keys are signed 64-bit integers, for a BIGINT column. The legit-hashes pages explain each definition and its keys.

Any file but a PNG or a JPEG is a decode_failed result whose detected_format, such as gif or webp, is read from its first bytes, so failures can be counted by format. One decode serves every image definition in a request.

A large batch

legit-hasher run --input requests.jsonl --output results.jsonl --progress 30

Resuming

When a run stops, run the same command again with --resume. Every request whose id already has a result line is skipped, a last line without its newline, which a killed process can leave, is cut off and its request runs again, and --retry-failed runs the failures again. In request order, the output is byte for byte what an uninterrupted run would have written, apart from retried failures, which come last. Resuming holds about 32 bytes a request, about 3.2 GB for 100 million, so split batches that large into files of a few million requests.

Damaged files

A JPEG cut off part way often still decodes and hashes without an error, and its PDQ quality can even be high. So decode.truncated says whether the file ends where its format says it should. A truncated file is still hashed and still a success: to keep damaged files out of an index, check the flag. Damage inside a complete JPEG, such as corrupt compressed data, is not detected.

Errors and exit status

A failure is a result line with a stable error_type, and the run goes on: read_failed, too_large or decode_failed, for instance, for a whole request, or wrong_source or invalid_parameter for one definition, whose failure leaves the other entries standing. Match on error_type, never on the message.

How run exits
Status When
0Every request succeeded with every definition.
1A request or a definition failed. Each failure is a result line, and the run went on.
2The run itself could not go on: a mistaken flag, an unreadable input, an unwritable output, or an output to resume that is not this runner's.

Two more commands

legit-hasher distance reads pairs of stored hashes and gives their Hamming distance, or, for two MinHash signatures, how many values match and the estimated Jaccard similarity. legit-hasher info reports the format version, the definitions, the limits and the CPU's instruction sets. Nothing detected changes a hash: the runner uses no fused multiply-add and no reordered sums for pdq-v1, and no SIMD of its own, so a definition's output is the same on every machine.

As a worker

Built with the serve feature, legit-hasher serve is a worker on the Redis Streams work contract of legit-streams: applications add hashing tasks to a stream, any number of workers on any machines take them, and each result goes back to the stream the task names. A task holds the same request a line of run holds, and its result the same object, so a caller can develop against the command line and move to the stream unchanged.

cargo install --locked legit-hasher --features serve

By default serve refuses an image over 50 million pixels and a text over 1 MiB, which run does not. Give run the same --max-pixels and --max-text-bytes to get the same answer for a request with one fault.

A first task

In three terminals: a throwaway Redis, 6.2 or newer; a worker; then one task and its result.

docker run --rm -p 6379:6379 redis:8
legit-hasher serve --redis redis://127.0.0.1:6379
redis-cli XADD hash_tasks '*' task_id app_1 model_type post model_id 42 \
  task_name default model_name '' source app v 1 text_data 'Where is the station?' \
  options '{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}'
redis-cli XRANGE hash_results - +

The result is a flat map: the echoed envelope, status, worker_id, processing_ms and result, the object run writes for the same request without its line. Broken over lines, with the hash shortened:

{"format":1,"id":"app_1","status":"success",
 "runner":{"name":"legit-hasher","version":"0.1.1","hashes":"0.2.1",
           "decoder":"image 0.25.10"},
 "hashes":[{"id":"simhash-v1","tokens":"words","value":"simhash-v1:…"}]}

Streams and fields

The keys of the task kind hash
What Name
Bulk task streamhash_tasks
Worker group, both laneshash_workers
Result stream of a task that names no reply_tohash_results
An application's result streamresults:{app}:hash
Fast task streamhash_tasks:fast
A fast task's reply keyresults:{app}:hash:rpc:{task_id}

A task is the contract's envelope, which the worker echoes untouched, with options as JSON text and one source: text_data, image_data (base64, for small images, since a stream holds its tasks in memory) or image_url (bulk lane only). Unlike run, the worker ignores fields it does not know, as the contract says, so a misspelt field is missing rather than refused. A request that fails as a whole still carries the whole object in result. Results arrive at least once: treat a second result for a task_id as a repeat. --kind renames hash, and --key-prefix puts a prefix before every key.

The fast lane

For text and distance tasks a caller waits for, a worker also reads hash_tasks:fast, on threads of its own, so bulk work never delays it. The caller names its reply key and, optionally, a deadline, reads the reply, deletes the key, and falls back to the bulk lane or an error on a timeout. An image gets invalid_task there. --fast-jobs sets how many fast tasks run at once, 2 by default.

Fetching by URL

image_url is for images held elsewhere, such as presigned URLs of object storage. Anyone who can write a task can make the worker fetch a URL, so the defaults are closed:

The worker judges an address, not the network's routing: a VPN, a translator prefix or a tunnel can carry a public address somewhere private, so fence the worker at the network's edge too. Its HTTP client is pinned to the release these guarantees were checked against, ureq 3.5.2. Of the codes a fetch can fail with, host_not_allowed repeats until the allowlist or the URL changes, url_expired (a 401 or 403) needs a fresh URL, and a caller may send a download_failed task again, a bounded number of times, with a pause.

Sizing a worker

--jobs defaults to the cores, not the memory. An image task holds its source and about 14 bytes a pixel, so at the default limit of 50 million pixels one can need about 780 MB. Set --jobs, --max-pixels and a memory limit on the process together:

An 8-core machine with 4 GB for the worker
Settings Worst case
--jobs 4 --max-pixels 50000000about 3.1 GB
--jobs 8 --max-pixels 25000000about 3.5 GB

With image_url the time is the fetch, not the hash, so the right --jobs is several times the cores, within that bound; measure against your own store before choosing. The limits bound one task, and none is a quota: give producers a Redis account of their own, and the workers one that reads tasks and writes results.

Under a supervisor

On SIGTERM or SIGINT, serve takes no new task and releases at once the tasks whose fetch has not begun, so another worker claims them. The rest get 30 s by default to finish, and what still runs then is released too. It answers the fast tasks it has read and exits 0. A second signal ends it at once with status 1, and its tasks are claimed by other workers after the contract's 300 s. It exits 2 when it cannot start; once running, a failed command is logged and tried again. Standard error carries JSON log lines, which never hold a payload, and a heartbeat with counts. With --stats-file PATH the worker also writes what it has done to a file as one JSON document, rewritten whole at every heartbeat, for a collector beside it, such as a metrics agent or a status page, to read without parsing the log: counts, each lane's rate, the median and 95th percentile of the time a task took, accurate to within 10%, the values computed for each definition, and the task stream's backlog. The file holds numbers only: never a stream, host or application name, a URL, an error's text or a hash. Give a Redis URL that holds a password in LEGIT_HASHER_REDIS_URL, and never install the worker setuid or with file capabilities. The README has a systemd unit.

Running on this server

This site runs the program it describes. Beside its web server run a Redis of its own and one worker: this program, installed from crates.io with the command above and started as legit-hasher serve. No host is allowed, so it fetches nothing, and the web process sends it text only, with the legit-streams client.

Send it a text

The web process adds one task to hash_tasks:fast and waits up to 2 seconds on the task's reply key. The task is the contract's envelope, the text in text_data, and these options, sent as one line. They ask for a hash of the text's words, and for a signature of its runs of five characters, the size the README suggests starting with, with 16 band keys:

{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"},
 {"id":"minhash-v1","shingle":5,"band_keys":16}]}

What you type travels in this page's address, so it reaches the server's log like any address does. It also passes through the site's own Redis on its way to the worker, and is deleted there once the worker has answered it, or, if none answered in time, when a worker next reads it and discards it. The worker's log lines never hold a task's text. Up to 200 characters; do not paste anything private.

What the worker says of itself

The worker is started with --stats-file, and every number here is read from that file: the site counts none of them. It is legit-hasher 0.1.1, and has run for 15 hours 27 minutes. The bulk tasks are the ones the legit-streams page describes, one every 15 seconds from each web process of this site; the fast tasks are visitors', from this form and that page's.

Tasks the worker has answered since it started
Lane Answered A second Median time 95th percentile
Bulk7,3530.1276 µs357 µs
Fast110.0nonenone

A rate or a time covers the stretch between one writing of the file and the next, and reads none when the worker answered no task in it. The times are the worker's own, for one task, and are accurate to within 10%.

simhash-v1 values computed
7,364
minhash-v1 values computed
10
Bulk tasks no worker has taken yet
0
Bulk tasks taken and not yet answered
0

The worker wrote these numbers less than a minute and a half ago. These are the numbers as this page was served.

From PHP

For a batch, write the requests to a file, run the program over it, and read the results file. For one request at a time, keep a runner open on a pipe: results come back in order, one line each, as soon as each is ready.

<?php
$runner = proc_open(['legit-hasher', 'run', '--jobs', '1'],
    [0 => ['pipe', 'r'], 1 => ['pipe', 'w']], $pipes);

function hash_text($pipes, string $id, string $text): array
{
    fwrite($pipes[0], json_encode([
        'id' => $id,
        'text' => $text,
        'options' => ['format' => 1, 'definitions' => [
            ['id' => 'minhash-v1', 'shingle' => 5, 'band_keys' => 16]]],
    ]) . "\n");
    fflush($pipes[0]);
    return json_decode(fgets($pipes[1]), true, 512, JSON_THROW_ON_ERROR);
}

$result = hash_text($pipes, 'message-1',
    'your parcel is waiting: confirm your address today');

fclose($pipes[0]);
fclose($pipes[1]);
proc_close($runner);

Do not write a large batch into the pipe before reading: the runner stops reading when its output is not read, so both sides would wait. The worker needs no client library either: a producer adds a task with XADD and reads its result stream with XREADGROUP. The README shows both lanes from PHP.

Memory

At most 4 × jobs + 4 requests are in flight, and no line over --max-line-bytes, 8 MiB by default, is held: in a measurement, 200,000 short texts peaked at 11 MB, the same as a few. An image needs about 14 bytes a pixel with pdq-v1 and the others together, plus the file: about 300 MB for a 23-megapixel photograph, measured. The decoder's limits keep one worker under about 3.8 GiB, which info reports as limits.worker_peak_bytes, and --max-pixels N lowers that to about 14 × N bytes plus the file and 16 MiB of metadata. run has no --max-pixels by default.

Choose --jobs so that jobs × (file + 16 MiB + 14 × the largest image's pixels) fits in memory, and no more than the cores. For camera originals of up to 50 megapixels in files of up to 64 MiB, that is about 780 MB a job; for thumbnails, memory does not limit it.

On 64-bit Linux with glibc, run and serve set glibc's allocator to keep freed blocks of up to 32 MiB for reuse, so the pages of each image are not faulted in afresh. The results are the same byte for byte, and the gain is on images under about 8 megapixels, whose blocks fit under that size. LEGIT_HASHER_MALLOC=default keeps glibc's own settings, setting GLIBC_TUNABLES, even to an empty value, leaves the allocator alone, and elsewhere nothing changes; info says which is in effect.

What was measured

Unless a line says otherwise, these come from the crate's own smoke runs of December 2026, on x86-64 Linux machines with glibc, over generated and public-domain files.

Per core

One decode then three hashes, on one core
JPEGs A second
Thumbnailsabout 420
Medium, 1.5 megapixelsabout 21
Large, 23 megapixelsabout 0.64

The hashes are pdq-v1, blockhash-v1 and perceptual-v1, and pdq-v1 is two thirds of the large-image cost. This is the measurement of legit-hashes 0.2 on photographs, on an x86-64 Linux server, whose machine and rows are on the legit-hashes benchmarks page. The runner adds little to it: it decodes once and hashes on every core.

The allocator setting

run with pdq-v1 and perceptual-v1 on a 2-core x86-64 machine, the median of three runs each: with glibc's defaults, with the same settings given to glibc through GLIBC_TUNABLES, and with the program's own.

5,000 JPEGs of about 26 KB
Allocator Files a second Kernel's share of CPU time Peak memory
1 job 16 jobs 1 job 16 jobs 1 job 16 jobs
glibc's defaults5831,06114.9%18.4%12.5 MiB20.8 MiB
GLIBC_TUNABLES7151,2821.8%1.2%12.5 MiB22.0 MiB
The program's own7261,2871.6%1.4%12.5 MiB21.7 MiB
200 JPEGs of 1.5 megapixels
Allocator Files a second Kernel's share of CPU time Peak memory
1 job 16 jobs 1 job 16 jobs 1 job 16 jobs
glibc's defaults19.736.814.4%16.0%28.0 MiB335 MiB
GLIBC_TUNABLES25.142.80.6%1.8%27.9 MiB392 MiB
The program's own25.242.40.6%2.1%27.9 MiB390 MiB

Connection reuse

The crate's smoke test sent 3,000 tasks by image_url through a Redis 8 server, from a plain http server on the same 2-core machine, with images of about 27 KB, to an earlier build that opened a connection for almost every fetch and to the build that keeps one a job open.

3,000 fetches on one machine, over plain http
Jobs Connections opened Tasks a second
Earlier build Reusing build Earlier build Reusing build
--jobs 822972,3592,569
--jobs 64559592,0532,367

Over a network each connection saved is also a round trip, and over https a TLS handshake.

On a 16-core host

Separate runs on a 16-core host: one million stored JPEGs of about 29 KB hashed at about 4,000 a second with 16 jobs, about 450 a second on one core, and the allocator setting cut system time from about 20% of CPU to about 1%, for about 14 MB of resident memory at 16 jobs. Fetching cached objects of about 29 KB by URL, a worker ran about 200 tasks a second at --jobs 8 and 600 to 900 at --jobs 64; --jobs 128 gave fewer, as something beyond the worker saturated. A first fetch of an object the store had not cached took about 230 ms.

Copies at different sizes

To compare images stored at different sizes, reduce each to one size, then hash. In the legit-hashes 0.2 measurement, two copies of a picture at different resolutions, each reduced to 500 pixels on its long side, differed by a median of 0 to 2 bits of pdq-v1, with no pair past 31 bits, Meta's suggested threshold; a reduction against an original, by a median of 10. Two reductions of one file are the best case: copies held separately sit further apart, so measure on your own data before choosing a threshold. The legit-hashes guide says more.

Testing

The tests run the built program. A golden request file covering every definition, every source and every error code run gives but internal is compared byte for byte with committed results, and each hash in them is checked against legit-hashes. Other tests cover one job against eight, resuming from a cut at any point, a million short requests in bounded memory, every EXIF orientation and cut JPEGs, on images the tests make themselves. The worker's tests run on the in-memory double of legit-streams and check that it gives the result object run gives, field for field. Fetching is tested against a plain http server on 127.0.0.1; for https, connection reuse rests on the pool of ureq. No test reaches another machine.

The format is versioned

Format 1 is in every result line and in info, and required in every request. Removing or renaming a field or an error code, changing a field's type or meaning, changing the order or number of result lines, or changing what a successful value is would come with format 2. A new definition, parameter or result field can come in any release, so ignore result fields you do not know. A definition's output never changes: a new one is added beside the old.

What it does not do

The README has the full contract: every request and result field, every flag, limit and default, every error code, the stats file's fields, the library's API, the PHP examples for both lanes, and a systemd unit.