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
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
#!/usr/bin/env python3
"""
IRexp release_check.py — DoR integrity asserts for Sci Data Hub patch.

Skeleton + runnable checks against local jsonl.gz mirrors.
Default root: /workspace/irexp-opus4/data (Hub rev used for inventory).
After a patch build, point --data-dir at the patched out/ directory.

Usage:
  python3 release_check.py
  python3 release_check.py --data-dir /workspace/irexp-opus4/out
  python3 release_check.py --expect-commercial-n 88519  # post-lt3 drop, pre-ND
"""

from __future__ import annotations

import argparse
import gzip
import json
import sys
from collections import Counter
from pathlib import Path
from typing import Any, Iterable

BAND_KEY = "ir_bands_cm-1"
OLD_KEY = "ir_bands_old_cm-1"
BAND_LO, BAND_HI = 350.0, 4000.0
MIN_BANDS = 3

CORE_KEYS = {
    "id",
    BAND_KEY,
    "ir_source",
    "h_nmr",
    "c_nmr",
    "smiles",
    "selfies",
    "inchikey",
    "has_structure",
    "source_doi",
    "license",
    "license_raw",
    "license_pool",
    "license_source",
}
# pmcid required on PMC-derived pools; Chemotion SA uses `source` instead (schema note).
PMC_POOLS_REQUIRE_PMCID = {"commercial", "non_commercial", "resolved_commercial", "train_no_bench_commercial"}

# Documented (Table-1-adjacent) audit / QC fields — prefer keep + document
COMMERCIAL_DOC_FIELDS = {
    OLD_KEY,
    "ir_shared_in_paper",
    "ir_table_flatten_suspect",
    "ir_refetch_confirmed",
    "ir_refetch_merged",
}

# Hypervalent I–O exception ids observed on rev 50d6155 (has_structure=False ∧ smiles).
# Recompute / refresh if the set changes; empty set means enforce strict equivalence.
KNOWN_HS_FALSE_WITH_SMILES: set[str] = set()  # cleared after has_structure flip (presubmit)


