legit-hasher 0.1.4

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
Documentation

legit-hasher

One implementation of the legit-hashes definitions for callers in any language. Write requests as JSON lines to legit-hasher run and read one JSON line of results for each: PDQ, blockhash and the 64-bit image hashes of PNG and JPEG files, SimHash and MinHash of text, with the index keys to store beside them. An application 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. legit-hasher distance compares stored hashes, and legit-hasher info reports the definitions, the limits and the CPU's instruction sets. Built with the serve feature, legit-hasher serve takes the same requests as tasks from Redis Streams and replies with the same results, so the runner can live on another machine than the applications it serves.

It's a command-line program and a plain Rust library, with no framework dependency.

Installation

cargo install --locked legit-hasher

--locked builds with the dependency versions the release was tested with. It needs Rust 1.99 or newer. Nothing compiles C or downloads anything at build time.

For the worker mode, turn on the serve feature:

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

It adds legit-streams for the work contract, ureq with rustls to fetch images by URL, tracing-subscriber for its log lines and signal-hook for a clean stop. The rustls crypto provider, ring, compiles C and assembly; the batch tool, without the feature, has none of these.

Security

run reads the files and texts its caller hands it. serve takes tasks from a Redis stream, and anyone who can write to that stream can make it fetch a URL and hash what it's given, so its defaults are closed and its limits are set:

  • No host is allowed: every image_url is refused until --allow-host or --allow-hosts-file lists a host.
  • Public addresses only: the worker connects to no loopback, private, link-local, shared, documentation, reserved, multicast or translated address, whatever the host resolves to, unless --allow-range opens its range.
  • The default port only: an allowed host is allowed on port 443 for an https URL, 80 for an http URL when --allow-http is set, or on the one port its entry names.
  • No redirects: a redirect is download_failed unless --max-redirects allows some, and then each is checked as the first URL is.
  • HTTPS only: plain http needs --allow-http, and never carries a user or password.
  • Three limits on what a task costs: a text of at most 1 MiB (--max-text-bytes), an image of at most 50 million pixels (--max-pixels) and a fetched body of at most 64 MiB (--max-fetch-bytes), besides the request format's own: at most 16 definitions, 64 KiB of options and a shingle of 64 characters.

Fetching by URL says what each check does and what it doesn't, and Sizing a worker what the limits mean for memory. Who may write tasks at all is a matter for the Redis server's access rules.

Quick start

echo '{"id": "cat", "path": "cat.jpg", "options": {"format": 1, "definitions": [{"id": "pdq-v1"}, {"id": "perceptual-v1"}]}}' \
  | legit-hasher run
{"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.4","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"}]}

Store each value as it is: it names its definition and parses back with legit-hashes. (Long values are shortened with … in this README; the program never shortens anything.)

Requests

One JSON object per line. Blank lines are skipped. A request has an id, exactly one source, and options:

{"id": "upload-90211344",
 "path": "/srv/media/90/21/1344.jpg",
 "options": {"format": 1,
             "orientation": "ignore",
             "definitions": [{"id": "pdq-v1", "chunk_keys": 16},
                             {"id": "perceptual-v1", "chunk_keys": 5},
                             {"id": "blockhash-v1"}]}}

(Shown over several lines here; on the wire each request is one line.)

Field Meaning
id Your id for the request, a JSON string or integer, echoed back untouched. Give each request its own: --resume finds finished requests by id.
path An image file on the machine the runner runs on. A relative path is read from the runner's working directory.
text UTF-8 text to hash. The runner changes no character: normalise first if case, whitespace or Unicode form shouldn't count.
base64 Image bytes, standard base64 (RFC 4648 section 4, padding optional), for images sent from another machine. At most limits.max_inline_bytes, which info states.
options.format The format version, 1. Required.
options.definitions One to 16 definitions to compute, each {"id": ..., <parameters>}. Results come back in the same order. The same id may appear twice with different parameters; the same definition with the same parameters twice is invalid_options.
options.orientation "ignore" (the default) hashes the pixels as stored. "apply" turns them upright by the file's EXIF orientation tag first. Use one setting for every hash you'll compare.

A field the format doesn't define is refused, so a misspelt option fails loudly rather than being ignored. options may take at most 64 KiB (65,536 bytes) of JSON: on the command line as compact JSON, in a task as its options field is sent. These limits are the format's own, the same for run and serve, and info states them.

Definitions and their parameters

Id Reads Hash Parameters Returns beside value
average-v1 image, luma 64 bits chunk_keys
difference-v1 image, luma 64 bits chunk_keys
perceptual-v1 image, luma 64 bits chunk_keys
pdq-v1 image, RGBA 256 bits chunk_keys quality, 0 to 100
blockhash-v1 image, RGBA 256 bits chunk_keys
simhash-v1 text 64 bits shingle or tokens, chunk_keys
minhash-v1 text 128 values of 32 bits shingle or tokens, band_keys empty
minhash-legacy-v1 text 128 values of 32 bits shingle or tokens, band_keys empty
  • shingle: n splits the text into every window of n characters (shingles_v1), n from 1 to 64; tokens: "words" splits it into ASCII-lower-cased words (words_v1), each occurrence a feature for SimHash. A text definition needs exactly one of the two: there's no default, because what you store depends on it. For MinHash on text, start with "shingle": 5.
  • chunk_keys: n returns the hash split into n index keys: from 1 to 64 for a 64-bit hash, from 4 to 256 for a 256-bit one. Two hashes within distance d share a key when n is at least d + 1.
  • band_keys: n returns a signature's n band keys, n dividing 128: 1, 2, 4, 8, 16, 32, 64 or 128. Two texts of Jaccard similarity s share a key with probability 1 - (1 - s^(128/n))^n.
  • Keys are signed 64-bit integers, for a BIGINT column, with the same bits as the unsigned keys legit-hashes defines.

The legit-hashes README defines each algorithm, says which to choose, and explains chunk and band keys in full.

Images

The runner decodes PNG and JPEG, telling them apart by their bytes, not the file name. Every other file is a decode_failed result whose message names the format read from its first bytes, such as unsupported format: gif, and whose detected_format holds it alone, so you can count failures by format. Named formats: gif, webp, avif, heic, heif, jxl, bmp, tiff, ico, pdf, psd, isobmff, html, svg, xml, json, empty and otherwise unknown.

One decode serves every image definition in a request. With pdq-v1 or blockhash-v1 the file is decoded to RGBA and the luma for the others is converted from it; with only the 64-bit image hashes it's decoded straight to luma. Either way the pixels, and so the hashes, are exactly what legit-hashes' decode_rgba_v1 and decode_luma_v1 give. A request with only text definitions on an image reads the file but decodes nothing.

Results

One JSON object per line, one per non-blank request line, with its fields in this order:

Field When Meaning
format always 1.
id always The request's id, or null when the line had none that could be read.
line always The input line the request came from, counting from 1, blank lines included.
status always success or error.
error_type, error on error A stable code from the list below, and a message for a person.
detected_format on error, when the bytes were read The format from the first bytes, such as gif.
width, height image decoded The size of the pixels hashed: after orientation, if applied.
source image read bytes, the source's byte length, and sha1, its SHA-1 as 40 hex digits: proof of which bytes were hashed. An identity check, not a security measure.
decode image decoded format (jpeg or png), frames (how many the file holds; the first is hashed), orientation_tag (the EXIF tag, or null), orientation_applied, and truncated (below).
runner always name, version, hashes (the exact legit-hashes release) and decoder (the decoder and its exact release), so every stored hash can record what made it: a decoder release can change pixels, and so hashes.
hashes on success One entry per requested definition, in request order.
timings with --timings, once a request was read read_us, decode_us and total_us, in microseconds.

Each entry of hashes is one of:

