File size: 25,304 Bytes
0dd5490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
"""End-to-end smoke test for the matching stage: src.features, src.train_matcher, src.predict.

Run with `python tests/test_matcher_smoke.py` (or pytest). Builds a tiny synthetic world with the
hard cases from docs/dataset_findings.md (Indic-script vendor name resolved by transliteration, a
domain-form name, a former-name 'f/k/a' form, a chain = two S1 records with the same name and
different addresses, singletons, orphans, a missed true match, an S1 id without any candidate),
normalises it with src.normalize exactly like scripts/preprocess_normalize.py, fabricates a
blocking-style candidate parquet and then:
  * build_features: in-process == forked workers; keep_s1 subset == the same rows of a full run;
    spot checks on the hard cases; competition counts;
  * train_matcher: k-fold core function + leave-one-country-out through the CLI;
  * predict: train countries + an unseen third country (France); matching_results.tsv and
    candidate_pairs.tsv checked structurally and with student_resource/utils/validate_submission.py.
Everything stays in a temp dir of a few hundred KB.
"""
import json
import os
import random
import shutil
import subprocess
import sys
import tempfile
import unicodedata
import re
from pathlib import Path

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.normalize import normalize_record  # noqa: E402

VALIDATOR = ROOT.parents[1] / "student_resource" / "utils" / "validate_submission.py"
INDIC = re.compile(r"[ऀ-෿]")
NAME_LEX = {"श्री": "shree", "गणेश": "ganesh", "ट्रेडर्स": "traders", "प्राइवेट": "private", "लिमिटेड": "limited",
            "कृष्णा": "krishna", "मोटर्स": "motors", "बालाजी": "balaji", "फूड्स": "foods"}
ADDR_LEX = {}

US_A = ["Holloway", "Prime", "Westbrook", "Summit", "Riverside", "Oakridge", "Maple", "Cedar", "Liberty", "Pioneer",
        "Harbor", "Evergreen", "Golden", "Granite", "Falcon", "Keystone", "Bluebird", "Ironwood", "Sterling"]
US_B = ["Dental", "Pediatric", "Seafood", "Consulting", "Logistics", "Realty", "Bakery", "Auto", "Learning", "Fitness"]
US_C = ["Group", "LLC", "Inc", "Services", "Center", "Co"]
US_ST = ["Elm", "Oak", "Westchester", "Montebello", "Ellis", "Fawn", "Lake", "Hill", "Pine", "Cedar", "Sunset"]
US_TY = [("Street", "St"), ("Road", "Rd"), ("Drive", "Dr"), ("Avenue", "Ave"), ("Court", "Ct")]
US_CITY = [("High Point", "NC", "North Carolina"), ("Phoenix", "AZ", "Arizona"), ("Tahlequah", "OK", "Oklahoma"),
           ("Fort Worth", "TX", "Texas"), ("Morganton", "NC", "North Carolina")]
IN_A = ["Shree", "Aditya", "Krishna", "Ganesh", "Lakshmi", "Balaji", "Durga", "Sai", "Om", "Vishnu", "Maruti", "Surya"]
IN_B = ["Marketing", "Properties", "Traders", "Enterprises", "Textiles", "Pharma", "Constructions", "Motors", "Foods"]
IN_C = ["Private Limited", "LLP", "Pvt Ltd", "Limited"]
IN_LOC = ["Gulmohar Colony", "Subhash Nagar", "MG Road", "Civil Lines", "Banjara Hills", "Salt Lake"]
IN_CITY = [("Bhopal", "Madhya Pradesh", "MP"), ("New Delhi", "Delhi", "DL"), ("Bengaluru", "Karnataka", "KA"),
           ("Hyderabad", "Telangana", "TG"), ("Pune", "Maharashtra", "MH")]
FR_A = ["Boulangerie", "Atelier", "Maison", "Cabinet", "Garage", "Pharmacie", "Librairie", "Brasserie"]
FR_B = ["Dupont", "Martin", "Lefevre", "Moreau", "Bernard", "Petit", "Rousseau", "Fontaine"]
FR_C = ["SARL", "SAS", "EURL", "SA"]
FR_ST = ["de la Paix", "Victor Hugo", "des Lilas", "Pasteur", "du Moulin", "Jean Jaures"]
FR_CITY = [("Lille", "Hauts-de-France", "Nord"), ("Bordeaux", "Nouvelle-Aquitaine", "Gironde"),
           ("Nantes", "Pays de la Loire", "Loire-Atlantique")]


