#!/usr/bin/env python3 """Validate a cascade package against specification v0.1. Usage: python validate_package.py PACKAGE_DIR [--schema cascade_package.schema.json] [--report report.json] [--max-messages 20] Exit code 0 if there are no errors (warnings are allowed), 1 otherwise. Requires: pip install jsonschema """ import argparse import calendar import collections import datetime import gzip import hashlib import json import os import re import sys try: import jsonschema except ImportError: # pragma: no cover sys.exit("This validator needs the jsonschema package: pip install jsonschema") PRECISIONS = ["second", "minute", "hour", "day", "month", "year"] LAG_UNIT_SECONDS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400, "year": 31557600} CORE_ROLES = {"anchor", "source", "target", "participant"} CORE_FLAGS = { "time_imputed", "time_coarse", "title_garbled", "low_confidence", "duplicate_merged", "unassessed", "same_owner", "coordinated", "propagation_override", } FILES = { "events": ("events.jsonl", True), "entities": ("entities.jsonl", True), "entity_relations": ("entity_relations.jsonl", False), "links": ("links.jsonl", True), "omitted": ("omitted.jsonl", False), } PII_PATTERNS = [ (re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "e-mail address"), (re.compile(r"(?i)\b(password|passwd|api[_-]?key|secret|token)\s*[=:]\s*\S+"), "possible credential"), (re.compile(r"(? self.max_messages: print(f" ... {len(msgs) - self.max_messages} more") ne = sum(len(v) for v in self.errors.values()) nw = sum(len(v) for v in self.warnings.values()) print(f"\n{ne} error(s), {nw} warning(s)") def open_maybe_gz(path): if os.path.exists(path): return open(path, "rb") if os.path.exists(path + ".gz"): return gzip.open(path + ".gz", "rb") return None def read_jsonl(pkg, name, report): path = os.path.join(pkg, name) fh = open_maybe_gz(path) if fh is None: return None, None records, raw = [], hashlib.sha256() with fh: for n, line in enumerate(fh, 1): raw.update(line) line = line.strip() if not line: continue try: records.append((n, json.loads(line.decode("utf-8")))) except Exception as exc: # noqa: BLE001 report.error("json", f"{name} line {n}: {exc}") return records, raw.hexdigest() def parse_time(s): return datetime.datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S").replace( tzinfo=datetime.timezone.utc ) + datetime.timedelta(seconds=float("0" + s[19:-1]) if len(s) > 20 else 0) def epoch(s): dt = parse_time(s) return calendar.timegm(dt.timetuple()) + dt.microsecond / 1e6 def truncate(s, precision): d = s[:19] cut = {"year": 4, "month": 7, "day": 10, "hour": 13, "minute": 16, "second": 19}[precision] return d[:cut] def coarser(p, q): return p if PRECISIONS.index(p) >= PRECISIONS.index(q) else q def simultaneous(ev_a, ev_b): pa, pb = ev_a["time"]["precision"], ev_b["time"]["precision"] p = coarser(pa, pb) return truncate(ev_a["time"]["start"], p) == truncate(ev_b["time"]["start"], p) def scan_text_for_pii(obj, where, report): text = json.dumps(obj, ensure_ascii=False) for pat, label in PII_PATTERNS: m = pat.search(text) if m: report.warn("pii", f"{where}: {label} found ({m.group(0)[:40]})") def validate_schema(records, definition, schema, name, report): wrapper = {"$schema": schema["$schema"], "$defs": schema["$defs"], "$ref": f"#/$defs/{definition}"} validator = jsonschema.Draft202012Validator(wrapper) bad = 0 for n, rec in records: for err in validator.iter_errors(rec): bad += 1 path = "/".join(str(p) for p in err.absolute_path) report.error("schema", f"{name} line {n} {path}: {err.message[:160]}") break return bad def tarjan_scc(nodes, adj): """Iterative Tarjan; returns list of components.""" index, low, on, stack, comps, idx = {}, {}, set(), [], [], [0] for root in nodes: if root in index: continue work = [(root, iter(adj.get(root, ())))] index[root] = low[root] = idx[0] idx[0] += 1 stack.append(root) on.add(root) while work: v, it = work[-1] advanced = False for w in it: if w not in index: index[w] = low[w] = idx[0] idx[0] += 1 stack.append(w) on.add(w) work.append((w, iter(adj.get(w, ())))) advanced = True break if w in on: low[v] = min(low[v], index[w]) if advanced: continue work.pop() if work: low[work[-1][0]] = min(low[work[-1][0]], low[v]) if low[v] == index[v]: comp = [] while True: w = stack.pop() on.discard(w) comp.append(w) if w == v: break comps.append(comp) return comps def main(): ap = argparse.ArgumentParser() ap.add_argument("package") ap.add_argument("--schema", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascade_package.schema.json")) ap.add_argument("--report") ap.add_argument("--max-messages", type=int, default=20) args = ap.parse_args() rep = Report(args.max_messages) schema = json.load(open(args.schema, encoding="utf-8")) # ---- manifest ------------------------------------------------------- mpath = os.path.join(args.package, "manifest.json") if not os.path.exists(mpath): rep.error("files", "manifest.json is missing") rep.print() return 1 manifest = json.load(open(mpath, encoding="utf-8")) validate_schema([(0, manifest)], "manifest", schema, "manifest.json", rep) # ---- read files ----------------------------------------------------- data, hashes = {}, {} for key, (fname, required) in FILES.items(): recs, digest = read_jsonl(args.package, fname, rep) if recs is None: if required: rep.error("files", f"{fname} is missing") data[key], hashes[key] = [], None else: data[key], hashes[key] = recs, digest defs = {"events": "event", "entities": "entity", "entity_relations": "entity_relation", "links": "link", "omitted": "omitted"} for key, definition in defs.items(): validate_schema(data[key], definition, schema, FILES[key][0], rep) if rep.errors.get("schema") or rep.errors.get("json"): # structural problems make the cross-file checks unreliable rep.warn("skipped", "cross-file checks skipped because of schema or JSON errors") rep.print() return 1 events = {} for n, e in data["events"]: if e["id"] in events: rep.error("duplicate_id", f"events.jsonl line {n}: duplicate event id {e['id']}") events[e["id"]] = e entities = {} for n, e in data["entities"]: if e["id"] in entities: rep.error("duplicate_id", f"entities.jsonl line {n}: duplicate entity id {e['id']}") entities[e["id"]] = e links = {} for n, l in data["links"]: if l["id"] in links: rep.error("duplicate_id", f"links.jsonl line {n}: duplicate link id {l['id']}") links[l["id"]] = l # ---- vocabularies --------------------------------------------------- ev_kinds = {v["id"] for v in manifest["event_kinds"]} ent_types = {v["id"] for v in manifest["entity_types"]} rel_types = {v["id"] for v in manifest.get("entity_relation_types", [])} roles = CORE_ROLES | {v["id"] for v in manifest.get("roles", [])} lk = {k["id"]: k for k in manifest["link_kinds"]} bases = {v["id"] for v in manifest.get("evidence_bases", [])} rules = {r["id"] for r in manifest.get("rules", [])} judges = {j["id"]: j for j in manifest.get("judges", [])} flags_ok = CORE_FLAGS | {f["id"] for f in manifest.get("flags", [])} sources = {s["id"] for s in manifest["sources"]} def check_source_ids(items, where): for si in items: if si["source"] not in sources: rep.error("vocabulary", f"{where}: source '{si['source']}' is not declared in manifest.sources") # ---- entities ------------------------------------------------------- for n, e in data["entities"]: if e["type"] not in ent_types: rep.error("vocabulary", f"entity {e['id']}: type '{e['type']}' not declared") check_source_ids(e["provenance"]["source_ids"], f"entity {e['id']}") for n, r in data["entity_relations"]: for end in ("source", "target"): if r[end] not in entities: rep.error("reference", f"entity relation line {n}: {end} '{r[end]}' is not an entity") if r["type"] not in rel_types and r["type"] not in {"part_of", "adjacent_to", "depends_on", "member_of", "other"}: rep.error("vocabulary", f"entity relation line {n}: type '{r['type']}' not declared") # ---- events --------------------------------------------------------- referenced = set() first_ts, last_ts = None, None for n, e in data["events"]: eid = e["id"] if e["kind"] not in ev_kinds: rep.error("vocabulary", f"event {eid}: kind '{e['kind']}' not declared") anchors = [r for r in e["refs"] if r["role"] == "anchor"] if len(anchors) != 1: rep.error("anchor", f"event {eid}: needs exactly one anchor reference, found {len(anchors)}") for r in e["refs"]: if r["entity"] not in entities: rep.error("reference", f"event {eid}: entity '{r['entity']}' does not exist") else: referenced.add(r["entity"]) if r["role"] not in roles: rep.error("vocabulary", f"event {eid}: role '{r['role']}' not declared") t = e["time"] try: s_ep = epoch(t["start"]) except Exception: # noqa: BLE001 rep.error("time", f"event {eid}: start '{t['start']}' cannot be parsed") continue if t.get("end"): try: if epoch(t["end"]) < s_ep: rep.error("time", f"event {eid}: end is before start") except Exception: # noqa: BLE001 rep.error("time", f"event {eid}: end '{t['end']}' cannot be parsed") if t["basis"] == "imputed" and "time_imputed" not in e.get("flags", []): rep.warn("flags", f"event {eid}: time basis is imputed but flag time_imputed is missing") for f in e.get("flags", []): if f not in flags_ok: rep.error("vocabulary", f"event {eid}: flag '{f}' not declared in manifest.flags") check_source_ids(e["provenance"]["source_ids"], f"event {eid}") if not e["provenance"]["source_ids"]: rep.warn("provenance", f"event {eid}: no source ids") for rid in e["provenance"].get("extraction", {}).get("rule_ids", []): if rid not in rules: rep.error("vocabulary", f"event {eid}: rule '{rid}' not declared") scan_text_for_pii({"title": e["title"], "attrs": e.get("attrs", {})}, f"event {eid}", rep) first_ts = s_ep if first_ts is None else min(first_ts, s_ep) last_ts = s_ep if last_ts is None else max(last_ts, s_ep) # ids sorted? starts = [e["time"]["start"] for _, e in data["events"]] if starts != sorted(starts): rep.warn("order", "events.jsonl is not sorted by start time") # ---- observation window -------------------------------------------- ow = manifest["observation_window"] try: ws = epoch(ow["start"] if "T" in ow["start"] else ow["start"] + "T00:00:00Z") we = epoch(ow["end"] if "T" in ow["end"] else ow["end"] + "T23:59:59Z") if first_ts is not None and (first_ts < ws or last_ts > we): rep.warn("window", "some events lie outside manifest.observation_window") except Exception: # noqa: BLE001 rep.warn("window", "observation_window start or end is not an ISO date") # ---- links ---------------------------------------------------------- seen_pairs = collections.Counter() lag_total, lag_zero = collections.Counter(), collections.Counter() adj = collections.defaultdict(list) has_link = set() by_kind, by_level, by_relation, propagating = collections.Counter(), collections.Counter(), collections.Counter(), 0 for n, l in data["links"]: lid = l["id"] for end in ("from", "to"): if l[end] not in events: rep.error("reference", f"link {lid}: {end} '{l[end]}' is not an event") if l["from"] == l["to"]: rep.error("link", f"link {lid}: from and to are the same event") if l["from"] not in events or l["to"] not in events or l["from"] == l["to"]: continue a, b = events[l["from"]], events[l["to"]] k = lk.get(l["kind"]) # lag: explicit lag_seconds, else the kind's declared attribute, else the timestamp gap lag = l["gap_seconds"] spec = (k or {}).get("lag", {}) mapped = None if spec.get("source") == "attr": val = l.get("attrs", {}).get(spec["attr"]) if isinstance(val, (int, float)) and not isinstance(val, bool) and val >= 0: mapped = val * LAG_UNIT_SECONDS[spec["unit"]] else: rep.error("lag", f"link {lid}: kind '{l['kind']}' takes its lag from attrs.{spec['attr']}, which is missing or not a non-negative number") if "lag_seconds" in l: lag = l["lag_seconds"] if mapped is not None and abs(mapped - lag) > 1.0: rep.warn("lag", f"link {lid}: lag_seconds differs from the lag mapped from attrs.{spec['attr']}") elif mapped is not None: lag = mapped lag_total[l["kind"]] += 1 if spec.get("source", "timestamp") == "timestamp" and l["gap_seconds"] == 0 and "lag_seconds" not in l: lag_zero[l["kind"]] += 1 if k is None: rep.error("vocabulary", f"link {lid}: kind '{l['kind']}' not declared in manifest.link_kinds") else: rels = {r["id"]: r for r in k.get("relations", [])} if "relation" in l: if l["relation"] not in rels: rep.error("vocabulary", f"link {lid}: relation '{l['relation']}' not declared for kind '{l['kind']}'") default = rels.get(l["relation"], {}).get("propagates_default", k["propagates_default"]) else: default = k["propagates_default"] if l["propagates"] != default and "propagation_override" not in l.get("flags", []): rep.warn("propagation", f"link {lid}: propagates={l['propagates']} differs from the declared default; add flag propagation_override with a reason in attrs") if k["max_gap_seconds"] is not None and lag > k["max_gap_seconds"]: rep.error("window", f"link {lid}: lag {lag:.0f} s exceeds max_gap_seconds of kind '{l['kind']}'") if k["default_window_seconds"] is not None and k["max_gap_seconds"] is not None and k["default_window_seconds"] > k["max_gap_seconds"]: rep.error("window", f"kind '{l['kind']}': default_window_seconds is larger than max_gap_seconds") if l["evidence"]["existence"]["level"] not in k["levels"]: rep.warn("evidence", f"link {lid}: existence level '{l['evidence']['existence']['level']}' is not listed for kind '{l['kind']}'") sim = simultaneous(a, b) gap = epoch(b["time"]["start"]) - epoch(a["time"]["start"]) if not sim and gap < 0: rep.error("time_order", f"link {lid}: points backwards in time ({a['time']['start']} to {b['time']['start']}); list it in omitted.jsonl") elif sim and l["direction"] != "evidence": rep.error("tie_rule", f"link {lid}: events are simultaneous at the coarser precision, direction must be 'evidence'") elif l["direction"] == "evidence" and not sim: rep.warn("direction", f"link {lid}: direction 'evidence' used although the events are not simultaneous") if abs(gap - l["gap_seconds"]) > 1.0 and not (sim and gap < 0): rep.error("gap", f"link {lid}: gap_seconds {l['gap_seconds']} differs from the event times ({gap:.0f} s)") for part in ("existence", "relation"): item = l["evidence"].get(part) if not item: continue if item["basis"] not in bases: rep.error("vocabulary", f"link {lid}: evidence basis '{item['basis']}' not declared in manifest.evidence_bases") if item["level"] == "rule" and item.get("rule_id") not in rules: rep.error("vocabulary", f"link {lid}: rule '{item.get('rule_id')}' not declared in manifest.rules") if item["level"] == "judged": j = item["judge"] if j["id"] not in judges: rep.error("vocabulary", f"link {lid}: judge '{j['id']}' not declared in manifest.judges") if j["type"] == "unspecified": rep.warn("judge", f"link {lid}: judge type is unspecified") if item.get("text", "").rstrip().endswith("\u2026"): rep.warn("truncated_evidence", f"link {lid}: evidence text looks truncated (ends with an ellipsis)") if "source_ref" in item and item["source_ref"]["source"] not in sources: rep.error("vocabulary", f"link {lid}: source '{item['source_ref']['source']}' not declared") for f in l.get("flags", []): if f not in flags_ok: rep.error("vocabulary", f"link {lid}: flag '{f}' not declared in manifest.flags") if "relation" not in l and "unassessed" not in l.get("flags", []) and l["evidence"].get("relation") is None and k and k.get("relations"): rep.warn("relation", f"link {lid}: kind '{l['kind']}' has relations but the link has none; add flag unassessed if it was not judged") key = (l["from"], l["to"], l["kind"], l.get("relation")) seen_pairs[key] += 1 if seen_pairs[key] == 2: rep.error("duplicate_link", f"link {lid}: duplicate of an earlier link {key}") has_link.update((l["from"], l["to"])) by_kind[l["kind"]] += 1 by_level[l["evidence"]["existence"]["level"]] += 1 if "relation" in l: by_relation[l["relation"]] += 1 if l["propagates"]: propagating += 1 adj[l["from"]].append(l["to"]) scan_text_for_pii({"text": [i.get("text", "") for i in l["evidence"].values() if i]}, f"link {lid}", rep) for kind, total in lag_total.items(): kk = lk.get(kind) if kk and kk.get("lag", {}).get("source", "timestamp") == "timestamp" and kk["default_window_seconds"] is not None and total and lag_zero[kind] / total >= 0.95: rep.warn("lag_uninformative", f"kind '{kind}': {lag_zero[kind] / total:.0%} of its links have a zero timestamp gap, so its window cannot act; declare a lag source") # ---- attribute roles and the meaning of time --------------------------- if "time_meaning" not in manifest["domain"]: rep.warn("time_meaning", "manifest.domain.time_meaning is missing: state what the event time stands for") attr_keys = {"event": set(), "entity": set(), "link": set()} for _, e in data["events"]: attr_keys["event"].update(e.get("attrs", {})) for _, e in data["entities"]: attr_keys["entity"].update(e.get("attrs", {})) for _, l in data["links"]: attr_keys["link"].update(l.get("attrs", {})) role_ids = set() for r in manifest.get("attribute_roles", []): if r["id"] in role_ids: rep.error("attribute_role", f"attribute role id '{r['id']}' is used twice") role_ids.add(r["id"]) names = [r["attr"]] if isinstance(r["attr"], str) else r["attr"] for nm in names: if nm not in attr_keys[r["applies_to"]]: rep.error("attribute_role", f"attribute role '{r['id']}': no {r['applies_to']} has the attribute '{nm}'") if r["role"] == "position" and len(names) not in (1, 2): rep.error("attribute_role", f"attribute role '{r['id']}': a position names one attribute (coordinates object) or two (lat, lon)") if r["role"] == "time_of_day": try: from zoneinfo import ZoneInfo ZoneInfo(r["time_zone"]) except Exception: # noqa: BLE001 rep.warn("attribute_role", f"attribute role '{r['id']}': time zone '{r['time_zone']}' is not recognised (or the time zone database is missing)") # ---- cycles among propagating links -------------------------------- for comp in tarjan_scc(list(events), adj): if len(comp) > 1: same = all(simultaneous(events[comp[0]], events[c]) for c in comp[1:]) if same: rep.warn("cycle", f"cycle among simultaneous events {comp[:6]}; the algorithm contracts it into a compound event") else: rep.error("cycle", f"cycle among events at different times {comp[:6]}") # ---- omitted -------------------------------------------------------- omitted_by_reason = collections.Counter(o["reason"] for _, o in data["omitted"]) # ---- manifest statistics and file hashes --------------------------- st = manifest["statistics"] def expect(name, claimed, actual): if claimed != actual: rep.error("statistics", f"manifest statistics {name} is {claimed}, the files give {actual}") expect("events", st["events"], len(events)) expect("entities", st["entities"], len(entities)) expect("entity_relations", st["entity_relations"], len(data["entity_relations"])) expect("links.total", st["links"]["total"], len(links)) expect("links.propagating", st["links"]["propagating"], propagating) expect("links.by_kind", st["links"]["by_kind"], dict(by_kind)) expect("links.by_level", st["links"]["by_level"], dict(by_level)) if "by_relation" in st["links"]: expect("links.by_relation", st["links"]["by_relation"], dict(by_relation)) expect("events_without_links", st["events_without_links"], len([e for e in events if e not in has_link])) expect("unreferenced_entities", st["unreferenced_entities"], len([e for e in entities if e not in referenced])) expect("merged_duplicates", st["merged_duplicates"], sum(len(e["provenance"].get("merged_from", [])) for e in events.values())) if st["omitted"]["by_reason"] != dict(omitted_by_reason): total_claimed = sum(st["omitted"]["by_reason"].values()) if total_claimed < len(data["omitted"]): rep.error("statistics", "omitted.jsonl lists more items than manifest statistics.omitted claims") else: rep.warn("statistics", "omitted.jsonl is a sample; counts in manifest are larger than the listed items") for key, (fname, _) in FILES.items(): entry = manifest["files"].get(fname) if hashes[key] is None: continue if entry is None: rep.error("files", f"manifest.files has no entry for {fname}") continue if entry["sha256"] != hashes[key]: rep.error("files", f"{fname}: sha256 in manifest does not match the file") if entry["records"] != len(data[key]): rep.error("files", f"{fname}: record count in manifest ({entry['records']}) does not match ({len(data[key])})") rep.print() if args.report: json.dump({"summary": rep.summary(), "errors": rep.errors, "warnings": rep.warnings}, open(args.report, "w"), indent=1) return 1 if rep.errors else 0 if __name__ == "__main__": sys.exit(main())