def load_jsonl_gz(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with gzip.open(path, "rt", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def bands(row: dict[str, Any]) -> list[float]:
    b = row.get(BAND_KEY)
    if not b:
        return []
    return [float(x) for x in b]


def nonempty_smiles(row: dict[str, Any]) -> bool:
    s = row.get("smiles")
    return s is not None and str(s).strip() != ""


def int_bands(vals: Iterable[float]) -> list[int]:
    return [int(round(float(x))) for x in vals]


def order_unique_ints(vals: Iterable[float]) -> list[int]:
    out: list[int] = []
    seen: set[int] = set()
    for v in int_bands(vals):
        if v not in seen:
            seen.add(v)
            out.append(v)
    return out


class Checker:
    def __init__(self) -> None:
        self.failures: list[str] = []
        self.warnings: list[str] = []

    def check(self, cond: bool, msg: str) -> None:
        if not cond:
            self.failures.append(msg)

    def warn(self, cond: bool, msg: str) -> None:
        if not cond:
            self.warnings.append(msg)

    def section(self, title: str) -> None:
        print(f"\n== {title} ==")


def assert_ge3_bands(ck: Checker, name: str, rows: list[dict]) -> None:
    bad = [r["id"] for r in rows if len(bands(r)) < MIN_BANDS]
    ck.check(len(bad) == 0, f"{name}: {len(bad)} rows with len(bands)<{MIN_BANDS} e.g. {bad[:5]}")


def assert_band_range(ck: Checker, name: str, rows: list[dict]) -> None:
    bad = []
    for r in rows:
        for v in bands(r):
            if v < BAND_LO or v > BAND_HI:
                bad.append((r["id"], v))
                break
    ck.check(len(bad) == 0, f"{name}: {len(bad)} rows with bands outside [{BAND_LO},{BAND_HI}] e.g. {bad[:5]}")


def assert_no_dup_int_bands(ck: Checker, name: str, rows: list[dict]) -> None:
    bad = []
    for r in rows:
        ib = int_bands(bands(r))
        if len(ib) != len(set(ib)):
            bad.append(r["id"])
    ck.check(len(bad) == 0, f"{name}: {len(bad)} rows with duplicate integer bands e.g. {bad[:5]}")


def assert_has_structure_smiles(
    ck: Checker,
    name: str,
    rows: list[dict],
    allow_exceptions: set[str] | None = None,
) -> None:
    """has_structure ⇔ nonempty smiles, with optional documented exceptions."""
    allow = allow_exceptions or set()
    true_no_smiles = []
    false_with_smiles = []
    for r in rows:
        hs = r.get("has_structure")
        sm = nonempty_smiles(r)
        rid = r.get("id")
        if hs is True and not sm:
            true_no_smiles.append(rid)
        if hs is False and sm and rid not in allow:
            false_with_smiles.append(rid)
        if hs is False and sm and rid in allow:
            pass  # documented exception
        if hs not in (True, False):
            ck.check(False, f"{name}: non-bool has_structure on {rid}: {hs!r}")
    ck.check(
        len(true_no_smiles) == 0,
        f"{name}: {len(true_no_smiles)} has_structure=True without smiles e.g. {true_no_smiles[:5]}",
    )
    ck.check(
        len(false_with_smiles) == 0,
        f"{name}: {len(false_with_smiles)} has_structure=False with smiles "
        f"(not in exception set) e.g. {false_with_smiles[:5]}",
    )


def assert_unique_ids(ck: Checker, name: str, rows: list[dict]) -> None:
    ids = [r["id"] for r in rows]
    ck.check(len(ids) == len(set(ids)), f"{name}: duplicate ids within file ({len(ids)-len(set(ids))})")


def assert_core_schema(ck: Checker, name: str, rows: list[dict]) -> None:
    if not rows:
        ck.check(False, f"{name}: empty file")
        return
    # Every row must have core keys (presence; nulls allowed where meaningful)
    missing_counts = Counter()
    for r in rows:
        for k in CORE_KEYS:
            if k not in r:
                missing_counts[k] += 1
    ck.check(
        len(missing_counts) == 0,
        f"{name}: core keys missing on some rows: {dict(missing_counts)}",
    )


def assert_commercial_doc_fields(ck: Checker, rows: list[dict], require_dense_refetch: bool) -> None:
    """Documented fields: old bands always present; refetch preferably dense bools."""
    missing_old = sum(1 for r in rows if OLD_KEY not in r)
    ck.check(missing_old == 0, f"commercial: {missing_old} rows missing {OLD_KEY}")
    if require_dense_refetch:
        for field in ("ir_refetch_confirmed", "ir_refetch_merged"):
            missing = sum(1 for r in rows if field not in r)
            ck.check(
                missing == 0,
                f"commercial: {missing} rows missing dense {field} "
                f"(normalize absent→False before Hub patch)",
            )
    else:
        # Soft note for live Hub (sparse refetch)
        sparse_c = sum(1 for r in rows if "ir_refetch_confirmed" not in r)
        sparse_m = sum(1 for r in rows if "ir_refetch_merged" not in r)
        if sparse_c or sparse_m:
            ck.warn(
                False,
                f"commercial: refetch fields sparse "
                f"(confirmed missing={sparse_c}, merged missing={sparse_m}); "
                f"densify on next Hub patch",
            )


def assert_subset(ck: Checker, child: str, parent: str, child_ids: set[str], parent_ids: set[str]) -> None:
    extra = child_ids - parent_ids
    ck.check(len(extra) == 0, f"{child} ⊈ {parent}: {len(extra)} ids e.g. {list(extra)[:5]}")


def assert_disjoint(ck: Checker, a: str, b: str, a_ids: set[str], b_ids: set[str]) -> None:
    inter = a_ids & b_ids
    ck.check(len(inter) == 0, f"{a} ∩ {b} nonempty: {len(inter)} e.g. {list(inter)[:5]}")


def assert_resolved_equals_smiles(
    ck: Checker,
    commercial: list[dict],
    resolved_ids: set[str],
) -> None:
    """After rebuild: resolved ids == commercial ids with nonempty smiles."""
    expected = {r["id"] for r in commercial if nonempty_smiles(r)}
    only_exp = expected - resolved_ids
    only_res = resolved_ids - expected
    ck.check(
        len(only_exp) == 0 and len(only_res) == 0,
        f"resolved ≠ commercial∩smiles: missing_from_resolved={len(only_exp)} "
        f"extra_in_resolved={len(only_res)} (sample miss {list(only_exp)[:3]})",
    )


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument(
        "--data-dir",
        type=Path,
        default=Path("/workspace/irexp-opus4/data"),
        help="Directory with irexp_*.jsonl.gz",
    )
    ap.add_argument(
        "--expect-commercial-n",
        type=int,
        default=None,
        help="If set, assert commercial row count equals this (e.g. 88519 after lt3 drop)",
    )
    ap.add_argument(
        "--strict-resolved-smiles",
        action="store_true",
        help="Assert resolved == commercial∩smiles (enable after rebuild)",
    )
    ap.add_argument(
        "--require-dense-refetch",
        action="store_true",
        help="Assert ir_refetch_* present on every commercial row",
    )
    ap.add_argument(
        "--allow-live-defects",
        action="store_true",
        help="Warn instead of fail on known live Hub defects (lt3, dups, resolved sync)",
    )
    args = ap.parse_args()
    d = args.data_dir
    ck = Checker()

    files = {
        "commercial": d / "irexp_commercial.jsonl.gz",
        "non_commercial": d / "irexp_non_commercial.jsonl.gz",
        "sharealike": d / "irexp_sharealike.jsonl.gz",
        "resolved_commercial": d / "irexp_resolved_commercial.jsonl.gz",
        "train_no_bench_commercial": d / "train_no_bench_commercial.jsonl.gz",
    }
    for name, path in files.items():
        ck.check(path.is_file(), f"missing file: {path}")
    if ck.failures:
        for f in ck.failures:
            print("FAIL:", f)
        return 1

    data = {name: load_jsonl_gz(path) for name, path in files.items()}
    ids = {name: {r["id"] for r in rows} for name, rows in data.items()}

    print(f"data-dir: {d}")
    for name, rows in data.items():
        print(f"  {name}: n={len(rows)}")

    # --- counts ---
    ck.section("counts")
    if args.expect_commercial_n is not None:
        ck.check(
            len(data["commercial"]) == args.expect_commercial_n,
            f"commercial n={len(data['commercial'])} != expect {args.expect_commercial_n}",
        )

    # --- per-file quality ---
    for name, rows in data.items():
        ck.section(f"quality:{name}")
        assert_unique_ids(ck, name, rows)
        assert_core_schema(ck, name, rows)
        if name in PMC_POOLS_REQUIRE_PMCID:
            missing_pmcid = sum(1 for r in rows if "pmcid" not in r)
            ck.check(missing_pmcid == 0, f"{name}: {missing_pmcid} rows missing pmcid")
        if name == "sharealike":
            # Chemotion rows: source present, pmcid often absent; PMC SA: pmcid present
            no_prov = [
                r["id"] for r in rows
                if not r.get("pmcid") and not r.get("source")
            ]
            ck.check(len(no_prov) == 0, f"sharealike: {len(no_prov)} rows lack both pmcid and source")

        if args.allow_live_defects and name in {
            "commercial",
            "resolved_commercial",
            "train_no_bench_commercial",
            "non_commercial",
        }:
            # Report live defects as warnings
            n_lt3 = sum(1 for r in rows if len(bands(r)) < MIN_BANDS)
            n_dup = sum(1 for r in rows if len(int_bands(bands(r))) != len(set(int_bands(bands(r)))))
            if n_lt3:
                ck.warn(False, f"{name}: LIVE defect len<3: {n_lt3}")
            if n_dup:
                ck.warn(False, f"{name}: LIVE defect dup-int bands: {n_dup}")
            assert_band_range(ck, name, rows)
        else:
            assert_ge3_bands(ck, name, rows)
            assert_band_range(ck, name, rows)
            assert_no_dup_int_bands(ck, name, rows)

        allow = KNOWN_HS_FALSE_WITH_SMILES if name.startswith(
            ("commercial", "resolved", "train_no_bench")
        ) or name in {"commercial", "resolved_commercial", "train_no_bench_commercial"} else set()
        # Apply exceptions only to commercial family
        if name in {"commercial", "resolved_commercial", "train_no_bench_commercial"}:
            assert_has_structure_smiles(ck, name, rows, allow_exceptions=KNOWN_HS_FALSE_WITH_SMILES)
        else:
            assert_has_structure_smiles(ck, name, rows, allow_exceptions=set())

    # --- commercial documentation fields ---
    ck.section("commercial documented fields")
    assert_commercial_doc_fields(
        ck, data["commercial"], require_dense_refetch=args.require_dense_refetch
    )
    # Schema notes (non-fatal): companions lack audit columns
    for name in ("non_commercial", "sharealike"):
        for field in ("ir_bands_old_cm-1", "ir_shared_in_paper", "ir_table_flatten_suspect"):
            if any(field in r for r in data[name]):
                continue
            ck.warn(False, f"schema note: {name} lacks optional field {field} (document or align)")

    # --- cross-file relations ---
    ck.section("subset / disjoint")
    assert_disjoint(ck, "commercial", "non_commercial", ids["commercial"], ids["non_commercial"])
    assert_disjoint(ck, "commercial", "sharealike", ids["commercial"], ids["sharealike"])
    assert_disjoint(ck, "non_commercial", "sharealike", ids["non_commercial"], ids["sharealike"])
    assert_subset(
        ck, "resolved_commercial", "commercial", ids["resolved_commercial"], ids["commercial"]
    )
    assert_subset(
        ck,
        "train_no_bench_commercial",
        "resolved_commercial",
        ids["train_no_bench_commercial"],
        ids["resolved_commercial"],
    )

    if args.strict_resolved_smiles:
        assert_resolved_equals_smiles(ck, data["commercial"], ids["resolved_commercial"])
    else:
        # Live Hub: 364 hs/smiles missing from resolved — warn
        expected = {r["id"] for r in data["commercial"] if nonempty_smiles(r)}
        miss = expected - ids["resolved_commercial"]
        if miss:
            ck.warn(
                False,
                f"resolved sync: {len(miss)} commercial smiles rows not in resolved "
                f"(enable --strict-resolved-smiles after rebuild)",
            )

    # train_no_bench delta should be benchmark holdout (informational)
    held = ids["resolved_commercial"] - ids["train_no_bench_commercial"]
    print(f"\nresolved − train_no_bench: {len(held)} (expect benchmark IK14 holdout)")

    # --- summary ---
    print("\n== SUMMARY ==")
    for w in ck.warnings:
        print("WARN:", w)
    if ck.failures:
        for f in ck.failures:
            print("FAIL:", f)
        print(f"\nFAILED with {len(ck.failures)} assertion(s), {len(ck.warnings)} warning(s)")
        return 1
    print(f"PASSED with {len(ck.warnings)} warning(s)")
    return 0


if __name__ == "__main__":
    sys.exit(main())