{"id": "pdq-v1", "value": "pdq-v1:<64 hex digits>", "quality": 87, "chunk_keys": [123, -45, …]}
{"id": "minhash-v1", "shingle": 5, "value": "minhash-v1:<1024 hex digits>", "empty": false, "band_keys": [-8238337276044841188, …]}
{"id": "simhash-v1", "tokens": "words", "value": "simhash-v1:6bd14870e74eef31"}
{"id": "pdq-v2", "error_type": "unsupported_definition", "error": "`pdq-v2` isn't a definition this runner offers; `info` lists them"}
  • value is the stored form legit-hashes defines, <id>:<hex>. Parse it back with Hash::from_str or Signature::from_str.
  • A text entry echoes its shingle size or its tokens.
  • empty: true marks a signature of a text with no features. Two empty signatures look identical, so leave them out of an index.
  • quality, on a pdq-v1 entry, is the field to gate on before storing or indexing the hash. Meta's reference discards hashes of quality 49 and under. In one million stored images, 0.20% scored 49 or under and 0.02% scored 0; the zeros were all within a few bits of each other, so low-quality hashes match each other and belong out of an index. The runner reports the quality and applies no gate: the threshold is the caller's.
  • An entry that failed carries error_type and error in place of value. The others still stand, and the request's status stays success.
  • time_us, with --timings, is the time this hash and its keys took.

A complete error line:

{"format":1,"id":"upload-17","line":43,"status":"error","error_type":"decode_failed","error":"unsupported format: gif; the runner decodes jpeg and png","detected_format":"gif","source":{"bytes":43,"sha1":"2daeaa8b5f19f0bc209d976c02bd6acb51b00b0a"},"runner":{"name":"legit-hasher","version":"0.1.4","hashes":"0.2.1","decoder":"image 0.25.10"}}

Damaged files

A JPEG cut off part way often still decodes, with the missing part filled in, and hashes without an error; its PDQ quality can even be high. So decode.truncated says whether the file ends where its format says it should:

  • JPEG: the runner follows the file's segments from the start-of-image marker, through the compressed data after each start-of-scan, to the end-of-image marker. true when the bytes run out first, false when the end marker is found, null when what's there isn't a JPEG structure it can follow. Bytes after the end marker are ignored. The decoder doesn't report the errors it recovers from, so damage inside a complete file, such as corrupt compressed data, isn't detected.
  • PNG: the runner follows the chunks to IEND. A cut PNG is refused by the decoder as decode_failed, so a successful PNG is false unless only its end chunk is missing.

A truncated file is still hashed and still a success: the flag is information. To keep damaged files out of an index, check it.

Error codes

The request as a whole, in error_type:

Code Meaning
invalid_request The line isn't a request: not JSON, not an object, no usable id, a field of the wrong type, a field the format doesn't define, invalid base64, or a line over --max-line-bytes.
invalid_options options is missing, over 64 KiB, lacks format or names another version, has no definitions or more than 16, holds an entry that isn't an object with a string id or that repeats an earlier one, gives an unknown orientation, or has a key the format doesn't define.
no_source No path, text or base64, or more than one.
read_failed The file at path couldn't be read: missing, unreadable, a directory, or gone since it was listed.
too_large Over a limit info states: the file's length, a side, the decoder's memory, --max-pixels (from the header, from what was decoded, or because the header gave no size), or a text over --max-text-bytes.
decode_failed The bytes aren't a PNG or JPEG the decoder can read: another format, damaged data or no image at all.
internal The runner failed on this request, such as a panic. Every other request still gets its result. Report it as a bug.
download_failed, url_expired, host_not_allowed Only from serve, for an image_url source: see Fetching by URL.

One entry of hashes, in its error_type:

Code Meaning
unsupported_definition The id isn't a definition this runner offers.
wrong_source An image definition on text, or a text definition on an image.
invalid_parameter A parameter the definition doesn't take, a value of the wrong type or out of range, or a text definition without exactly one of shingle and tokens.

Exit status

0 when every request succeeded with every definition, 1 when any request or definition failed (each failure is a result line, and the run went on), 2 when the run itself couldn't go on: a mistaken flag, an unreadable input, an unwritable output, or an output to resume that isn't this runner's.

Running a large batch

legit-hasher run --input requests.jsonl --output results.jsonl --progress 30
  • --jobs N hashes N requests at once, one thread each. The default is the logical cores available to the process.
  • Results come in request order. --unordered writes each as it finishes instead, which keeps every core busy when one request is much slower than the rest; match results to requests by id.
  • --progress SECONDS writes a JSON line to standard error at that interval, with done, failed, skipped, elapsed_s and per_second, and a last one marked "progress": "finished". Standard output carries nothing but results.
  • --timings adds the time each step took.
  • --input FILE reads the requests from FILE rather than standard input; --input - is standard input too.
  • --output FILE refuses a file that already exists, so a finished run is never overwritten by accident: resume it, or remove it.

Every flag that takes a value takes it as the next argument or after =: --jobs 4 or --jobs=4. legit-hasher help, -h or --help prints every command and flag, and legit-hasher --version or -V the version; both exit 0.

Resuming

When a run over millions of files stops, run the same command again with --resume:

legit-hasher run --input requests.jsonl --output results.jsonl --resume

Every request whose id already has a result line in the output is skipped, successful or failed, and the rest are appended. A line without its newline at the end of the file, which a killed process can leave, isn't trusted: it's cut off and that request runs again. A request whose line had no readable id is matched by its line number instead, so the input must be the same file. --retry-failed also removes the failed results from the output and runs those requests again. In request order, a resumed run's output is byte for byte what an uninterrupted run would have written, apart from any retried failures, which come last.

Resuming holds a 128-bit hash of each finished id, about 32 bytes a request: about 3.2 GB for 100 million. For batches that large, split the input into files of a few million requests and run them one after another.

Feeding it a list of files

Any JSON encoder will do. With jq, from find:

find /srv/media -type f \( -name '*.jpg' -o -name '*.jpeg' -o -name '*.png' \) \
  | jq -R -c '{id: ., path: ., options: {format: 1, definitions: [{id: "pdq-v1", chunk_keys: 16}, {id: "perceptual-v1", chunk_keys: 5}]}}' \
  > requests.jsonl

Use the path as the id, as here, or your own key: from id<TAB>path lines, split("\t") in jq gives both.

Comparing hashes: distance

echo '{"id": 1, "a": "perceptual-v1:c3f00f3c99a5a55a", "b": "perceptual-v1:c3f00f3c99a5a55b"}' | legit-hasher distance
{"format":1,"id":1,"line":1,"status":"success","definition":"perceptual-v1","distance":1,"bits":64}

Bit hashes give their Hamming distance and width in bits; signatures give matching values, values (128) and similarity, the estimated Jaccard similarity. id is optional and echoed. Hashes of different definitions, or a hash and a signature, give error_type: "mismatch"; a value that doesn't parse gives invalid_hash, and a line that isn't a pair invalid_request.

distance takes --input FILE and --output FILE as run does, and nothing else. Like run's, its --output refuses a file that already exists, exiting 2 without touching it. Its exit status is run's: 0 when every pair was compared, 1 when any line failed, 2 when it couldn't go on.

What info reports

legit-hasher info prints one JSON object. Shortened:

{
  "format": 1,
  "runner": {"name": "legit-hasher", "version": "0.1.4", "hashes": "0.2.1", "decoder": "image 0.25.10"},
  "definitions": [
    {"id": "pdq-v1", "input": "rgba", "bits": 256, "returns": ["value", "quality", "chunk_keys"], "parameters": ["chunk_keys"]},
    {"id": "minhash-v1", "input": "text", "values": 128, "returns": ["value", "empty", "band_keys"], "parameters": ["shingle", "tokens", "band_keys"]}
  ],
  "image_formats": ["jpeg", "png"],
  "limits": {"max_file_bytes": 67108864, "max_side": 16384, "max_decoder_bytes": 268435456, "max_metadata_bytes": 268435456, "max_pixels": null,
             "max_text_bytes": null, "max_definitions": 16, "max_options_bytes": 65536, "max_shingle": 64,
             "max_line_bytes": 8388608, "max_inline_bytes": 6291456, "worker_peak_bytes": 4102029312},
  "cpu": {"arch": "x86_64", "model": "…", "logical_cores": 32,
          "features": {"avx2": true, "avx512f": true, "avx512vpopcntdq": true, "fma": true, "popcnt": true, "sse2": true, "sse4.2": true}},
  "pdq_arithmetic": "native-f32",
  "malloc": "tuned"
}
  • format is the request and result format this runner speaks. Check it before sending work.
  • definitions lists every definition offered, with what it reads, its width, what it returns and its parameters.
  • limits are those requests are held to; --max-line-bytes, --max-pixels and --max-text-bytes given to info show their effect.
  • cpu is the machine: the architecture, the model (read on Linux, null elsewhere), the cores --jobs defaults to, and the instruction sets detected at run time, sse2, sse4.2, popcnt, fma, avx2, avx512f and avx512vpopcntdq on x86-64 and neon on aarch64.
  • malloc says how run and serve set up the memory allocator in this environment: tuned, tunables, default or system (see Memory and --jobs).
  • serve, in a build with the serve feature, names the task kind, its streams and fields, and, when --user-agent is given, the User-Agent fetches send.
  • pdq_arithmetic says how pdq-v1 computes here: native-f32 on x86-64 and aarch64, whose f32 arithmetic is IEEE-754 single precision, or software-f32, the same operations computed exactly in integers, on other targets.