# ---------------------------------------------------------------------------------------------
# synthetic world
# ---------------------------------------------------------------------------------------------
def _typo(s, rng):
    if len(s) < 6:
        return s
    i = rng.randrange(1, len(s) - 2)
    return s[:i] + s[i + 1] + s[i] + s[i + 2:]


def _entity(country, rng):
    if country == "US":
        city, ab, full = rng.choice(US_CITY)
        ty, tya = rng.choice(US_TY)
        st, num = rng.choice(US_ST), rng.randint(10, 9999)
        name = f"{rng.choice(US_A)} {rng.choice(US_B)} {rng.choice(US_C)}"
        return name, (num, st, ty, tya, city, ab, full)
    if country == "India":
        city, st, code = rng.choice(IN_CITY)
        name = f"{rng.choice(IN_A)} {rng.choice(IN_B)} {rng.choice(IN_C)}"
        return name, (rng.randint(1, 999), rng.randint(1, 99), rng.choice(IN_LOC), city, st, code)
    city, reg, dep = rng.choice(FR_CITY)
    name = f"{rng.choice(FR_A)} {rng.choice(FR_B)} {rng.choice(FR_C)}"
    return name, (rng.randint(1, 200), rng.choice(FR_ST), city, reg, dep)


def _s1_addr(country, a):
    if country == "US":
        num, st, ty, tya, city, ab, full = a
        return f"{num} {st} {ty}, {city}, {full}"
    if country == "India":
        n1, n2, loc, city, st, code = a
        return f"{n1}/{n2}, {loc}, {city}, {st}"
    num, st, city, reg, dep = a
    return f"{num} rue {st}, {city}, {reg}"


def _vendor_addr(country, a, rng):
    r = rng.random()
    if r < 0.06:
        return ""
    if country == "US":
        num, st, ty, tya, city, ab, full = a
        if rng.random() < 0.1:
            num = num + 2
        s = f"{num} {st.upper()} {tya.upper()}, {city.upper()}, {ab}" if rng.random() < 0.5 else f"{num} {st} {tya}, {city}"
        return s
    if country == "India":
        n1, n2, loc, city, st, code = a
        return rng.choice([f"H.No {n1}/{n2}, {loc}, {city}, {code}", f"{n1}/{n2}, {city}, {st}", f"{loc}, {city}"])
    num, st, city, reg, dep = a
    return rng.choice([f"{num} R. {st}, {city.upper()}, {dep}", f"{num} rue {st}, {city}"])


def _vendor_name(name, rng):
    r = rng.random()
    if r < 0.3:
        return name
    if r < 0.5:
        return " ".join(name.split()[:-1]) or name  # legal / generic suffix dropped
    if r < 0.65:
        return name.upper()
    if r < 0.8:
        return _typo(name, rng)
    return name + " Services"


