Last week I shipped the dedup layer: a whitespace-normalized fingerprint of every posting body, one sqlite table, and a graph node that routes to the end without calling the model when the job is a copy. It works — but its own honest part ended with an IOU. A posting that gets reworded — same job, same company, one recruiter's paraphrase posted on a second board — produces a different fingerprint, and my exact-match cache just shrugs and pays for the judgment again.
That paragraph was still warm when a reader asked about exactly that: what do you do about reposts that are meaning-identical but never byte-identical? This post pays the debt — and it turns out to be free of new infrastructure, because the answer was already in this series.
An exact fingerprint is just cosine similarity 1.0
Here's the mental shift that made this post small. My part-7 fingerprint says "same body ⇔ same 64-bit hash". That's one point on a continuum: two texts that differ in zero characters have cosine similarity 1.0 between their embeddings. Byte-identical dedup is a threshold check with the threshold at exactly 1.0 — and I already have the machinery for the general case, because part 2 built it: a 33 MB bge-small-en-v1.5 model, normalized 384-float vectors, cosine as a plain dot product.
So the fingerprint stays (it's free, it's exact, it's the fast path), and the fallback for fingerprint misses is obvious: embed the body and ask the store for its nearest neighbor. The two supporting pieces already exist in the repo from part 2:
# fingerprints.py — the part-7 exact path, untouched
import hashlib
import re
WHITESPACE = re.compile(r"\s+")
def normalize(text: str) -> str:
"""Lowercase, collapse whitespace."""
return WHITESPACE.sub(" ", text.lower().strip())
def fingerprint(text: str, length: int = 16) -> str:
return hashlib.sha256(normalize(text).encode("utf-8")).hexdigest()[:length]
def url_key(url: str) -> str:
"""Drop tracking params so UTM-littered reposts collide correctly."""
return url.split("?")[0]
# embedder.py — the part-2 embedding stack, reduced to one function
import fastembed
import numpy as np
MODEL = "BAAI/bge-small-en-v1.5" # 384 dims, ~33 MB, CPU, no API key
_model = None
def embedder() -> fastembed.TextEmbedding:
global _model
if _model is None: # lazy load: don't pay on import
_model = fastembed.TextEmbedding(model_name=MODEL)
return _model
def embed(text: str) -> np.ndarray:
vec = np.asarray(next(embedder().embed([text])), dtype=np.float32)
return vec / np.linalg.norm(vec) # normalize once -> dot product IS cosine
Two comments on the second block, because both are load-bearing for what follows:
- Normalize at embed time, not compare time. If every stored vector and every query vector is unit length,
emb @ q returns cosine similarities directly. I forget this rule about once a month, which is why it gets a comment in a series.
- The model is the same one that powers resume retrieval. One 33 MB download, loaded lazily, covers two features. Every "build your own RAG" tutorial that starts with a vector service loses to this by default at my scale — that argument was part 2's conclusion and it keeps compounding.
One column, not one service: 384 floats in the sqlite row
The vector store for dedup is not a new store. It's one BLOB column in the table from part 7:
# seen_store.py — the part-7 table with two new columns
import sqlite3
import time
import numpy as np
SCHEMA = """
CREATE TABLE IF NOT EXISTS seen_jobs (
fingerprint TEXT PRIMARY KEY,
url_key TEXT NOT NULL,
verdict TEXT NOT NULL,
score REAL NOT NULL,
policy_id TEXT NOT NULL DEFAULT 'v1',
judged_at REAL NOT NULL,
emb BLOB
);
CREATE INDEX IF NOT EXISTS idx_seen_pol ON seen_jobs (policy_id);
"""
class SeenStore:
def __init__(self, path: str = "seen_jobs.db", window_days: int = 14):
self.conn = sqlite3.connect(path)
self.conn.executescript(SCHEMA)
self.window = window_days * 86400
def exact(self, fp: str, policy_id: str) -> dict | None:
row = self.conn.execute(
"SELECT verdict, score, judged_at FROM seen_jobs"
" WHERE fingerprint = ? AND policy_id = ?",
(fp, policy_id),
).fetchone()
if row is None:
return None
return {"verdict": row[0], "score": row[1], "judged_at": row[2]}
def nearest(self, q: np.ndarray, policy_id: str) -> dict | None:
"""Best cosine match among embeddings stored for this policy.
Rows with an expired (or future) judged_at are skipped here —
a stale timestamp must not win the argmax.
"""
now = time.time()
rows = self.conn.execute(
"SELECT fingerprint, url_key, verdict, score, judged_at, emb"
" FROM seen_jobs WHERE policy_id = ? AND emb IS NOT NULL",
(policy_id,),
).fetchall()
rows = [r for r in rows
if (now - r[4]) <= self.window and (now + 60) >= r[4]]
if not rows:
return None
emb = np.stack([np.frombuffer(r[5], dtype=np.float32) for r in rows])
sims = emb @ q
i = int(sims.argmax())
return {
"fingerprint": rows[i][0], "url_key": rows[i][1],
"verdict": rows[i][2], "score": rows[i][3],
"judged_at": rows[i][4], "similarity": float(sims[i]),
}
def record(self, fp: str, url_key: str, verdict: str, score: float,
emb: np.ndarray, policy_id: str = "v1") -> None:
self.conn.execute(
"INSERT INTO seen_jobs"
" (fingerprint, url_key, verdict, score, policy_id, judged_at, emb)"
" VALUES (?, ?, ?, ?, ?, ?, ?)"
" ON CONFLICT(fingerprint) DO UPDATE SET"
" url_key = excluded.url_key, verdict = excluded.verdict,"
" score = excluded.score, policy_id = excluded.policy_id,"
" judged_at = excluded.judged_at, emb = excluded.emb",
(fp, url_key, verdict, score, policy_id, time.time(), emb.tobytes()),
)
self.conn.commit()
# expired() is unchanged from part 7: window_days lifetime, plus
# paranoid expiry for rows whose judged_at is somehow in the future.
exact() is the fastest possible lookup — one indexed row — and it runs first, every time, for free. nearest() is the fallback, and at the scale this series operates at, a full scan over a few dozen 384-float vectors is one matmul measured in microseconds — the same argument part 2 made about vector databases, wearing a new hat. The np.frombuffer(r[5], dtype=np.float32) round-trip is the only genuinely new skill here: sqlite BLOBs come out as bytes, numpy reconstructs them as a view, zero-copy — no serialization library, no new dependency. And part 7's expiry discipline carried over into the vector path for free: the filter on judged_at in nearest() is one list comprehension, because a posting that has gone stale must not win the argmax just because it's similar.
<!-- NOTE TO V: — if the real dedup store already evolved past the part-7 demo schema (real column names, real store file), reconcile schema and column names before publishing. window_days=14 and the demo path are stand-ins inherited from part 7. -->
The node: same shape, one check deeper
The part-7 dedup_node gained one branch. The routing philosophy from part 3 is intact — nodes return state patches, never call each other — and the cache check is still a node with zero tokens, because the embedding model is not an LLM: 384 floats at CPU speed, roughly a millisecond:
# dedup_node.py — same three-branch shape as part 7, plus the fuzzy branch
from embedder import embed
from fingerprints import fingerprint, url_key
from seen_store import SeenStore
from state import AgentState
store = SeenStore("seen_jobs.db", window_days=14)
POLICY_ID = "recruiter-strict-v1"
SIM_FLOOR = 0.92 # "same job, reworded" floor — tuned on measured pairs (below)
COOL_OFF_LO = 55.0 # cached rejections below this are confident -> reuse
def _reuseable(verdict: str, score: float) -> bool:
"""Match verdicts and confident rejections are cheap to reuse.
The gray zone [COOL_OFF_LO, 70) is where the model is noisy
(the eval-bands lesson), so gray-zone hits get a fresh call.
"""
if verdict == "match":
return True
return score < COOL_OFF_LO
def dedup_node(state: AgentState) -> dict:
fp = fingerprint(state.job_description)
hit = store.exact(fp, POLICY_ID)
if hit is not None and not store.expired(hit["judged_at"]) \
and _reuseable(hit["verdict"], hit["score"]):
return {"skip_llm": True, "verdict": hit["verdict"],
"score": hit["score"], "hit_mode": "exact"}
near = store.nearest(embed(state.job_description), POLICY_ID)
if (near is not None and near["similarity"] >= SIM_FLOOR
and _reuseable(near["verdict"], near["score"])):
return {"skip_llm": True, "verdict": near["verdict"],
"score": near["score"], "hit_mode": "fuzzy"}
return {"skip_llm": False, "hit_mode": "new"}
def record_node(state: AgentState) -> dict:
"""Runs after the judge node — now it also stores meaning."""
store.record(
fingerprint(state.job_description),
url_key(state.job_url),
state.verdict,
state.score,
embed(state.job_description), # NEW vs part 7: meaning in the row
POLICY_ID,
)
return {}
Two things in that block are edits that happened after feedback, which is the honest heart of this series:
The gray-zone re-judge survived the rewrite. When part 7 went out, a reader caught a real bug in my demo logic: my rule reused any cached rejection below score 70, so a posting that scored 68 once was locked out forever — exactly in the band where an LLM is noisiest. The fix is in this version: match verdicts and confident rejections (< 55) are reused, the 55–70 band re-judges on every hit, exact or fuzzy. A paraphrased repost in the gray zone buys the model a fresh opinion — correct behavior for a cache whose backend is a temperature-based judge that drifts between releases.
policy_id as a column, not a hash suffix. The part-7 comment thread also asked: what invalidates a verdict when my criteria change? Baking policy_id into the fingerprint text handled exact hits — but a paraphrased repost would still cosine through a policy bump and silently inherit an old-policy verdict. As a column with a WHERE, a policy bump empties the entire similarity index at once: old embeddings can never contaminate new-policy decisions. One string, one clause.
The hit_mode: "exact" | "fuzzy" | "new" field goes into the log line, so I can watch the fuzzy branch's hit rate on real data before I fully trust it.
<!-- NOTE TO V: — AgentState fields and node names must match the repo ("judge"/"record_node" etc.). Decide whether hit_mode belongs in state or in the log; COOL_OFF_LO=55 and the [55,70) gray band were settled in the part-7 comment answers — keep them consistent with what you posted. -->
The numbers: a gap you can draw a line through
I ran the demo graph over eight postings in two passes. Pass 1: three fresh postings (one match at 82, one confident rejection at 48, one gray-zone rejection at 61). Pass 2: the original unchanged, the same posting littered with UTM junk, a paraphrased repost of the 82-scorer (reordered sections, different sentences, same job), a gray-zone exact repost, and one genuinely unrelated job.
PASS 1
boards.example.com/acme/eng/123?ref=tw mode=new JUDGED score= 82.0
dataforge.example.com.jobs/3311 mode=new JUDGED score= 48.0
brightpath.example.com/careers/44 mode=new JUDGED score= 61.0
PASS 2
boards.example.com/acme/eng/123 mode=exact REUSE (exact) score= 82.0
otherboard.example.com/acme/eng/123?gh_jid=9 mode=exact REUSE (exact) score= 82.0
jobboard.example.com/xyz/888 (paraphr) mode=fuzzy REUSE (fuzzy) score= 82.0
logista.example.com/warehouse/12 (unrel) mode=new JUDGED score= 40.0
brightpath.example.com/careers/44repost (gray) mode=new JUDGED score= 61.0
LLM calls: pass 1 = 3, pass 2 = 2 (8 postings)
Read pass 2 as a ledger: two byte-identical copies free, the paraphrase free, the unrelated job correctly not recycled (a similarity misuse would have handed the warehouse-coordinator role an inherited 82), and the gray-zone repost re-judged — by design, not by accident. Three of five potential LLM calls saved, from one fallback and two thresholds.
Now the number the thresholds rest on — actual cosines, measured with the real model across the demo corpus:
front-end orig x front-end paraphrased: 0.945 <- same job, reworded
front-end orig x full-stack posting: 0.818 <- different job, related role
front-end orig x python/Django posting: 0.624 <- different field
front-end orig x warehouse coordinator: 0.582 <- unrelated
That's the whole threshold story in four numbers. My first guess for SIM_FLOOR was 0.85 — which would have wrongly recycled the full-stack job for the front-end matcher at 0.818 and handed it an inherited 82. The measured gap (0.945 above, 0.818 below) put the honest floor in the middle: 0.92. The lesson is verbatim from part 2's TOP_K post: a similarity constant can't be guessed, it has to be measured on the pairs you'll actually see — same-job pairs on one side, related-but-different roles on the other — and the gap between the bands is the safety margin. On this demo corpus the margin is comfortable.
<!-- NOTE TO V: — the cosine table and demo transcript are from the sandbox corpus (stub postings); before publishing, re-run the same probe on a handful of real postings from your scrape history and either quote those numbers or explicitly label the sandbox numbers as such. Also worth one real-log line: what % of nightly postings were reworded reposts — that number sells the intro. -->
What this cost, and what it didn't
- No new service, no new dependency, no new model. The embedding stack is the same 33 MB download that powers resume retrieval; the store gained 1,536 bytes per row (384 floats) and two columns.
- Embed on write, not on read.
record_node pays one embed per judged posting — and only judged ones. Cached and re-judged skips don't touch the store, so the write cost is paid exactly when you're paying the LLM anyway.
- The fingerprint didn't move. Exact match remains the fast path and handles the common case (unchanged reposts, UTM-littered copies) with one indexed lookup and zero embeddings at check time. Cosine only runs on fingerprint misses.
Wrap-up
Two posts ago the insight was "the identity of a job posting is its body." This post is the same sentence with a softer ending: identity is meaning, and meaning lives on a continuum — exact copies at 1.0, reworded reposts at 0.94, related roles at 0.82. My job is to know the bands, not just the endpoints. One blob column, one dot product, one measured threshold between them.
This is part 8 of Building an AI Job Copilot in Python. Previous post: the dedup layer with exact fingerprints. Earlier parts covered structured JSON output, retrieval without a vector DB, the first graph, the eval harness, and graph unit tests with checkpoints.
If you're building something similar: follow here or on dev.to. Next part: making the nightly batch resilient when the LLM is down — retries that don't multiply your spend. And tell me: did you set your similarity threshold by measuring pairs, or by copying a constant? I've done both, and only one survived contact with the corpus.