Nothing detected changes a hash. The CPU is reported, never used to pick a path that rounds differently: no fused multiply-add and no reordered sums for pdq-v1, and no SIMD of the runner's own. A definition's output is the same on every machine.

Memory and --jobs

Unless one says otherwise, the measurements under this heading come from the crate's own smoke runs of December 2026, on x86-64 Linux machines with glibc, over generated and public-domain files.

Memory is bounded on any input. At most 4 × jobs + 4 requests are in flight, read and not yet written, and no line longer than --max-line-bytes (8 MiB by default) is held. In a measurement, a run of 200,000 short texts peaked at 11 MB, the same as a run of a few.

Each worker needs memory for the image it's hashing: about 14 bytes a pixel with pdq-v1 and the others together (RGBA, luma and PDQ's two f32 planes), plus the file. That's about 300 MB for a 23-megapixel photograph, measured. The decoder's limits bound the worst case: a side of at most 16,384 pixels, at most 256 MiB of decoded pixels, at most 256 MiB of metadata such as a PNG's compressed ICC profile, and a file of at most 64 MiB, so one worker never needs more than limits.worker_peak_bytes, about 3.8 GiB. --max-pixels N lowers that bound to about 14 × N bytes plus the file and 16 MiB of metadata (limits.max_metadata_bytes). limits.worker_peak_bytes also counts one request line (--max-line-bytes, 8 MiB by default), which run holds and serve doesn't read. The 16 MiB is what the decoder is allowed for metadata while the size is read, not a ceiling on all the memory that read takes: to tell that a PNG's profile was kept, the decoder hands back its own copy, so a kept profile exists twice for a moment. It refuses as too_large, before anything is decoded or allocated, an image whose header states more pixels; an image the decoder itself reads as larger than N, which is the size it would allocate for, even where a header later in the file says otherwise; a PNG whose ICC profile doesn't inflate within 16 MiB while that size is read; and an image whose header gives no size the runner can read, rather than decode it blind. After decoding it checks the decoded size again. run has no --max-pixels by default; serve has 50 million.

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, with files of up to 64 MiB, that's about 780 MB a job; for thumbnails, memory doesn't limit it.

The allocator

On 64-bit Linux with glibc, run and serve set glibc's allocator as they start, in the process, to keep freed blocks of up to 32 MiB for reuse (M_MMAP_THRESHOLD) and up to 128 MiB of free memory before returning it to the kernel (M_TRIM_THRESHOLD). glibc otherwise maps each decoded image's buffers afresh and unmaps them when they're freed, so every page of every image is faulted in again. The results are the same byte for byte. A worker keeps the blocks of up to 32 MiB it freed, instead of returning them between images; a larger block, such as the RGBA pixels of an image past about 8 megapixels, is still mapped and returned each time, so the gain measured below is on images under that size. On 32-bit glibc, whose largest M_MMAP_THRESHOLD is 512 KiB, the program leaves the allocator alone and info says system.

Measured on a 2-core x86-64 machine, run with pdq-v1 and perceptual-v1, the median of three runs each, with glibc's defaults (LEGIT_HASHER_MALLOC=default), with the same settings given to glibc through the environment (GLIBC_TUNABLES=glibc.malloc.mmap_threshold=33554432:glibc.malloc.trim_threshold=134217728), and with the program's own (no variable set):

5,000 JPEGs of about 26 KB files a second, 1 job 16 jobs kernel's share of CPU time, 1 job 16 jobs peak memory, 1 job 16 jobs
glibc's defaults 583 1,061 14.9% 18.4% 12.5 MiB 20.8 MiB
GLIBC_TUNABLES 715 1,282 1.8% 1.2% 12.5 MiB 22.0 MiB
the program's own 726 1,287 1.6% 1.4% 12.5 MiB 21.7 MiB
200 JPEGs of 1.5 megapixels files a second, 1 job 16 jobs kernel's share of CPU time, 1 job 16 jobs peak memory, 1 job 16 jobs
glibc's defaults 19.7 36.8 14.4% 16.0% 28.0 MiB 335 MiB
GLIBC_TUNABLES 25.1 42.8 0.6% 1.8% 27.9 MiB 392 MiB
the program's own 25.2 42.4 0.6% 2.1% 27.9 MiB 390 MiB

A separate run on a 16-core host agrees: 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 system time fell from about 20% of CPU to about 1% with the setting on; turning it off gave back the earlier figures, and it cost about 14 MB of resident memory at 16 jobs.

To keep glibc's own settings, set LEGIT_HASHER_MALLOC=default; to choose others, set GLIBC_TUNABLES, even to an empty value, and the program leaves the allocator alone. With musl and on other systems, 32-bit glibc included, it changes nothing. info says which is in effect: tuned, default, tunables or system. The program never starts itself again to do this.

Sizing

Per core, one decode then pdq-v1, blockhash-v1 and perceptual-v1 runs at about 420 thumbnails, 21 medium (1.5-megapixel) or 0.64 large (23-megapixel) JPEGs a second, in a measurement of legit-hashes 0.2 on photographs on an x86-64 Linux server; pdq-v1 is two thirds of the large-image cost. The runner adds little: it decodes once and hashes on every core, and throughput scales with the cores until memory or the disk limits it.

If you'll compare images stored at different sizes, reduce every image to one size, then hash. In the same measurement, two copies of a picture at different resolutions, each reduced to 500 pixels on its long side before hashing, differed by a median of 0 to 2 bits of pdq-v1 (95th percentile 4 to 8, maximum 16), with no pair past 31 bits, Meta's suggested threshold. Hashing a reduction against an original is not sound in the same way: those differed by a median of 10 bits.

Two reductions of one file are the best case. In one real collection, a person judged 82 pairs of stored images without seeing their distances. Of the 47 pairs judged to be the same picture, or an edited copy of it, held as separate copies (re-encoded, re-saved at another size, sometimes framed slightly differently), a pdq-v1 distance of 31 found about half, 64 found 41 and 80 found 45. Nothing judged different was closer than 84, though three pairs judged very similar but not the same sat between 50 and 64. The pairs were picked from candidates an older 64-bit hash had placed close together, so they are a small and selected sample: measure on your own data before choosing a threshold.

In a second review of 210 pairs chosen by pdq-v1 distance, 2 of 135 pairs at 64 bits or under were unrelated images, against 30 of 38 at 74 to 80; a distance of 31 found about half of the true matches and 64 about four fifths.

Calling it from PHP

For a batch, write the requests to a file, run the program, and read the results:

<?php
$requests = tempnam(sys_get_temp_dir(), 'hash');
$results = $requests . '.out';
$in = fopen($requests, 'w');
foreach ($images as $id => $path) {
    fwrite($in, json_encode([
        'id' => $id,
        'path' => $path,
        'options' => ['format' => 1, 'definitions' => [
            ['id' => 'pdq-v1', 'chunk_keys' => 16],
            ['id' => 'perceptual-v1', 'chunk_keys' => 5],
        ]],
    ]) . "\n");
}
fclose($in);

exec('legit-hasher run --input ' . escapeshellarg($requests) . ' --output ' . escapeshellarg($results), $_, $status);
if ($status === 2) {
    throw new RuntimeException('legit-hasher could not run the batch');
}

foreach (new SplFileObject($results) as $line) {
    if ($line === '') {
        continue;
    }
    $result = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
    if ($result['status'] !== 'success') {
        // $result['error_type'] says why...
        continue;
    }
    foreach ($result['hashes'] as $hash) {
        // Store $hash['value'], and $hash['chunk_keys'] in indexed BIGINT columns...
    }
}

For one request at a time, keep a runner open and talk to it through a pipe. Results come back in order, one line per request, and each is written as soon as it's 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);

Don't write a large batch into the pipe before reading: the runner stops reading when its output isn't read, so both sides would wait. Interleave writes and reads, or use files as above.

Running it as a worker

