Metadata-Version: 2.4
Name: snarlik
Version: 0.2.0
Summary: Every pair of near-identical strings, with the scores PostgreSQL's pg_trgm gives
Author: Jan K. Griffioen-Järfalk
License-Expression: MIT
License-File: LICENSE
Project-URL: Homepage, https://github.com/u840903/snarlik
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# snarlik

[![CI](https://github.com/u840903/snarlik/actions/workflows/ci.yml/badge.svg)](https://github.com/u840903/snarlik/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Find every pair of near-identical strings in a list, with the same scores
PostgreSQL's `pg_trgm` gives, without the database. Written in Zig.

```sh
$ printf '1\tThe Daily\n2\tthe daily!\n3\tDaily Show\n' | snarlik -t 0.85
1	2	1
```

*Snarlik* is Swedish for "so alike you could mix them up".

- **Same answers as Postgres.** A pair comes out exactly when
  `a % b` would match it under `pg_trgm.similarity_threshold`, with the score
  `similarity(a, b)` returns, down to the last digit
  ([how](#matching-postgres)).
- **Fast.** On 145,785 podcast names it finds the 3,227 pairs at 0.85 in
  0.11 seconds,
  where Postgres's self-join takes 14 seconds on eight cores and 106 on one ([benchmark](#benchmark)).
- **One binary.** No database, no index to build, no runtime. Rows in,
  pairs out.

It's the candidate step of deduplication and record linkage: it finds the
pairs worth a closer look, and you decide what to do with them.

## Install

From PyPI, for the CLI and the [Python module](#from-python):

```sh
pip install snarlik      # or: uv add snarlik
```

Or download a binary for Linux, macOS or Windows from the
[releases](https://github.com/u840903/snarlik/releases), or build from
source with [Zig](https://ziglang.org/download/) 0.17.1:

```sh
git clone https://github.com/u840903/snarlik
cd snarlik
zig build -Doptimize=ReleaseFast   # → zig-out/bin/snarlik
```

## Use

```
snarlik [-t THRESHOLD] [-j THREADS] [-v] [FILE]
```

Input (FILE or stdin) is PostgreSQL `COPY` text format, one row per line:
`id<TAB>text` in every row, or only `text` in every row, in which case the
id is the row number. Rows with a NULL (`\N`) are skipped. Ids are printed
back exactly as they were written. Output is one pair per line,
`id_a<TAB>id_b<TAB>similarity`, in no particular order.

| Option | |
|---|---|
| `-t`, `--threshold` | Lowest similarity to report, in (0, 1]. Default 0.3, `pg_trgm`'s own default. |
| `-j`, `--threads` | Threads to use, at most one per CPU. Default: one per CPU. |
| `-v`, `--verbose` | Print counts to stderr. |

Straight from a database:

```sh
psql -c "\copy (SELECT id, name FROM podcasts) TO 'names.tsv'"
snarlik -t 0.85 names.tsv > pairs.tsv
```

### From Python

The wheel bundles the binary, and the `snarlik` module runs it:

```python
import snarlik

names = ["The Daily", "the daily!", "Daily Show", None]
snarlik.self_join(names, threshold=0.85)   # [(0, 1, 1.0)]
```

`self_join(texts, threshold=0.3, threads=None)` returns `(i, j, similarity)`
for every pair, with `i < j` indexes into `texts`; `None` is skipped like a
NULL. `snarlik.find_snarlik_bin()` gives the binary's path, to run it
yourself.

### As a Zig library

```sh
zig fetch --save git+https://github.com/u840903/snarlik
```

```zig
const snarlik = @import("snarlik");

const pairs = try snarlik.selfJoin(gpa, texts, .{ .threshold = 0.85 }, null);
defer gpa.free(pairs);
for (pairs) |p| std.debug.print("{s} ~ {s}: {d}\n", .{ texts[p.a], texts[p.b], p.similarity });
```

`selfJoin` uses `gpa` from several threads, so it must be thread-safe, as
Zig's `DebugAllocator`, `smp_allocator` and `c_allocator` are. Set
`.threads = 1` to stay on the calling thread.
`snarlik.similarity(gpa, a, b)` scores a single pair, like Postgres's
`similarity(a, b)`.

## Matching Postgres

`pg_trgm` splits text into words, lower-cases them, pads each as `"  word "`
and takes every three-character window. The similarity of two strings is
the trigrams they share divided by all the distinct trigrams of both. The
details are where other implementations drift:

- **Which characters make up a word** depends on the database's locale.
  Is `²` a letter? Is an Arabic vowel mark? snarlik doesn't guess: its
  tables come from asking Postgres about every Unicode codepoint
  (`tools/pgchars.sql`).
- **Trigrams with non-ASCII characters** are hashed to three bytes with
  Postgres's old CRC-32 variant, and snarlik hashes them the same way, so
  two different trigrams that happen to share a hash count as shared, as
  they do in Postgres.
- **Scores** are computed in 32-bit floats, as Postgres does, so a pair
  right at the threshold lands on the same side.

The bundled tables come from PostgreSQL 18.3 on Debian with the libc
provider and `en_US.utf8`, the common default. For another libc locale,
generate your own (ICU databases aren't supported: ICU lowercases some
characters to several, and by context):

```sh
psql -tA -F $'\t' -f tools/pgchars.sql > pgchars.tsv
python3 tools/gen_tables.py pgchars.tsv "PostgreSQL 17, libc sv_SE.utf8" > src/tables.zig
```

To check snarlik against your database on your own data:

```sh
PSQL="psql mydb" tools/check-pg.sh rows.tsv 0.85
# postgres: 3227 pairs, snarlik: 3227 pairs
# identical
```

CI runs this against PostgreSQL 18.3 on every change, and checks that the
bundled tables still match it.

Not covered yet: `word_similarity` and `strict_word_similarity` (`<%`,
`<<%`), and big-endian machines (Postgres's hashed trigrams depend on byte
order).

## How it's fast

Postgres's trigram index answers "which rows share any trigram with this
one?" For common trigrams such as `pod` or `the` that is a large share of the
table, and every hit gets its similarity computed.

snarlik avoids nearly all of that work:

- **Prefix filter** (AllPairs; Bayardo, Ma and Srikant, 2007). Trigrams are
  ranked rarest first and records sorted smallest first. A record of *n*
  trigrams can only reach threshold *t* with a record that shares one of its
  first *n − ⌈t·n⌉ + 1* trigrams, so only those are indexed and looked up,
  and records too small to reach *t* are skipped.
- **Position filter** (PPJoin; Xiao et al., 2008). Where two records' first
  shared trigram sits caps how many they can share in all. Most candidates
  fail that test and are never compared; the rest are compared from that
  trigram on, and the comparison stops as soon as the pair can no longer
  reach *t*.
- **Threads.** Each record looks up the finished index on its own, so the
  records are split across all CPUs (`-j` to choose how many).

The filters use the same float4 arithmetic as the final score, so they never
drop a pair Postgres would return.

## Benchmark

Apple M4 Pro (14 cores), PostgreSQL 18.3 in Docker on the same machine.
The Postgres column is one run of `tools/pg-pairs.sh`: loading the rows into
a temp table, building the GIN index and the `%` self-join, on one core.
snarlik's columns are the best of three runs, reading the file included.
Both found exactly the same pairs in every row of both tables.

**Real data:** 145,785 podcast names from [chart.haus](https://chart.haus)
(not published).

| Threshold | Pairs | Postgres, 1 core | snarlik, 1 thread | snarlik, 14 threads |
|---|---|---|---|---|
| 0.9 | 2,870 | 88 s | 0.13 s | 0.10 s |
| 0.85 | 3,227 | 106 s | 0.19 s | 0.11 s |
| 0.7 | 11,608 | 189 s | 0.61 s | 0.15 s |
| 0.6 | 52,935 | 297 s | 1.63 s | 0.26 s |

**Postgres at its best.** At 0.85, timing the join alone (rows already
loaded and indexed), the fastest setup found was a GIN index on an unlogged
table with eight parallel workers (the default `max_worker_processes`):
14 seconds. A GiST index took 9.5 minutes, and turning JIT off changed
nothing.

**Synthetic data:** 100,000 generated titles, reproducible with the commands
below. Made-up words share more trigrams than real titles, so there are
more candidates to rule out and the work per row is higher.

| Threshold | Pairs | Postgres, 1 core | snarlik, 1 thread | snarlik, 14 threads |
|---|---|---|---|---|
| 0.9 | 11,467 | 117 s | 0.14 s | 0.08 s |
| 0.8 | 21,753 | 195 s | 0.46 s | 0.11 s |
| 0.7 | 49,197 | 295 s | 1.43 s | 0.21 s |
| 0.6 | 180,264 | 454 s | 4.15 s | 0.48 s |

To reproduce, or to run it on your own rows:

```sh
zig build -Doptimize=ReleaseFast
bench/run.sh                                   # synthetic, snarlik only
PSQL="psql mydb" bench/run.sh                  # with Postgres (slow)
THRESHOLDS="0.85 0.6" bench/run.sh rows.tsv    # your own rows
```

`bench/gen_names.py` makes the synthetic titles: Zipf-distributed made-up
words, filler words such as "the" and "podcast", about one row in ten an
edited copy of an earlier one, and some Swedish, German, French, Cyrillic
and Japanese words.

## Development

```
src/
  root.zig      the library's public API
  trigram.zig   pg_trgm's trigrams and similarity
  join.zig      the self-join: filters, index, threads
  main.zig      the CLI and COPY text parsing
  tables.zig    generated from Postgres by tools/
python/         the Python module the wheels carry, and its test
tools/
  pgchars.sql, gen_tables.py   regenerate src/tables.zig
  build_wheel.py               package a binary as a Python wheel
  pg-pairs.sh, check-pg.sh     Postgres's pairs, and the diff against them
bench/          benchmark script and synthetic data generator
tests/          COPY escapes and edge cases for check-pg.sh
```

```sh
zig build test                                    # unit tests
PSQL="psql mydb" tools/check-pg.sh tests/copy-escapes.tsv
```

## License

MIT