def make_world(seed, countries, n_per_country, tag):
    """-> s1 rows, pool rows (raw), gt {s1: [ids]}, special {name: (s1_id, [vendor ids])}."""
    rng = random.Random(seed)
    s1, pool, gt, special = [], [], {}, {}
    nid = [0]

    def new_id(prefix):
        nid[0] += 1
        return f"{prefix}-{tag}{nid[0]:05d}"

    def add_vendor(country, name, addr):
        vid = new_id(rng.choice(["S2", "S3"]))
        pool.append((vid, name, addr, country))
        return vid

    for country in countries:
        for i in range(n_per_country):
            name, a = _entity(country, rng)
            sid = new_id("S1")
            s1.append((sid, name, _s1_addr(country, a), country))
            k = rng.choices([0, 1, 2, 3, 4], weights=[1, 2, 3, 3, 2])[0]
            gt[sid] = [add_vendor(country, _vendor_name(name, rng), _vendor_addr(country, a, rng)) for _ in range(k)]
        for _ in range(n_per_country // 3):  # orphans
            name, a = _entity(country, rng)
            add_vendor(country, _vendor_name(name, rng), _vendor_addr(country, a, rng))
    if "India" in countries:  # Indic-script vendor name, same address
        sid = new_id("S1")
        s1.append((sid, "Shree Ganesh Traders Private Limited", "12/4, Banjara Hills, Hyderabad, Telangana", "India"))
        v1 = add_vendor("India", "श्री गणेश ट्रेडर्स प्राइवेट लिमिटेड", "12/4, Banjara Hills, Hyderabad, Andhra Pradesh")
        v2 = add_vendor("India", "Shree Ganesh Traders Pvt Ltd", "12/4, Hyderabad, TG")
        gt[sid] = [v1, v2]
        special["indic"] = (sid, [v1, v2])
    if "US" in countries:
        sid = new_id("S1")  # domain form
        s1.append((sid, "Dutta International School", "740 Montebello Drive, Phoenix, Arizona", "US"))
        v = add_vendor("US", "duttainternationalschool.com", "740 MONTEBELLO DR, PHOENIX, AZ")
        gt[sid] = [v]
        special["domain"] = (sid, [v])
        sid = new_id("S1")  # former-name form
        s1.append((sid, "Big Seafood LLC", "1200 Elm Street, Fort Worth, Texas", "US"))
        v = add_vendor("US", "Belovera Sys f/k/a Big Seafood LLC", "1200 Elm St, Fort Worth, TX")
        gt[sid] = [v]
        special["former"] = (sid, [v])
        chain = []  # same name, two addresses
        for num, st, city, ab, full in [(15, "Ellis", "High Point", "NC", "North Carolina"),
                                        (3315, "Fawn", "Tahlequah", "OK", "Oklahoma")]:
            sid = new_id("S1")
            s1.append((sid, "Primary Care Group", f"{num} {st} Road, {city}, {full}", "US"))
            vs = [add_vendor("US", "Primary Care Group", f"{num} {st} Rd, {city}, {ab}"),
                  add_vendor("US", "PRIMARY CARE GROUP LLC", f"{num} {st.upper()} ROAD, {city.upper()}")]
            gt[sid] = vs
            chain.append((sid, vs))
        special["chain"] = chain
        sid = new_id("S1")  # singleton with an orphan look-alike
        s1.append((sid, "Keystone Realty Inc", "88 Lake Court, Morganton, North Carolina", "US"))
        add_vendor("US", "Keystone Realty Group", "4512 Pine Ave, Phoenix, AZ")
        gt[sid] = []
        special["singleton"] = (sid, [])
    rng.shuffle(pool)
    return s1, pool, gt, special


def _translit_tokens(raw):
    out, unk = [], 0
    for t in raw.split():
        if INDIC.search(t):
            m = NAME_LEX.get(t) or NAME_LEX.get(t.strip(".,()"))
            if m:
                out.append(m)
            else:
                unk += 1
                out.append(t)
        else:
            t2 = unicodedata.normalize("NFKD", t)
            t2 = "".join(c for c in t2 if not unicodedata.combining(c)).lower()
            t2 = re.sub(r"[^a-z0-9]+", " ", t2).strip()
            if t2:
                out.extend(t2.split())
    return out, unk


def norm_table(rows):
    """Same record layout as scripts/preprocess_normalize.py."""
    out = []
    for eid, n, a, c in rows:
        r = normalize_record(n, a, c)
        if r["name_has_indic_script"]:
            toks, unk = _translit_tokens(n)
        else:
            toks, unk = r["name_tokens"], 0
        r["name_translit_tokens"], r["name_translit_unknown"] = toks, unk
        r["name_translit"] = " ".join(toks)
        r["addr_tokens_translit"] = [ADDR_LEX.get(t, t) for t in r["addr_tokens"]]
        r["entity_id"], r["raw_name"], r["raw_address"] = eid, n, a
        r.pop("addr_postal", None)
        out.append(r)
    return pa.Table.from_pylist(out)


def _jac(a, b):
    a, b = set(a.lower().split()), set(b.lower().split())
    return len(a & b) / len(a | b) if (a or b) else 0.0


def make_cands(s1, pool, gt, seed, per_s1=10, drop_true=0.04, no_cand_s1=()):
    """Blocking-like candidate table: true matches (a few dropped) + most similar same-country vendors."""
    rng = random.Random(seed)
    by_c = {}
    for v in pool:
        by_c.setdefault(v[3], []).append(v)
    rows = []
    for sid, n, a, c in s1:
        if sid in no_cand_s1:
            continue
        true = set(gt.get(sid, []))
        scored = sorted(by_c.get(c, []), key=lambda v: -(_jac(n, v[1]) + 0.5 * _jac(a, v[2])))
        chosen = [v for v in scored if v[0] in true and rng.random() > drop_true]
        for v in scored:
            if len(chosen) >= per_s1:
                break
            if v[0] not in true and v not in chosen:
                chosen.append(v)
        for r, v in enumerate(chosen):
            sn, sa = _jac(n, v[1]), _jac(a, v[2])
            rev = rng.random() < 0.15
            rows.append({"s1_id": sid, "cand_id": v[0], "country": c, "src": v[0][:2],
                         "sim_name": np.float32(sn), "sim_nameaddr": np.float32(0.5 * (sn + sa)),
                         "sim_addr": np.float32(sa) if v[2] else np.float32("nan"),
                         "sim_word": np.float32(0.5 * (sn + sa)), "f_name": True, "f_nameaddr": r < 6,
                         "f_addr": bool(v[2]), "f_word": r < 8, "from_reverse": rev,
                         "rank_name": r, "rank_nameaddr": r if r < 6 else None, "rank_addr": None,
                         "rank_word": r if r < 8 else None, "rank_rev": 0 if rev else None})
    tab = pa.Table.from_pylist(rows)
    return tab.cast(pa.schema([(f.name, pa.int16() if f.name.startswith("rank_") else f.type) for f in tab.schema]))


def write_tsv(path, rows, header=("entity_id", "business_name", "business_address", "country")):
    with open(path, "w", encoding="utf-8") as fh:
        fh.write("\t".join(header) + "\n")
        for r in rows:
            fh.write("\t".join(r) + "\n")


def build_dataset(d: Path):
    s1, pool, gt, special = make_world(7, ["US", "India"], 45, "a")
    t1, tpool, tgt, tspecial = make_world(11, ["US", "India", "France"], 18, "t")
    norm = d / "norm"
    norm.mkdir(parents=True, exist_ok=True)
    pq.write_table(norm_table(s1), norm / "s1.parquet")
    pq.write_table(norm_table([v for v in pool if v[0].startswith("S2")]), norm / "s2.parquet")
    pq.write_table(norm_table([v for v in pool if v[0].startswith("S3")]), norm / "s3.parquet")
    pq.write_table(norm_table(t1), norm / "t1.parquet")
    pq.write_table(norm_table([v for v in tpool if v[0].startswith("S2")]), norm / "t2.parquet")
    pq.write_table(norm_table([v for v in tpool if v[0].startswith("S3")]), norm / "t3.parquet")
    no_cand = {s1[3][0]}  # one S1 id never gets candidates (scored as an empty prediction)
    pq.write_table(make_cands(s1, pool, gt, 1, no_cand_s1=no_cand), d / "cands_train.parquet")
    pq.write_table(make_cands(t1, tpool, tgt, 2, no_cand_s1={t1[0][0]}), d / "cands_test.parquet")
    pq.write_table(pa.table({"a": [s for s, v in gt.items() for _ in v], "b": [x for v in gt.values() for x in v]}),
                   d / "pairs.parquet")
    pq.write_table(pa.table({"source1_entity_id": list(gt), "matched_entity_ids": [",".join(v) for v in gt.values()]}),
                   d / "gt.parquet")
    # pair audit (same columns as the EDA table pf3): one row per true pair
    names = {r[0]: r[1] for r in s1 + pool}
    addrs = {r[0]: r[2] for r in pool}
    au = [{"a": s, "b": v, "indic_name": bool(INDIC.search(names[v])), "domain_form": ".com" in names[v],
           "former_form": "f/k/a" in names[v], "addr_empty": addrs[v] == "", "name_j": _jac(names[s], names[v])}
          for s, vs in gt.items() for v in vs]
    pq.write_table(pa.Table.from_pylist(au), d / "pair_audit.parquet")
    test_dir = d / "dataset_test"
    test_dir.mkdir(exist_ok=True)
    write_tsv(test_dir / "test_source1.tsv", t1)
    write_tsv(test_dir / "test_source2.tsv", [v for v in tpool if v[0].startswith("S2")])
    write_tsv(test_dir / "test_source3.tsv", [v for v in tpool if v[0].startswith("S3")])
    return {"s1": s1, "pool": pool, "gt": gt, "special": special, "t1": t1, "tpool": tpool, "tgt": tgt,
            "no_cand": no_cand, "test_dir": test_dir}


# ---------------------------------------------------------------------------------------------
# tests
# ---------------------------------------------------------------------------------------------
def _row(df, s1_id, cand_id):
    m = (df["s1_id"].astype(str) == s1_id) & (df["cand_id"].astype(str) == cand_id)
    assert m.sum() == 1, (s1_id, cand_id, int(m.sum()))
    return df[m].iloc[0]


def check_features(d: Path, W: dict):
    import polars as pl
    from src.features import PAIR_FEATURES, build_features, build_idf_tables, feature_columns, load_norm

    s1t = load_norm(d / "norm" / "s1.parquet")
    pt = load_norm([d / "norm" / "s2.parquet", d / "norm" / "s3.parquet"])
    cands = pl.read_parquet(d / "cands_train.parquet")
    idf = build_idf_tables(s1t)
    assert set(idf) == {"us", "india"}, idf.keys()
    f1 = build_features(cands, s1t, pt, idf, n_jobs=1, verbose=False)
    f2 = build_features(cands.to_pandas(), s1t, pt, idf, n_jobs=2, task_rows=97, verbose=False)
    cols = feature_columns(f1)
    assert len(f1) == cands.height and cols == feature_columns(f2)
    a1 = f1[[c for c in cols if c != "country"]].to_numpy(np.float64)
    a2 = f2[[c for c in cols if c != "country"]].to_numpy(np.float64)
    assert np.allclose(a1, a2, equal_nan=True), "forked workers differ from in-process"
    assert (f1["country"].astype(str) == f2["country"].astype(str)).all()
    assert str(f1["country"].dtype) == "category" and sorted(f1["country"].cat.categories) == ["India", "US"]
    assert not np.isnan(f1[PAIR_FEATURES].to_numpy()).any(), "pair features must not be NaN"
    assert list(f1["s1_id"].astype(str)) == cands.get_column("s1_id").to_list()  # input order kept

    sp = W["special"]
    sid, (v1, v2) = sp["indic"][0], sp["indic"][1]
    r = _row(f1, sid, v1)
    assert r.p_has_indic == 1 and r.n_jac == 1.0 and r.n_ratio == 100 and r.n_legal3 == 1, r[PAIR_FEATURES[:20]]
    assert r.a_state3 == 1  # telangana == andhra pradesh
    sid, (v,) = sp["domain"]
    r = _row(f1, sid, v)
    assert r.p_is_domain == 1 and r.n_sp_ratio == 100 and r.a_stno3 == 1, r
    sid, (v,) = sp["former"]
    r = _row(f1, sid, v)
    assert r.n_alt_best == 100 and r.n_ratio == 100
    (sa, va), (sb, vb) = sp["chain"]
    own, other = _row(f1, sa, va[0]), _row(f1, sa, vb[0])
    assert own.n_ratio == other.n_ratio == 100 and own.a_tset > other.a_tset and own.a_stno3 == 1 and other.a_stno3 == 0
    assert own.c_p_n >= 2 and own.s1_name_freq == 2  # two S1 records share the chain name
    # competition sanity
    g = f1.groupby(f1["s1_id"].astype(str))
    assert (g["c_s1_n"].transform("first").to_numpy() == g["c_s1_n"].transform("size").to_numpy()).all()
    assert (f1["c_s1_rank"] >= 1).all() and (f1["c_s1_gap"] >= 0).all()
    assert (g["c_s1_rank"].transform("min") == 1).all()
    gp = f1.groupby(f1["cand_id"].astype(str))
    assert (gp["c_p_n"].transform("first").to_numpy() == gp["c_p_n"].transform("size").to_numpy()).all()
    # keep_s1 subset = the same rows of the full run (competition context unchanged)
    keep = sorted(set(cands.get_column("s1_id").to_list()))[::3]
    f3 = build_features(cands, s1t, pt, idf, n_jobs=2, task_rows=50, keep_s1=keep, verbose=False)
    sub = f1[f1["s1_id"].astype(str).isin(keep)].reset_index(drop=True)
    assert len(f3) == len(sub) > 0
    assert np.allclose(sub[[c for c in cols if c != "country"]].to_numpy(np.float64),
                       f3[[c for c in cols if c != "country"]].to_numpy(np.float64), equal_nan=True)
    print(f"features OK: {len(f1)} rows x {len(cols)} features")


def check_train(d: Path, W: dict):
    from src import train_matcher

    folds_file = d / "artifacts" / "folds.parquet"
    common = ["--cands", str(d / "cands_train.parquet"), "--norm-dir", str(d / "norm"), "--pairs", str(d / "pairs.parquet"),
              "--gt", str(d / "gt.parquet"), "--workers", "2", "--task-rows", "200", "--lr", "0.1", "--leaves", "15",
              "--min-data-in-leaf", "5", "--rounds", "300", "--early-stop", "30", "--log-period", "0",
              "--inner-val-frac", "0.2", "--folds", "3", "--folds-file", str(folds_file),
              "--pair-audit", str(d / "pair_audit.parquet")]
    out = d / "model_kfold"
    m = train_matcher.run(train_matcher.build_parser().parse_args(common + ["--out-dir", str(out), "--neg-ratio", "4"]))
    for fn in ["model_fold0.txt", "model_fold2.txt", "calibrator.pkl", "features.json", "metrics.json",
               "importance.csv", "oof.parquet", "folds.parquet"]:
        assert (out / fn).exists(), fn
    assert folds_file.exists()
    folds = pq.read_table(folds_file).to_pydict()
    assert sorted(folds["s1_id"]) == sorted(W["gt"]) and set(folds["fold"]) == {0, 1, 2}
    assert m["headline"] == "kfold_oof"
    ev = m["results"]["kfold_oof"]
    assert m["universe_mode"] == "all" and m["n_eval_s1"] == len(W["gt"]) == ev["n_s1"], (m["universe_mode"], m["n_eval_s1"])
    assert ev["n_s1_with_cands"] == len(W["gt"]) - len(W["no_cand"])  # the no-candidate S1 id is still scored
    assert 0.0 <= ev["macro_f05"] <= 1.0 and ev["blocking_pair_recall"] < 1.0
    assert ev["macro_f05"] > 0.6, ev["macro_f05"]
    assert 0.0 < ev["expected_f05_mean_all"] <= 1.0 and ev["threshold_oof"] in [float(x) for x in ev["threshold_sweep"]]
    assert ev["pair_cal"]["auc"] > 0.9
    cats = {r["category"]: r for r in ev["noise"]}
    assert cats["indic_script"]["pairs"] >= 1 and cats["domain_form"]["pairs"] >= 1 and cats["former_name"]["pairs"] >= 1
    assert {r["slice"] for r in ev["breakdown"] if r["dimension"] == "true_count"} >= {"0", "1", "2"}
    assert {r["slice"] for r in ev["breakdown"] if r["dimension"] == "group"} == {"us", "india"}
    meta = json.loads((out / "features.json").read_text())
    assert meta["models"] == ["model_fold0.txt", "model_fold1.txt", "model_fold2.txt"] and "country" in meta["features"]
    print(f"train k-fold OK: macro F0.5 {ev['macro_f05']:.4f} (expected {ev['expected_f05_mean_all']:.4f}), "
          f"AUC {ev['pair_cal']['auc']:.4f}")

    # leave-one-country-out + --max-s1 through the CLI, reusing the shared folds file
    out2 = d / "model_loco"
    cmd = [sys.executable, "-m", "src.train_matcher"] + common + ["--out-dir", str(out2), "--holdout-country", "India",
                                                                   "--max-s1", "80"]
    p = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)
    assert p.returncode == 0, p.stdout[-3000:] + p.stderr[-3000:]
    assert "folds: reused" in p.stdout
    m2 = json.loads((out2 / "metrics.json").read_text())
    assert m2["headline"] == "loco:india" and m2["n_eval_s1"] == 80
    r2 = m2["results"]
    assert set(r2) == {"loco:india", "loco:india/train_oof", "loco:india/oracle_calibration"}
    n_india = sum(1 for k in r2["loco:india/train_oof"]["breakdown"] if k["dimension"] == "group" and k["slice"] == "india")
    assert n_india == 0 and all(b["slice"] == "india" for b in r2["loco:india"]["breakdown"] if b["dimension"] == "group")
    assert pq.read_table(out2 / "folds.parquet").to_pydict() == folds
    assert len(json.loads((out2 / "features.json").read_text())["models"]) == 3
    print(f"train holdout India OK: macro F0.5 {r2['loco:india']['macro_f05']:.4f} "
          f"(oracle calibration {r2['loco:india/oracle_calibration']['macro_f05']:.4f})")
    return out