legit-hasher serve (built with the serve feature) is a worker on the Redis Streams work contract legit-streams states: 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. One well-resourced machine can serve many small ones, and every definition, text included, is served. A task holds the same request a line of legit-hasher run holds, and its result holds the same result object, so a caller can develop against the command line and move to the stream unchanged. serve has two limits by default that run doesn't, --max-pixels 50000000 and --max-text-bytes 1048576; give run the same to get the same answer for an image or a text past them. That holds for a request with one fault: with several, the two can report different codes, because serve checks a text's length before options and run after.

One Redis, one worker, one producer

In a first terminal, start a throwaway Redis (6.2 or newer):

docker run --rm -p 6379:6379 redis:8

In a second, start a worker:

legit-hasher serve --redis redis://127.0.0.1:6379

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

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: task_id app_1, status success, the echoed model_type, model_id, task_name and model_name, worker_id, processing_ms, and result:

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

legit-streams' producer example sends tasks of this kind from Rust too.

The task kind hash

The streams are named after the kind, hash, as the contract names them:

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

--kind changes hash to another name, such as a second deployment kept apart from the first, and --key-prefix puts a prefix before every key, as many PHP applications do on a connection; names inside entries, such as reply_to, never carry it.

A hashing task is the contract's envelope (task_id, model_type, model_id, task_name, model_name, source, v, and optionally reply_to), which the worker echoes untouched as the contract says, and these payload fields, every value a string:

Field Meaning
text_data UTF-8 text to hash, as text on the command line. An empty text_data is an empty text, which is hashed.
image_data Image bytes, standard base64, as base64 on the command line. For small images: a stream holds its tasks in memory. Empty means absent.
image_url An https URL of an image the worker fetches, or http where the worker allows it, such as a presigned URL of object storage. Refused unless the worker allows its host: see Fetching by URL. Bulk lane only.
options The request's options as JSON text, exactly as on the command line: format, definitions and orientation. Required.
id Optional: the id the result object carries, as a string. Without it, the result object's id is the task's task_id.

A task gives exactly one of text_data, image_data and image_url. model_name is empty, or legit-hasher; any other is unsupported_model, since the definitions are chosen in options. The worker ignores fields it doesn't know, as the contract says, so a misspelt field is missing rather than refused.

A distance task carries a and b, each a stored hash or signature, and an optional id, as a line of legit-hasher distance does, and no source.

The result is the contract's result envelope with one field of its own, result: the JSON object legit-hasher run writes for the same request, the same fields, names, order and values (see Results), without line; for a distance task, what legit-hasher distance writes, without line. The envelope's status is the object's status:

  • A request that succeeds is a success, even when one of its definitions failed, as on the command line: that entry of hashes carries its error_type.
  • A request that fails as a whole is an error whose error_type and error are the object's, such as decode_failed, too_large or invalid_options, a task with more than one source (no_source), or a distance task's invalid_hash or mismatch, and whose result still holds the whole object, so detected_format, source and runner reach the caller.
  • The contract's own codes stand where it names one: invalid_task for a task with no source or pair at all, half a pair, both a source and a pair, or an image on the fast lane (its result says no_source or invalid_request), unsupported_model, max_deliveries_exceeded and unsupported_version.
  • A URL source adds download_failed, url_expired and host_not_allowed, below.

worker_id is the worker's consumer name and processing_ms the time the task took. With serve --timings, the result object carries timings as run --timings writes them, a URL's fetch counted as its read_us. Results are at least once, as the contract says: a reader treats a second result for a task_id as a repeat.

The fast lane

For work a caller waits for, such as hashing a text as it's written or checking a distance while a user waits for a page, a worker also reads hash_tasks:fast with the same group, on threads of its own, so bulk work never delays it. A fast task is a text hashing task or a distance task, with the contract's two more fields: reply_to, the reply key results:{app}:hash:rpc:{task_id}, and optionally deadline_ms. The worker answers on the reply key; the caller reads it from 0, deletes it, and falls back to the bulk lane or an error on a timeout. An image, inline or by URL, gets invalid_task on the fast lane: send it to hash_tasks. --no-fast serves the bulk lane only, and --fast-jobs sets how many fast tasks run at once (2 by default).

From PHP, with plain Redis commands

No client library is needed: a producer in any language adds a task with XADD and reads its result with a consumer group. With phpredis:

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// A task id: 1 to 64 of [A-Za-z0-9_-], unique across applications. The contract recommends
// `{app}_{ULID}`; any id with enough randomness to be unguessable will do.
$taskId = 'app_' . bin2hex(random_bytes(12));

$redis->xAdd('hash_tasks', '*', [
    'task_id' => $taskId,
    'model_type' => 'photo',          // the record the hashes are for, echoed back
    'model_id' => '90211344',
    'task_name' => 'default',
    'model_name' => '',
    'source' => 'app',                // the application's name
    'v' => '1',
    'reply_to' => 'results:app:hash', // where the result goes
    'image_url' => $presignedUrl,
    'options' => json_encode(['format' => 1, 'definitions' => [
        ['id' => 'pdq-v1', 'chunk_keys' => 16],
        ['id' => 'perceptual-v1', 'chunk_keys' => 5],
    ]]),
]);

// The application reads its result stream with a group of its own; creating it again fails
// harmlessly...
$redis->xGroup('CREATE', 'results:app:hash', 'app', '0', true);
$read = $redis->xReadGroup('app', 'app-host1', ['results:app:hash' => '>'], 25, 5000);
foreach ($read['results:app:hash'] ?? [] as $entryId => $fields) {
    $result = isset($fields['result']) ? json_decode($fields['result'], true) : null;
    if ($fields['status'] === 'success') {
        foreach ($result['hashes'] as $hash) {
            // Store $hash['value'] for the record $fields['model_type'] / $fields['model_id'],
            // and $hash['chunk_keys'] in indexed BIGINT columns...
        }
    } else {
        // $fields['error_type'] says why; $result, when there is one, says what was learned...
    }
    $redis->xAck('results:app:hash', 'app', [$entryId]);
    $redis->xDel('results:app:hash', [$entryId]);
}

Field by field, a producer in any language does the same: it builds the envelope, adds one source and options (JSON text), XADDs the map to hash_tasks, and reads results:{app}:hash with XREADGROUP, decoding result as JSON and acknowledging and deleting each entry once it's handled. A reader should apply a result only to a task it sent, and handle a repeated task_id once.

A fast call, for text while a user waits:

<?php
$taskId = 'app_' . bin2hex(random_bytes(12));
$replyKey = "results:app:hash:rpc:{$taskId}";
$entryId = $redis->xAdd('hash_tasks:fast', '*', [
    'task_id' => $taskId, 'model_type' => 'query', 'model_id' => '0', 'task_name' => 'default',
    'model_name' => '', 'source' => 'app', 'v' => '1',
    'reply_to' => $replyKey,
    'deadline_ms' => (string) ((int) (microtime(true) * 1000) + 2000), // the caller waits 2 s
    'text_data' => $text,
    'options' => json_encode(['format' => 1, 'definitions' => [['id' => 'minhash-v1', 'shingle' => 5, 'band_keys' => 16]]]),
]);
$reply = $redis->xRead([$replyKey => '0'], 1, 2000);
$redis->del($replyKey);
if (!$reply) {
    $redis->xDel('hash_tasks:fast', [$entryId]); // no worker answered in time: fall back
} else {
    $fields = reset($reply[$replyKey]);
    $result = json_decode($fields['result'], true);
}

Fetching by URL

