#!/usr/bin/env python3 """alias_merge.py — group fragmented employer spellings into one history key. WHY THIS EXISTS (c307, 2026-09-11). The paid product's headline feature is "hand us your list; day one every name is scored against the 1988-present archive". That report, the per-employer public pages, and the `history` line attached to every alert are all built by `warn_watch.dossier_index()`, which keys on the EXACT lowercased `company_canonical` string. The alert MATCHER, by contrast, uses token-subset matching (`warn_watch.notice_matches`). Those two disagree, and the disagreement is worst exactly where it hurts most: Boeing files under 22 distinct spellings in the archive, including the typos 'Boeing Compnay' and 'Thte Boeing Company'. A buyer watching "Boeing" DOES get an alert when 'Boeing - El Paso' files (token subset), but the history line on that alert looks up the key 'boeing - el paso' and reports "2 prior notices" when the truth is 420 across 13 states. Measured on the 59,134-row archive (c307): - 34,154 distinct canonical keys. - Tier 1 (stopword/punctuation only): 415 groups, 467 keys, 663 notices. - Tier 2 (prefix absorption, purity >= 0.90): 4,615 keys, 7,238 notices. => ~7,900 notices (13% of the archive) gain a materially fuller history. THE OVER-MERGE HAZARD, AND THE GUARD. Naive prefix absorption folds 'venture stores' into 'venture' and 'marriott international' into 'marriott', which would attribute unrelated companies to each other ON PUBLIC PAGES -- strictly worse than under-counting, because it looks like evidence. The guard is token PURITY: for a single-token parent P, the share of distinct canonical keys containing token P that actually START with P. boeing 0.93 verizon 0.94 ames 1.00 -> merged meta 0.86 united 0.83 compass 0.78 -> blocked sears 0.76 novartis 0.69 general 0.63 -> blocked marriott 0.47 venture 0.21 -> blocked At PURITY_MIN = 0.90 the rule deliberately UNDER-merges (it blocks the genuinely-correct 'cvs health' -> 'cvs'). That asymmetry is intentional: a missed merge under-reports a history, a false merge publishes a lie. Multi-token parents ('thermo fisher', 'general dynamics', 'p f chang s') are not purity-gated -- two or more tokens matching in order is already strong evidence, and no false merge was found among them by inspection. USAGE python3 alias_merge.py --selftest # assert the known good/bad cases python3 alias_merge.py --report # impact summary + examples from alias_merge import build_alias_map amap = build_alias_map(rows) # exact canonical (lower) -> group key NOT YET WIRED INTO publish.sh. See BACKLOG 0-ALIAS-MERGE. """ import collections import csv import re import sys FULL_CSV = "out/full/warn_notices.csv" STOP = {"inc", "llc", "corp", "corporation", "co", "company", "ltd", "the", "of", "and", "incorporated", "lp", "llp", "plc"} PURITY_MIN = 0.90 # single-token parents below this are never used PARENT_MIN_NOTICES = 3 # a parent must itself be a real, repeatedly-filing employer def tokens(s): """Same tokenizer as warn_watch.tokens -- keep these two in step.""" return [t for t in re.split(r"[^a-z0-9]+", str(s or "").lower()) if t] def norm_sig(s): """Normalized token signature: lowercase, punctuation-free, stopwords dropped.""" return tuple(t for t in tokens(s) if t not in STOP) def canon_of(row): return (row.get("company_canonical") or row.get("company") or "").strip().lower() def build_alias_map(rows, purity_min=PURITY_MIN, parent_min=PARENT_MIN_NOTICES): """exact lowercased canonical -> group key (also a lowercased canonical). Identity entries are omitted; callers should treat a missing key as 'maps to itself'. Deterministic: no dict-ordering dependence. """ counts = collections.Counter() for r in rows: c = canon_of(r) if c: counts[c] += 1 # signature -> [canonical keys], and signature total notice count by_sig = collections.defaultdict(list) for k in counts: by_sig[norm_sig(k)].append(k) sig_total = {s: sum(counts[k] for k in ks) for s, ks in by_sig.items() if s} # token -> distinct signatures containing it (for the purity guard) tok2sigs = collections.defaultdict(set) for s in sig_total: for t in set(s): tok2sigs[t].add(s) parents = {s for s, n in sig_total.items() if n >= parent_min} def purity(p): if len(p) != 1: return 1.0 sigs = tok2sigs.get(p[0]) or () if not sigs: return 0.0 return sum(1 for s in sigs if s[:1] == p) / len(sigs) # Tier 1: every key in a signature group collapses onto that group's # highest-volume key (ties broken by the shorter, then lexically first name). def rep_of(keys): return sorted(keys, key=lambda k: (-counts[k], len(k), k))[0] sig_rep = {s: rep_of(ks) for s, ks in by_sig.items() if s} # Tier 2: a signature absorbs into its SHORTEST existing parent prefix. absorb = {} for s in sig_total: for L in range(1, len(s)): p = s[:L] if p in parents and p != s and purity(p) >= purity_min: absorb[s] = p break # Resolve prefix chains (a -> b -> c) to their terminal parent. def resolve(s, _seen=None): _seen = _seen or set() while s in absorb and s not in _seen: _seen.add(s) s = absorb[s] return s amap = {} for s, ks in by_sig.items(): if not s: continue target = sig_rep[resolve(s)] for k in ks: if k != target: amap[k] = target return amap def load_rows(path=FULL_CSV): with open(path, newline="", encoding="utf-8", errors="replace") as f: return list(csv.DictReader(f)) # -------------------------------------------------------------------------- # selftest: the cases that justified the design. If these ever flip, the # tokenizer, the purity guard or the archive changed -- investigate, do not # "fix" the assertion. # -------------------------------------------------------------------------- MUST_MERGE = [ # (child spelling, expected group token) ("boeing - el paso", "boeing"), ("boeing compnay", "boeing"), ("boeing commercial airplane group", "boeing"), ("boeing company - oregon location", "boeing"), ] MUST_NOT_MERGE = [ # over-merge hazards: must stay separate ("venture stores", "venture"), ("marriott international", "marriott"), ("compass group", "compass"), ("sears holdings", "sears"), ] def selftest(): rows = load_rows() amap = build_alias_map(rows) ok = True for child, parent_tok in MUST_MERGE: got = amap.get(child, child) if norm_sig(got) != (parent_tok,): print("FAIL merge: %r -> %r (wanted group %r)" % (child, got, parent_tok)) ok = False for child, parent_tok in MUST_NOT_MERGE: got = amap.get(child, child) if norm_sig(got) == (parent_tok,): print("FAIL over-merge: %r was folded into %r" % (child, parent_tok)) ok = False # No key may map to itself, and every target must be a real canonical. canon = {canon_of(r) for r in rows} for k, v in amap.items(): if k == v: print("FAIL identity entry: %r" % k); ok = False; break if v not in canon: print("FAIL target not a real employer: %r -> %r" % (k, v)); ok = False; break # Boeing's grouped history must beat the ungrouped one. grouped = collections.Counter() for r in rows: c = canon_of(r) if c: grouped[amap.get(c, c)] += 1 before = sum(1 for r in rows if canon_of(r) == "boeing") after = grouped.get("boeing", 0) states = {r.get("state") for r in rows if amap.get(canon_of(r), canon_of(r)) == "boeing"} print("boeing notices: %d -> %d | states: %d" % (before, after, len(states))) if after <= before: print("FAIL: grouping did not improve Boeing"); ok = False print("alias_merge selftest:", "PASS" if ok else "FAIL") return 0 if ok else 1 def report(): rows = load_rows() amap = build_alias_map(rows) canon = collections.Counter(canon_of(r) for r in rows if canon_of(r)) moved = sum(canon[k] for k in amap) groups = collections.defaultdict(list) for k, v in amap.items(): groups[v].append(k) print("distinct canonical employers : %d" % len(canon)) print("keys folded into a group : %d" % len(amap)) print("notices re-homed : %d (%.1f%% of %d)" % (moved, 100.0 * moved / max(1, len(rows)), len(rows))) print("employers whose history grows: %d" % len(groups)) print("\nlargest regrouped employers:") for tgt, ks in sorted(groups.items(), key=lambda kv: -sum(canon[k] for k in kv[1]))[:12]: print(" %-42s +%4d notices from %d spellings" % (tgt[:42], sum(canon[k] for k in ks), len(ks))) return 0 if __name__ == "__main__": if "--selftest" in sys.argv: sys.exit(selftest()) sys.exit(report())