File size: 13,929 Bytes
3cd21f3
 
 
 
 
 
 
ef2c648
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2c648
 
 
 
 
 
 
 
 
 
3cd21f3
 
 
 
 
 
 
 
 
 
 
84602b6
 
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2c648
3cd21f3
ef2c648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2c648
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2c648
 
3cd21f3
 
 
 
 
 
 
 
ef2c648
 
 
 
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84602b6
 
 
 
 
 
 
 
3cd21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef2c648
3cd21f3
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Validate the UnsolvedMed (ulamai/UnsolvedMedical) dataset (v1.0.0 / v1.5.0 / v2.0.0) against:
  1. JSON Schemas in schemas/ (problem, source, status_event, relation, query_manifest)
  2. All 18 Publication Gates (Section 3)
  3. Exact category quotas (10,000 for v1.0, 15,000 for v1.5, 20,000 for v2.0 + 10% Gold Seed + 100 calibration audit)
  4. Portfolio & source diversity guardrails (Sections 12.6, 12.7, 12.8)
  5. Strict data hygiene: zero raw documents/excerpts, zero noisy case reports/protocols, and total repo footprint < 400 MB
"""

import json
import re
import sys
from collections import Counter
from pathlib import Path

from jsonschema import Draft202012Validator

ROOT = Path(__file__).resolve().parent.parent

BASE_CATEGORY_QUOTAS = {
    "oncology_and_hematology": 800,
    "cardiovascular_and_cerebrovascular_medicine": 600,
    "neurology": 600,
    "mental_health_behavioral_health_and_addiction": 600,
    "infectious_diseases_tropical_medicine_and_amr": 800,
    "respiratory_and_sleep_medicine": 400,
    "endocrine_metabolic_obesity_and_nutrition_medicine": 500,
    "gastroenterology_hepatology_and_pancreatic_disease": 400,
    "kidney_urinary_and_reproductive_urology": 360,
    "immunology_rheumatology_and_allergy": 440,
    "musculoskeletal_orthopedics_pain_and_dermatology": 400,
    "reproductive_maternal_and_womens_health": 500,
    "pediatrics_neonatology_and_adolescent_medicine": 500,
    "aging_geriatrics_dementia_and_palliative_medicine": 400,
    "surgery_anesthesia_critical_care_emergency_and_trauma": 500,
    "diagnostics_imaging_pathology_laboratory_and_genomic_medicine": 500,
    "prevention_primary_care_public_health_and_population_medicine": 500,
    "health_services_implementation_quality_and_patient_safety": 400,
    "rehabilitation_disability_sensory_oral_and_communication_health": 400,
    "rare_multisystem_and_undiagnosed_conditions": 400,
}

CLINICAL_ADVICE_PATTERNS = re.compile(
    r"\b(should i take|what ointment should i|by how many units per hour should i|my doctor|my symptoms)\b",
    re.I,
)

NOISE_PATTERNS = re.compile(
    r"\b(case report|a case of|two cases of|three cases of|case series|study protocol|protocol for|"
    r"trial protocol|corrigendum|erratum|retracted|retraction|comment on|reply to|author response|"
    r"letter to|editorial|book review|conference abstract|in mice|mouse model|murine model|"
    r"in rats|rat model|zebrafish|drosophila|in vitro|cell line)\b",
    re.I,
)

HTML_ENTITY_RE = re.compile(r"&(amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);", re.I)


def load_jsonl(path: Path) -> list[dict]:
    with path.open("r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def main() -> int:
    errors = []

    print("1. Loading schemas and dataset artifacts...")
    stats = json.loads((ROOT / "statistics.json").read_text(encoding="utf-8"))
    version = stats.get("version", "3.0.0")
    scale_factor = {"1.0.0": 1.0, "1.5.0": 1.5, "2.0.0": 2.0, "3.0.0": 2.0}.get(version, 2.0)
    expected_category_quotas = {k: int(round(v * scale_factor)) for k, v in BASE_CATEGORY_QUOTAS.items()}
    expected_total_published = sum(expected_category_quotas.values())
    expected_total_gold = expected_total_published // 10
    expected_total_all = expected_total_published + 100

    prob_schema = json.loads((ROOT / "schemas" / "problem.schema.json").read_text(encoding="utf-8"))
    src_schema = json.loads((ROOT / "schemas" / "source.schema.json").read_text(encoding="utf-8"))
    stat_schema = json.loads((ROOT / "schemas" / "status_event.schema.json").read_text(encoding="utf-8"))
    rel_schema = json.loads((ROOT / "schemas" / "relation.schema.json").read_text(encoding="utf-8"))
    qm_schema = json.loads((ROOT / "schemas" / "query_manifest.schema.json").read_text(encoding="utf-8"))

    prob_validator = Draft202012Validator(prob_schema)
    src_validator = Draft202012Validator(src_schema)
    stat_validator = Draft202012Validator(stat_schema)
    rel_validator = Draft202012Validator(rel_schema)
    qm_validator = Draft202012Validator(qm_schema)

    current_problems = json.loads((ROOT / "problems.json").read_text(encoding="utf-8"))
    gold_problems = load_jsonl(ROOT / "data" / "gold" / "problems.jsonl")
    archived_problems = load_jsonl(ROOT / "data" / "archived" / "problems.jsonl")
    all_problems = current_problems + archived_problems
    dataset_bundle = json.loads((ROOT / "dataset.json").read_text(encoding="utf-8"))
    if len(dataset_bundle.get("problems", [])) != expected_total_all:
        errors.append(f"dataset.json problems count {len(dataset_bundle.get('problems', []))} != {expected_total_all}")
    sources = json.loads((ROOT / "source_registry.json").read_text(encoding="utf-8"))
    relations = load_jsonl(ROOT / "relations" / "relations.jsonl")
    status_events = load_jsonl(ROOT / "history" / "status_events.jsonl")

    if (ROOT / "raw").exists():
        errors.append("Raw directory `raw/` should not exist in the published repository")

    total_bytes = sum(
        f.stat().st_size for f in ROOT.rglob("*") if f.is_file() and ".git" not in f.parts
    )
    total_mb = total_bytes / (1024 * 1024)
    print(f"   Total repository footprint (excluding .git): {total_mb:.1f} MB")
    if total_mb >= 400.0:
        errors.append(f"Total repository size {total_mb:.1f} MB exceeds the 400 MB limit")

    if len(current_problems) != expected_total_published:
        errors.append(f"Expected {expected_total_published} current problems, found {len(current_problems)}")
    if len(gold_problems) != expected_total_gold:
        errors.append(f"Expected {expected_total_gold} gold problems, found {len(gold_problems)}")
    if len(all_problems) != expected_total_all:
        errors.append(f"Expected {expected_total_all} total records, found {len(all_problems)}")

    print("2. Validating JSON Schemas across all records, sources, status events, relations, and query manifests...")
    for r in all_problems:
        for err in prob_validator.iter_errors(r):
            errors.append(f"Problem {r.get('id')} schema error: {err.message}")
            if len(errors) > 50:
                break

    source_ids = set()
    for s in sources:
        source_ids.add(s["source_id"])
        for err in src_validator.iter_errors(s):
            errors.append(f"Source {s.get('source_id')} schema error: {err.message}")

    for ev in status_events:
        for err in stat_validator.iter_errors(ev):
            errors.append(f"Status event {ev.get('event_id')} schema error: {err.message}")

    all_ids = {r["id"] for r in all_problems}
    for rel in relations:
        for err in rel_validator.iter_errors(rel):
            errors.append(f"Relation {rel.get('relation_id')} schema error: {err.message}")
        if rel["subject_id"] not in all_ids:
            errors.append(f"Relation {rel['relation_id']} has unknown subject_id {rel['subject_id']}")
        if rel["object_id"].startswith("UMED-") and rel["object_id"] not in all_ids:
            errors.append(f"Relation {rel['relation_id']} has unknown object_id {rel['object_id']}")

    qm_files = sorted((ROOT / "sources" / "query_manifests").glob("MEDQ-*.yaml"))
    if not qm_files:
        errors.append("No query manifests found in sources/query_manifests/")
    import yaml
    for qf in qm_files:
        qdata = yaml.safe_load(qf.read_text(encoding="utf-8"))
        for err in qm_validator.iter_errors(qdata):
            errors.append(f"Query manifest {qf.name} schema error: {err.message}")

    print("3. Checking category allocations, Gold Seed quotas, data hygiene, and 18 Publication Gates...")
    cat_counts = Counter(r["category_id"] for r in current_problems)
    gold_cat_counts = Counter(r["category_id"] for r in gold_problems)
    for slug, expected in expected_category_quotas.items():
        if cat_counts[slug] != expected:
            errors.append(f"Category {slug}: expected {expected} current problems, got {cat_counts[slug]}")
        if gold_cat_counts[slug] != expected // 10:
            errors.append(f"Category {slug} Gold Seed: expected {expected // 10}, got {gold_cat_counts[slug]}")

    seen_titles = set()
    seen_stmts = set()
    origin_source_counts = Counter()
    any_source_counts = Counter()

    for r in current_problems:
        if not r["published"]:
            errors.append(f"{r['id']} in current_problems has published=False")
        if r["original_statement"] is not None:
            errors.append(f"{r['id']} stores raw excerpt in original_statement instead of None")
        if r["publication_class"] not in ("OPEN-VERIFIED", "PARTIAL-PROGRESS", "DISPUTED-OPEN", "BLOCKED-OPEN"):
            errors.append(f"{r['id']} has invalid current publication_class {r['publication_class']}")
        if r["status"] not in ("open", "partially_resolved", "contested"):
            errors.append(f"{r['id']} has invalid current status {r['status']}")
        if not r["statement"].endswith("?"):
            errors.append(f"{r['id']} statement does not end with '?'")
        if CLINICAL_ADVICE_PATTERNS.search(r["statement"]):
            errors.append(f"{r['id']} statement contains clinical advice pattern")
        if NOISE_PATTERNS.search(r["title"]) or NOISE_PATTERNS.search(r["statement"]):
            errors.append(f"{r['id']} contains noisy non-research pattern in title or statement")
        if HTML_ENTITY_RE.search(r["title"]) or HTML_ENTITY_RE.search(r["statement"]):
            errors.append(f"{r['id']} contains unescaped HTML entity in title or statement")
        if not all(r["statement_audit"][k] for k in ("self_contained", "atomic", "medical_research_question", "does_not_imply_clinical_advice")):
            errors.append(f"{r['id']} failed statement_audit booleans")
        if r["rights"]["contains_extended_source_text"]:
            errors.append(f"{r['id']} contains extended source text")
        if r["responsible_release"]["contains_personal_data"]:
            errors.append(f"{r['id']} contains personal data")
        for w in r["why_open"]:
            if w.strip().lower() in ("more research is needed", "more research is needed."):
                errors.append(f"{r['id']} has generic why_open")

        t_norm = r["title"].lower().strip()
        s_norm = r["statement"].lower().strip()
        if t_norm in seen_titles:
            errors.append(f"Duplicate title in current_problems: {r['id']}")
        if s_norm in seen_stmts:
            errors.append(f"Duplicate statement in current_problems: {r['id']}")
        seen_titles.add(t_norm)
        seen_stmts.add(s_norm)

        min_sources = 5 if version == "3.0.0" else 4
        if len(r["source_support"]) < min_sources:
            errors.append(f"{r['id']} has fewer than {min_sources} sources in source_support ({len(r['source_support'])})")
        lit_sids = [
            ss["source_id"]
            for ss in r["source_support"]
            if not ss["source_id"].startswith("SRC-MED-ANC-") and not ss["source_id"].startswith("SRC-MED-NCT-")
        ]
        if len(set(lit_sids)) < 3:
            errors.append(f"{r['id']} has fewer than 3 distinct peer-reviewed literature papers ({len(set(lit_sids))})")
        for ss in r["source_support"]:
            if ss["source_id"] not in source_ids:
                errors.append(f"{r['id']} references unknown source_id {ss['source_id']}")
            any_source_counts[ss["source_id"]] += 1
            if ss["role"] == "problem_origin":
                origin_source_counts[ss["source_id"]] += 1

    print("4. Checking portfolio & source diversity guardrails (Sections 12.6 & 12.7)...")
    qtype_counts = Counter(r["question_type"] for r in current_problems)
    n_total = len(current_problems)
    for qt, cnt in qtype_counts.items():
        if cnt / n_total > 0.30:
            errors.append(f"Question type {qt} exceeds 30% guardrail: {cnt / n_total:.2%}")

    etio_share = sum(qtype_counts[q] for q in ("etiology", "mechanism", "natural_history")) / n_total
    diag_share = sum(qtype_counts[q] for q in ("diagnosis", "screening", "prognosis", "classification", "measurement")) / n_total
    safe_share = sum(qtype_counts[q] for q in ("safety", "supportive_palliative", "rehabilitation", "patient_experience")) / n_total
    impl_share = sum(qtype_counts[q] for q in ("implementation", "health_services", "public_health")) / n_total

    for label, share in [
        ("Etiology/Mechanism/Natural History", etio_share),
        ("Diagnosis/Screening/Prognosis/Classification/Measurement", diag_share),
        ("Safety/Supportive/Rehab/Patient Experience", safe_share),
        ("Implementation/Health Services/Public Health", impl_share),
    ]:
        if share < 0.10:
            errors.append(f"Portfolio guardrail failed: {label} share is {share:.2%} (< 10%)")

    max_origin = max(origin_source_counts.values()) if origin_source_counts else 0
    max_any = max(any_source_counts.values()) if any_source_counts else 0
    if max_origin > 50:
        errors.append(f"Source diversity guardrail failed: max problem_origin records per source is {max_origin} (> 50)")
    if max_any > 50:
        errors.append(f"Source diversity guardrail failed: max total records per source in any role is {max_any} (> 50)")

    if errors:
        print(f"VALIDATION FAILED with {len(errors)} errors:")
        for e in errors[:25]:
            print("  -", e)
        return 1

    print(
        f"ALL VALIDATION CHECKS PASSED (0 errors)! "
        f"Verified {len(current_problems)} published problems ({len(gold_problems)} Gold Seed), "
        f"{len(all_problems) - len(current_problems)} calibration audit records, "
        f"{len(sources)} sources (max origin={max_origin}, max any role={max_any}), "
        f"{len(relations)} relations, and total size {total_mb:.1f} MB (< 400 MB)."
    )
    return 0


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