image_url is how a worker reads images held elsewhere, such as presigned URLs of object storage. A URL comes from a task, and anyone who can write to the task stream can write a task, so a worker that fetched any URL would let them use it to reach what only the worker can reach: a cloud metadata service such as 169.254.169.254, which hands out the machine's credentials, an admin port on 127.0.0.1, or another service on its network. This is server-side request forgery. The worker guards against it, and its HTTP client is pinned to the exact release (ureq 3.5.2) these guarantees were checked against:

  • An allowlist of hosts is required. With no --allow-host and no --allow-hosts-file, every image_url is refused with host_not_allowed. An entry is a name, every name under one (*.example.com, which doesn't match example.com itself), an IPv4 address in dotted decimal or an IPv6 address, and optionally a port: images.example.com:8443, [2001:db8::1]:8443. The file lists one a line; blank lines and # comments are skipped. Entries are read strictly: no empty label, at most one final dot, brackets only around an IPv6 address, no zone such as %eth0, no name whose last label is a number (127.1, 2130706433 and 0x7f.1 are addresses in other spellings), and a port from 1 to 65535. Names compare without case; addresses compare as addresses, so two spellings of one IPv6 address match. List the ASCII form of an international name (xn--…).
  • One port per entry. An entry without a port allows only the default port of the URL's scheme, 443 for an https URL, and 80 for an http URL when --allow-http is set. A URL or a redirect to any other port of an allowed host is host_not_allowed; list host:port to allow it. A URL's port that isn't 1 to 65535, an empty one included, is refused, never read as the default.
  • Public addresses only. The worker resolves the name itself and connects only to ordinary public unicast addresses, unless an --allow-range (a CIDR range or a single address, repeatable) holds the address. Refused by default, from the IANA special-purpose registries: loopback, link-local (169.254.0.0/16, fe80::/10), unspecified and 0.0.0.0/8, multicast, broadcast, private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), shared (100.64.0.0/10), 192.0.0.0/24, documentation, benchmarking, 6to4 relay anycast (192.88.99.0/24) and reserved (240.0.0.0/4) IPv4; unique local (fc00::/7), site-local (fec0::/10), documentation (2001:db8::/32, 3fff::/20) and discard-only IPv6; and every IPv6 form that carries an IPv4 address or leads through a translator or a tunnel: IPv4-compatible (::/96), NAT64 (64:ff9b::/96, 64:ff9b:1::/48), 6to4 (2002::/16), Teredo (2001::/32, with the rest of 2001::/23) and anything outside 2000::/3. An IPv4-mapped address (::ffff:a.b.c.d) is checked as its IPv4 address. The blocks the registries mark globally reachable, routed like any public address, are left reachable: 192.31.196.0/24, 192.175.48.0/24 and 2620:4f:8000::/48 (AS112) and 192.52.193.0/24 (AMT). Object storage on a private network is --allow-range 10.0.0.0/8 plus its host; on the same machine, --allow-range 127.0.0.0/8.
  • What a resolver answers is checked before connecting. ureq's resolver hands the worker at most 16 addresses of a longer answer, and the worker connects only to addresses it checked: every address the worker may connect to is checked, and one refused address among them refuses the fetch. So an allowed name can't be pointed at one of those ranges, by a changed DNS record or otherwise.
  • Connections are reused, and every request is checked all the same. A connection whose response was read to its end stays open for the next fetch from the same scheme, host and port (and user, over https); a worker keeps up to one idle connection a --jobs, each for --idle-timeout seconds (60), and closes them all once it has fetched nothing for that long. Before every request, on a reused connection too, the URL passes the checks of scheme, user, host and port, and its host is resolved and its addresses checked again: a URL refused now is refused, whatever connection is idle. A reused connection keeps the address it was opened to, which was checked when it was opened, so a change of the host's DNS records is seen at the next new connection, not at once. A connection carries nothing from one task to the next but its socket and its TLS session: no header, cookie or credential. A redirect's connection is always closed, with a body or none. A refused status or a body over the cap closes its connection when a body is left unread; a refused status with no body, such as a 403 or 500 with Content-Length: 0, is handed back to the client's pool before the worker sees it, and its connection stays open for reuse like any other.
  • Every checked address is tried before a connect fails, and a failed connect is tried once more. The worker connects to the addresses the host resolved to, in the resolver's order, each given an equal share of what is left of --connect-timeout, so an address that fails at once, such as an IPv6 address on a host with no IPv6 route, leaves its time to the next. When none connects, a failure of any kind comes before the request was written, or the connection is reset or closed before any byte of a reply, the request is tried again after 200 ms on a new resolution, checked again, --connect-retries times (1; 0 turns it off). Never after a byte of a reply, an HTTP status among them, and never past --fetch-timeout. The message of a final failure counts the connects, addresses and attempts and gives each reason, such as connection refused, network unreachable, without naming an address.
  • The worker judges an address, not the network's routing. A VPN, a NAT64 or other translator prefix of your network's own, or a tunnel can carry an ordinary public address somewhere private. Fence the worker at the network's edge too: let it reach the storage it needs and nothing else.
  • No redirects by default. A redirect is download_failed. --max-redirects N follows up to N, and every hop passes the same checks of scheme, user, host, port and address as the first URL. The worker follows them itself and closes each redirect's connection without reading its body, so a redirect's body never counts against the time or the cap.
  • HTTPS only, unless --allow-http allows plain http, for a private network. A URL with a user or password is refused over plain http, which would send them in the clear; over https they go to that URL's own host only.
  • Limits. The body returned is held to --max-fetch-bytes (at most and by default 64 MiB, the decoder's input limit): too_large, refused from its Content-Length or as soon as the bytes read pass it, never held past it. The cap is on the body returned: each response's headers, what the TLS and socket layers read ahead, and the one byte read past the cap to find a body too long are outside it, and --fetch-timeout bounds them. --connect-timeout (10 s) bounds connecting and --fetch-timeout (60 s) the whole fetch, redirects and body included.
  • No credential is sent but what the URL carries: no proxy from the environment, no Authorization but from the URL's own user and password. As this crate's own manifest builds ureq, it keeps no cookies and asks for no compression. A program that builds this library with ureq's cookies feature turned on elsewhere in its dependencies changes that: ureq then keeps the cookies a server sets and sends them on later fetches, across tasks, and has no setting to turn that off. The legit-hasher program has no such feature.
  • --user-agent TEXT sets the User-Agent fetches send, legit-hasher/ and the version by default, for storage that refuses or slows clients that don't name themselves. Printable ASCII only.

What a result and a log line hold: a URL's query string, user and password are never in a result or a log line, any of which may be a signed credential; ids, paths, the host, the model fields and the values of options that were refused are. A result names a URL by its scheme, host, port and path, and the worker's log line for a failed fetch names the stream entry, the code and the host. So don't put a secret in a path, an id or a model field. The HTTP client's own log records, which name whole URLs at debug, are never written: serve installs no bridge from the log crate.

A fetch's failure is one of these codes:

Code Meaning
host_not_allowed The scheme, a user or password over http, the host, the port or an address it resolves to is refused, at the start or on a redirect. A setting of the worker, so the same task fails again: fix the allowlist or the URL.
url_expired The server answered 401 or 403: a presigned URL that has expired, or one that was never valid. Send a fresh URL. For a URL with no signature it means the object is gone or not public, and sending the same URL again will fail the same way.
download_failed No such host, no connection, a timeout, a redirect not followed or one too many, another status that isn't 2xx, or a body cut short. A failure before any request was written is retried once first, whatever its kind.
too_large The body is over --max-fetch-bytes.
invalid_request The value isn't an absolute URL.

What a caller should send again: a download_failed task, a bounded number of times, with a pause, since the worker has already tried its connect once more. url_expired and host_not_allowed are final for the task as sent: send a fresh URL for the first, and nothing until the allowlist or the URL changes for the second.

Give every worker on a group the same allowlist: any worker may take any task.

Sizing a worker

--jobs sets the bulk tasks run at once, one thread each, by default the available cores. Each one in flight holds its source, up to --max-fetch-bytes for a URL or the decoded image_data, plus about 14 bytes a pixel while it hashes (see Memory and --jobs); a text task holds its text, at most --max-text-bytes (1 MiB), and little more. With the default --max-pixels of 50 million, one image task can need about 780 MB (14 × 50,000,000 bytes, plus a file of up to 64 MiB, plus 16 MiB of metadata), so the worst case is --jobs times that, plus the fast lane's --fast-jobs text tasks.

The default job count follows the CPUs, not the memory. Set --jobs, --max-pixels and a memory limit on the process together, so that jobs × (file + 16 MiB + 14 × max-pixels) fits under the limit (info --max-pixels N reports one job's bound as limits.worker_peak_bytes, which also counts one request line, --max-line-bytes, 8 MiB by default, that serve doesn't read): on an 8-core machine with 4 GB for the worker, about 3.1 GB at --jobs 4 --max-pixels 50000000, or about 3.5 GB at --jobs 8 --max-pixels 25000000.

With image_url the time is the fetch, not the hash (about 3 ms for an image of this size), so the right --jobs is several times the cores, within the memory bound. In one run on a 16-core host, for cached objects of about 29 KB: about 200 tasks a second at --jobs 8 and 600 to 900 at --jobs 64; --jobs 128 gave fewer, with the time per task more than doubled, so something beyond the worker saturates near there. A first fetch of an object the store had not cached took about 230 ms, which bounds a rebuild at about jobs / 0.23 tasks a second: a rebuild is all first fetches. Measure against your own store before choosing.

A worker keeps a connection a job open, which takes the connect, and over https the TLS handshake, out of each fetch's time. In that run a worker at --jobs 64 opened about 60 connections for 5,000 fetches and reused them for the rest. An earlier build that opened a connection for almost every fetch failed about 1% of them at that rate with a connect error; the reusing build failed one fetch in 30,000, with a different error that is now retried. On the test smoke (3,000 tasks by image_url through a Redis 8 server, from a plain http server on the same 2-core machine, images of about 27 KB), the connections the worker opened went from 229 to 7 at --jobs 8 and from 559 to 59 at --jobs 64, and its throughput from 2,359 to 2,569 and from 2,053 to 2,367 tasks a second. Over a network each connection saved is a round trip, and over https a TLS handshake too, so the gain there is larger than on one machine. The heartbeat's connections_opened and connections_reused show how a worker is doing: opened should stay near --jobs for each host it fetches from.

These limits bound one task; none is a quota. Anyone who can add to hash_tasks can fill the worker with tasks at the limits, one after another. The Redis server's access rules, which clients may write the task streams, are the control on who may enqueue; give producers an account of their own, and the workers one that reads tasks and writes results.

Throughput is what Sizing gives per core, less the time to fetch: place workers where the images are cheap to fetch.

Running it under a supervisor

serve runs until it gets SIGTERM or SIGINT. Then it takes no new task, and releases at once, so another worker claims them, the tasks it holds whose fetch hasn't begun. A task whose fetch has begun, or that has nothing to fetch, gets --shutdown-grace (30 s) to finish and is answered by this worker; what still runs when the grace ends is released too. It answers the fast tasks it has read, and exits 0. A second signal ends it at once, with exit status 1, and its tasks are claimed by other workers after the contract's 300 s. It exits 2 when it can't run: a mistaken flag, or a Redis it can't reach at the start. Once running, a failed command is logged and tried again, never fatal.

Standard error carries JSON lines: the log lines of the worker and of legit-streams, which never hold a payload, and a heartbeat every --heartbeat seconds (30):

{"timestamp":"…","level":"INFO","message":"Heartbeat","state":"running","consumer":"legit-hasher-host1_4242","uptime_s":600,"in_flight":7,"done":81211,"failed":12,"fast_done":930,"fast_failed":0,"fetched":81190,"fetched_bytes":2377120055,"connections_opened":9,"connections_reused":81181,"connect_retries":3,"target":"legit_hasher::serve_command"}

in_flight is the bulk tasks running, done and failed the bulk tasks answered and those that failed, and fast_done and fast_failed the same on the fast lane; fetched and fetched_bytes count the URLs fetched; connections_opened the connections opened to fetch them, TLS included, connections_reused the requests written to a connection an earlier fetch had opened, and connect_retries the requests tried again after a failure at the connect level. With --events-socket, the line has two more, events_sent and events_dropped: the events socket's datagrams sent and dropped since the start.

Stats file

--stats-file PATH writes what the worker has done to PATH as one JSON document: once when the worker has started, at every heartbeat, and once after the workers have stopped. The heartbeat line is for people reading the log; the file is the place for a collector beside the worker to read, such as a metrics agent or a status page, without parsing the log. Without the flag nothing is written.

{"format":1,"program":"legit-hasher","version":"0.1.4","state":"running","at":1796245000,"started_at":1796200000,"interval_s":30.0,"jobs":64,"in_flight":7,"bulk":{"answered":81211,"failed":12,"rate_per_s":271.3,"median_ms":71.0,"p95_ms":240.0},"fast":{"answered":930,"failed":0,"rate_per_s":0.4,"median_ms":0.3,"p95_ms":0.9},"fetch":{"fetched":81190,"fetched_bytes":2377120055,"connections_opened":9,"connections_reused":81181,"connect_retries":3},"definitions":{"pdq-v1":81199,"perceptual-v1":81199},"backlog":{"waiting":1203,"pending":64}}

Every count is since the worker started.

Field What it is
format The document's version, 1. A change that isn't only a new field raises it.
program, version legit-hasher and its release.
state running, or stopped in the last document.
at, started_at When the document was written and when the worker started, in Unix seconds.
interval_s The seconds the rates and times cover: the time since the previous document. null in the first.
jobs Bulk tasks run at once, --jobs.
in_flight Bulk tasks running now.
bulk, fast Each lane's tasks; fast is null when the worker serves no fast lane (--no-fast).
….answered, ….failed Tasks answered, and of those the ones that failed, as the heartbeat's done and failed, fast_done and fast_failed. A failed task is an answered one too: failed is part of answered, not beside it.
….rate_per_s Tasks answered in the interval over its length.
….median_ms, ….p95_ms The median and 95th percentile of the time the worker spent on each task answered in the interval, as its result's processing_ms reports it in whole milliseconds, read here to the microsecond. Both are accurate to within 10%: they come from fixed buckets, none wider than 10% of its lower bound, from 0.01 ms to 10 minutes. null when no task was answered in the interval.
fetch The heartbeat's fetched, fetched_bytes, connections_opened, connections_reused and connect_retries.
definitions For each definition, how many values it has computed without an error, both lanes together. A definition no task has asked for is absent; one asked for that has only failed, or only in tasks that failed before hashing, such as on a fetch or a decode, is 0.
backlog The bulk task stream's group, as XINFO GROUPS reports it: waiting, the tasks not yet delivered to any worker, and pending, those delivered and not yet answered, by every worker of the group. Read once a document, on a connection of its own and never one a task uses, for at most 2 s; null when it couldn't be read, and waiting alone is null when the server doesn't report it (before Redis 7.0, or after tasks were deleted unread).

rate_per_s, median_ms and p95_ms are null in the first document. The file never holds a stream, group, consumer, key prefix, host or application name, a URL or an address, an error's text, a hash, a model_type or an allowlist entry: numbers only, apart from program, version, state and the definitions' ids. Reading the backlog needs xinfo on the task stream for the worker's Redis user.

Each write is whole: the document goes to PATH with .tmp added, in the same directory, and is renamed over PATH, so a reader never sees half of one. The file has mode 0644. A write that fails, and a backlog that can't be read, is logged at warning level when it's the first failure since a success or its kind differs from the last one's, and never stops or slows the worker; the next heartbeat tries again. A failed write leaves the file as it was, and the next document written covers the interval since the one in the file, its rates and times included; until a first document is written, the next is a first document. A PATH whose directory doesn't exist stops serve at the start with exit status 2, as a mistaken flag does; under systemd, RuntimeDirectory=legit-hasher and --stats-file /run/legit-hasher/stats.json give it one.

The consumer name is --consumer (by default legit-hasher- and the host name) and the process id, and -fast before the id on the fast lane, so a restarted worker is a new consumer. Give the Redis URL in LEGIT_HASHER_REDIS_URL rather than --redis when it holds a password, so it isn't on the command line. A systemd unit:

[Unit]
Description=legit-hasher worker
After=network-online.target
Wants=network-online.target

[Service]
EnvironmentFile=/etc/legit-hasher/env
ExecStart=/usr/local/bin/legit-hasher serve --jobs 4 --max-pixels 50000000 --allow-hosts-file /etc/legit-hasher/hosts
# Four jobs at 50 million pixels need about 3.1 GB; the limit stops the worker past that...
MemoryMax=4G
# glibc's own allocator settings rather than the program's, if you prefer memory to speed:
# Environment=LEGIT_HASHER_MALLOC=default
KillSignal=SIGTERM
# The shutdown grace, plus a read in progress, plus a margin...
TimeoutStopSec=45
Restart=on-failure
RestartSec=5
DynamicUser=yes
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target

/etc/legit-hasher/env holds LEGIT_HASHER_REDIS_URL=redis://:<password>@<host>:6379, readable by root only. The worker needs no privilege: never install it setuid or with file capabilities.

Events file

The stats file gives totals and rates. --events-file PATH gives each task, as it is answered: every --events-interval seconds (1) in which at least one task was answered, the worker replaces PATH with one JSON document holding exactly the tasks answered since the previous document, four numbers each, for a collector that shows them one by one, such as a live display or a scatter of times. The log has no line per task, and gets none. Without the flag nothing is written and nothing is recorded.

{"format":1,"program":"legit-hasher","version":"0.1.4","state":"running","started_at":1796250904,"seq":812,"from_ms":1796251199121,"at_ms":1796251200123,"count":3,"dropped":0,"records":[[3,0,1,229104],[9,0,1,231877],[11,1,1,412]]}
Field What it is
format The document's version, 1. A change that isn't only a new field raises it.
program, version legit-hasher and its release.
state running, or stopped in the last document.
started_at When the worker started, in Unix seconds: the stats file's started_at.
seq 1 for the first document the process writes, one more for each written after it; a write that fails takes no number.
from_ms, at_ms The interval the document covers, in Unix milliseconds: from_ms is the previous document's at_ms, or when the worker started for the first.
count The number of records.
dropped Tasks answered in the interval, or in an earlier one whose write failed, that aren't in records: past --events-max in one interval, or in a document that couldn't be written.
records The tasks answered in the interval, in the order they were answered, each an array of four whole numbers, described below.

Each record is, in order:

  1. the milliseconds after from_ms at which the task was answered, from 0 to the interval's length. The wall clock is read once a document and the offsets measured on the monotonic clock, so a step of the wall clock can't make one negative or put them out of order;
  2. the lane: 0 bulk, 1 fast;
  3. the outcome: 1 answered without a failure, 0 failed, exactly as the stats file counts failed: an error, or a result with a failed definition;
  4. the microseconds the worker spent on the task, on the clock the result's processing_ms and the stats file's times are read from.

The file never holds a task id or entry id, a model_type, model_id or model_name, a source, a URL or an address, a host, stream, group, consumer, key prefix or application name, an error's type or text, a definition's id, an image's dimensions, a byte count, a hash or an allowlist entry: what the worker keeps for it is the four numbers of each task, and nothing else.

The document holds only the tasks answered since the previous one, and replaces it. A reader that reads less often than the worker writes misses documents, and sees it as a gap in seq; a restart shows as a new started_at or a seq that goes back. Nothing is kept for a reader, by design: the file can't fill a disk, and a reader that is slow or absent can't slow a task. Read it at least twice an interval, and skip a seq already seen.

An interval in which no task was answered writes nothing. One document is written once the worker has started, with no record, and one last one after the workers have stopped, with "state": "stopped" and whatever was answered since the one before. A task is recorded in a buffer of at most --events-max records (10,000; from 1 to 100,000), sized once at the start; the tasks past it in one interval are counted in dropped. Recording takes one short lock, held to add a record or a count and never while the file is written, and allocates nothing; a thread of the worker's own writes the file, never one a task runs on.

Each write is whole, as the stats file's: to PATH with .tmp added, in the same directory, then renamed over PATH; mode 0644; the temporary file is removed when a write fails. A failed write is logged at warning level the first time and again only when its error's kind changes, never stops or slows the worker, and drops its interval's records, which the next document counts in dropped: the file never carries a backlog. A PATH whose directory doesn't exist, or that names a directory, stops serve at the start with exit status 2, as does the same PATH for both files, either file named as the other's .tmp, --events-interval outside 0.2 to 60 seconds, or --events-interval or --events-max without --events-file.

A record for each task shows when work happens, which totals don't: whether the file may leave the machine is for its operator to decide. Under systemd, put it in the unit's runtime directory beside the stats file: RuntimeDirectory=legit-hasher with --stats-file /run/legit-hasher/stats.json --events-file /run/legit-hasher/events.json.

Events socket

The events file gives a collector the tasks of the last interval, once an interval, and only once they're answered. --events-socket PATH gives it each event as it happens: the worker sends one datagram to a Unix socket at PATH when a task reaches its handler (a start) and one when its reply is ready (a finish), on both lanes, for a display that draws each task the moment it starts and the moment it ends. It is off by default; with it, nothing leaves the machine, as only a reader on the same host can bind a Unix socket.

{"v":1,"w":1796250904,"seq":48211,"e":0,"t":1796251199121337,"lane":0,"slot":17,"kind":1}
{"v":1,"w":1796250904,"seq":48260,"e":1,"t":1796251199350441,"lane":0,"slot":17,"kind":1,"ok":1,"us":229104}

Each datagram is one JSON object, UTF-8, with no newline and at most 200 bytes, of whole numbers under fixed keys:

Key What it is
v The datagram's version, 1.
w When the worker started, in Unix seconds: the stats and events files' started_at.
seq 1 for the process's first event, one more for each after it, starts and finishes together, whether or not the datagram could be sent: a dropped event shows as a gap. With w, a reader tells a restart from a gap.
e 0 a start, 1 a finish.
t When it happened, in Unix microseconds. The wall clock is read once, when the worker starts, and the monotonic clock's time since added to it, so times never go back and a start is never after its own finish.
lane 0 bulk, 1 fast.
slot The task's slot on its lane: the lowest number from 0 that no other running task of the lane holds, taken at the start and freed at the finish, and the same in both. With --jobs 64 the bulk lane's slots are 0 to 63, and no two running tasks ever hold one, so a display can draw a slot as a row.
kind What the task asks to be hashed, from its payload field alone: 1 an image (image_data or image_url), 2 a text (text_data), 0 anything else, such as a distance task or a payload that can't be told.
ok On a finish only: 1 answered without a failure, 0 failed, exactly as the stats file counts failed.
us On a finish only: the microseconds the worker spent on the task, on the clock the result's processing_ms and the events file read.

A datagram never holds a task id or entry id, a model_type, model_id or model_name, a source, a URL or an address, a host, stream, group, consumer, key prefix or application name, an error's type or text, a definition's id, an image's dimensions, a byte count, a hash, an allowlist entry, a process id or a thread id: the event the worker builds holds the numbers above, and nothing else.

The collector owns the socket: it binds a datagram socket (SOCK_DGRAM) at PATH and reads. The worker only sends to PATH, from an unbound, non-blocking socket it opens at the start, and never creates, binds, changes or removes anything there. Nothing is queued for a reader: when nothing is bound at PATH, the reader has gone, or its queue is full, the datagram is dropped, counted in the heartbeat's events_dropped, and seq shows it; the task isn't delayed, the send isn't tried again, and nothing is logged for it. The collector may restart at any time, and the worker follows: it holds no connection, but addresses PATH afresh on every send, so once a restarted collector has removed its old socket and bound a new one at PATH, the next event reaches it, with no restart of the worker. Any other failure, such as a permission refused, drops the datagram too, and is logged at warning level the first time and again only when its error's kind changes. Each send is one system call on the task's own thread, under one short lock that also numbers the event, reads its time and takes its slot, so datagrams are sent in seq order and a socket delivers them in that order: a reader sees seq strictly rising and t never going back, and a gap in seq always means a drop, never a datagram still to come. Nothing is allocated.

Read as fast as datagrams come. On Linux a datagram socket queues at most net.unix.max_dgram_qlen of them (10 by default); a reader that does nothing but read keeps up with a busy worker, and raising the setting absorbs a pause. A reader in Python:

import json, os, socket

path = "/run/legit-hasher-events/events.sock"
if os.path.exists(path):
    os.unlink(path)
reader = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
reader.bind(path)
while True:
    event = json.loads(reader.recv(256))
    print(event["seq"], "finish" if event["e"] else "start", event["lane"], event["slot"])

The socket and the events file answer different readers, and can run together, as can either with the stats file. The socket gives each event as it happens, starts as well as finishes, to a reader that keeps up; the file gives one document an interval of the tasks answered in it, which a simple reader can poll and a slow one can't lose track of. An event for each task shows when work happens, which totals don't: whether what the collector receives may leave the machine is for its operator to decide.

Under systemd, let the collector's own unit make the directory: RuntimeDirectory=legit-hasher-events with RuntimeDirectoryMode=0750 and UMask=0007, run as the collector's user and a group the worker's user is in, so the worker can reach and write to the socket and nobody else can. What arrives is read only by the process that bound the socket. Then give the worker --events-socket /run/legit-hasher-events/events.sock. The flag is for Unix only, a usage error elsewhere; a PATH longer than a socket address holds (107 bytes on Linux), or the same as the stats file's or the events file's, or either's .tmp, stops serve at the start with exit status 2.

What a control plane still does

A worker only keeps its own tasks claimable. Something else, an operator or a separate control plane, has to:

  • Start and stop machines by demand: the depth of hash_tasks (XLEN) and its pending list (XPENDING hash_tasks hash_workers), against the throughput each worker reports. Leave the fast lane out of that measure: a fast backlog means its workers are down, not that more bulk capacity is needed.
  • Watch the fast lane: alert when hash_tasks:fast holds entries and no fast consumer has read for a while, and delete fast entries older than 120 s, pending or not, without sending them again.
  • Set aside tasks that keep failing: a task delivered more than three times is answered with max_deliveries_exceeded and removed. The application decides whether to send it again; moving it to dead:hash_tasks first is the operator's choice. host_not_allowed is a setting, not a passing failure: it repeats until the allowlist or the URL changes.
  • Remove consumers of dead workers from the group once they own nothing, and keep the group's settings the same on every worker: the claim threshold (300 s), the lease renewal (60 s) and the delivery limit (3) are the contract's defaults, which serve uses.
  • Bound the streams: Producer in legit-streams refuses to send past a target depth; image_data makes a stream's depth its memory, so prefer image_url for anything but small images, and trim result streams nobody reads.

The formats are versioned

Other systems are built against these formats, so they're versioned: FORMAT, now 1, is in every result line, in info, and required in every request's options. A runner refuses a request for a version it doesn't speak.

These are breaking changes, which would come with format 2: 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 for the same input. A definition's output never changes in any case: a new definition, such as a pdq-v2, if one is ever defined, is added beside the old.

These are not breaking, and can come in any release: a new definition id, a new optional request field or parameter (refused by older runners, so a client knows), a new result field, a new detected_format name, a new info field, and a clearer error message. Match on error_type, never on error. Ignore result fields you don't know.

As a library

The program is a thin shell around the library, which a Rust program can call directly:

use legit_hasher::{Request, Settings, Status, hash};

let line = br#"{"id": 7, "text": "The quick brown fox",
    "options": {"format": 1, "definitions": [{"id": "simhash-v1", "tokens": "words", "chunk_keys": 4}]}}"#;