def check_predict(d: Path, W: dict, model_dir: Path):
    from src import predict

    out = d / "output"
    argv = ["--cands", str(d / "cands_test.parquet"), "--norm-dir", str(d / "norm"), "--model-dir", str(model_dir),
            "--s1", str(d / "norm" / "t1.parquet"), "--out-dir", str(out), "--workers", "2", "--task-rows", "100",
            "--save-probs"]
    if VALIDATOR.exists():
        argv += ["--validator", str(VALIDATOR), "--test-dir", str(W["test_dir"])]
    rc = predict.main(argv)
    assert rc == 0, "predict / validator failed"
    s1_ids = [r[0] for r in W["t1"]]
    lines = (out / "matching_results.tsv").read_text(encoding="utf-8").split("\n")
    assert lines[0] == "source1_entity_id\tmatched_entity_ids" and lines[-1] == ""
    rows = [ln.split("\t") for ln in lines[1:-1]]
    assert [r[0] for r in rows] == s1_ids and all(len(r) == 2 for r in rows)
    cl = (out / "candidate_pairs.tsv").read_text(encoding="utf-8").split("\n")
    assert cl[0] == "source1_entity_id\tcandidate_entity_ids"
    cand = {r.split("\t")[0]: set(x for x in r.split("\t")[1].split(",") if x) for r in cl[1:] if r}
    assert list(cand) == s1_ids
    seen = set()
    n_match = 0
    for sid, lst in rows:
        ids = [x for x in lst.split(",") if x]
        assert len(ids) == len(set(ids)) and all(x[:3] in ("S2-", "S3-") for x in ids)
        assert set(ids) <= cand[sid], sid
        assert not (set(ids) & seen), "one-parent rule violated"
        seen |= set(ids)
        n_match += bool(ids)
    assert cand[W["t1"][0][0]] == set() and rows[0][1] == ""  # no candidates -> empty row
    france = [r for r, s in zip(rows, W["t1"]) if s[3] == "France"]
    assert france and sum(bool(r[1]) for r in france) > 0, "unseen country must still get matches"
    summ = json.loads((out / "predict_summary.json").read_text())
    assert summ["validator_rc"] in (None, 0)
    # score against the synthetic test truth (sanity only)
    from src.metric import macro_f05, read_id_list_tsv

    pred = read_id_list_tsv(out / "matching_results.tsv")
    tr = {k: set(v) for k, v in W["tgt"].items()}
    fr = {k: v for k, v in tr.items() if any(s[0] == k and s[3] == "France" for s in W["t1"])}
    print(f"predict OK: {len(rows)} rows, {n_match} non-empty; synthetic test macro F0.5 {macro_f05(pred, tr):.4f} "
          f"(France {macro_f05(pred, fr):.4f}); validator rc {summ['validator_rc']}")


def test_matcher_smoke():
    d = Path(tempfile.mkdtemp(prefix="matcher_smoke_"))
    try:
        W = build_dataset(d)
        check_features(d, W)
        model_dir = check_train(d, W)
        check_predict(d, W, model_dir)
    finally:
        if os.environ.get("KEEP_SMOKE_DIR"):
            print(f"kept {d}")
        else:
            shutil.rmtree(d, ignore_errors=True)


if __name__ == "__main__":
    test_matcher_smoke()
    print("PASS test_matcher_smoke")