let request = Request::from_json(line).map_err(|outcome| outcome.to_json())?;
let outcome = hash(&request, Settings::default());
assert_eq!(outcome.status, Status::Success);
println!("{}", outcome.to_json());
# Ok::<(), String>(())

run drives a batch over any reader and writer, and Finished::load reads an output to resume. distances backs the distance command, over any reader and writer, and compare compares one line of it; Info::detect backs info. With the serve feature, serve::Server runs the worker on any legit_streams::Streams, the in-memory double included, and serve::Fetcher is the URL client with its FetchPolicy, whose check_url says whether a URL would be fetched, without fetching it: it checks the scheme, a user or password over plain http, the host and the port. The addresses a host resolves to are checked only when it's fetched. serve::StatsFile and serve::EventsFile write the two files, and serve::Server::start_with_events starts a server that records each answered task for the second.

Testing

cargo test -p legit-hasher

The tests run the built program. A golden request file covers every definition, the path, text and base64 sources and every request and definition error code run gives but internal, and its results are compared byte for byte with a committed file; each hash in that file is checked against what legit-hashes returns for the same input. The image_url source and the fetch codes are serve's, and its tests below cover them; the distance codes are its own tests'; internal is a unit test of the batch runner, a panic inside one request from a stand-in hasher, which every other request outlives. Other tests check that one job and eight give the same output and that unordered output holds the same lines; that a run cut at any point, mid-line included, resumes to exactly the full output; malformed and oversized lines, an empty input, a file that vanishes between listing and reading, and a million short requests in bounded memory; every EXIF orientation against the image crate's own rotations; cut JPEGs; an existing --output left untouched; and that info lists every definition legit-hashes exports; and that --help or -h after each command prints the help and exits 0. Every image the tests use is generated or tiny, and made by the tests themselves.

cargo test builds the crate with serve too. Its tests run the worker on legit-streams' in-memory double: every golden request, as text, inline bytes and a URL, gives through the worker the result object run gives, field for field; errors become the contract's error results; a task whose worker died is claimed and run by another, and one delivered past the limit is answered max_deliveries_exceeded; a stop releases the task still running; the fast lane hashes text, compares pairs and refuses images; and both lanes hold the text, options and definition limits. The address check is tested against a table of every refused range and its neighbours, and the allowlist against strict and tricky spellings, with no connection made. Fetching runs against an HTTP server on 127.0.0.1 the tests start: the size cap, from the length and while streaming; timeouts; redirects off by default, followed when allowed, and a redirect's body left unread; a host off the allowlist, another port of an allowed host, and a user over plain http, directly and through a redirect; an allowed name that resolves to loopback, refused before connecting; the User-Agent; and a query string and a password in the URL, found in no log line and no result field. The test server can keep connections open and count them, and speaks plain http only: 200 fetches in a row use one connection, 8 threads making 400 fetches at most 8, a worker with 8 jobs counts in its heartbeat what it opened and reused, a connection idle past --idle-timeout isn't reused and is closed, a redirect's connection, with a body or none, is closed and never reused, a pooled connection serves only its own host and port, every request is checked before it's written while a connection is idle, and no cookie reaches the next fetch. With a resolver the tests script, every checked address is tried in order, many fetches at once fall through an unreachable first address, a final connect failure counts its connects, addresses and attempts and names no address, and a failed connect is tried once more on a new resolution checked again, but never after a byte of a reply, for a status or past the deadline. A stop lets a fetch already begun finish within the grace and answers its task, releases at once a task that reaches the worker after the stop, and releases a task that outlasts the grace. The stats file is read as a collector would: the first document's nulls, a median and 95th percentile within 10% of the processing_ms of tasks that waited known, spread times for their images, failures counted as answered too, each definition's values with one failing on one task, the backlog of tasks added, delivered and acknowledged on the double and null when it can't be read, no temporary file left behind even when a write fails, a failed write leaving the next document a first one or measured from the last one written, a reader looping on the file while it's rewritten 1,000 times never reading part of a document, and none of the names, addresses, error texts, hashes or model types a worker given distinctive ones handled in the file. The events file is driven the same way, a write at a time: the first document numbered 1 and empty and the last stopped, each task's lane, outcome and time against its result's processing_ms in the order answered, failures as the stats file counts them and the documents adding up to its counts, nothing written and no number taken for an interval with no task, --events-max 5 keeping 5 of 12 and counting 7 dropped, a failed write leaving no file behind and its records counted as dropped in the next, a reader looping on 1,000 rewrites, none of a worker's distinctive ids, names, sources, URLs, definitions or errors in any document, the flags' mistakes, and no buffer at all without the flag. The events socket is read by a socket each test binds, in batches whose datagrams fit the kernel's queue: every task one start and one finish, numbered without a gap, the finish's time matched to the result's processing_ms; four jobs held open by their fetch holding slots 0 to 3, a fifth task taking the slot the first freed, and no slot started twice before its finish over 300 tasks on both lanes; each kind; failures finishing with ok 0 and the finishes adding up to the stats file's counts; a handler that panics, through the crate's own test build, finishing failed and freeing its slot; no reader, a reader binding later and one binding again, with nothing created at the path; a reader that never reads while 3,000 tasks run; the same distinctive values as the files', in no datagram; and the flags' mistakes. For https, reuse rests on ureq's pool, which keys a connection by scheme, host, port and user, and takes back only one whose response was read to its end. No test reaches another machine.

Changes

0.1.4

serve --events-socket PATH: a datagram on a local Unix socket when a task starts and when it is answered, for a collector that shows each as it happens; see Events socket. And --help or -h after a command (run, distance, info, serve) prints the help to standard output and exits 0, where it was refused as an unknown option. Nothing else changes.

0.1.3

serve --events-file PATH: the tasks answered in the last interval, four numbers each, for a collector that shows them one by one; see Events file. Nothing else changes.

0.1.2

Documentation only: the crate's homepage, and a rustdoc example made deterministic. No behaviour changed.

0.1.1

serve --stats-file PATH: a JSON document of what the worker has done, rewritten whole at every heartbeat, for a collector to read; see Stats file. Built on legit-streams 0.1.1, for its Streams::group_backlog. Nothing else changes: no task or result field, error code, default, existing flag or hash value.

0.1.0

The first release: run, distance and info over JSON lines, and with the serve feature a worker on the Redis Streams contract of legit-streams 0.1, with image_url fetching closed by default as Security lists.

License

MIT. See LICENSE.md.