"""Deterministic political discourse measurements and review provenance checks.""" from collections import Counter, defaultdict from datetime import datetime, timezone import hashlib import json import random import re VERSION = "doxa-measures-0.1.0" LABELS = ("asserted", "attributed", "qualified", "insufficient_context") FRAMES = ("causal_responsibility", "economic_consequence", "human_impact", "institutional_process", "public_safety") ENGINEERING_PREVIEW = "engineering_preview" HUMAN_REVIEWED = "human_reviewed" def timestamp(value): result = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) if result.strftime("%Y-%m-%dT%H:%M:%SZ") != value: raise ValueError("Timestamp must use UTC and second precision") return result def match_exclusion(left, right): """Return the first ineligibility reason against the declared matching rule.""" for field in ("event_id", "genre", "source_cohort", "claim_type"): if not left.get(field) or left[field] != right.get(field): return f"different_{field}" if left["claim_type"] not in {"budget", "capacity", "service_effect", "procedural_change"}: return "not_a_factual_comparison" if not left.get("actor") or not right.get("actor") or left["actor"] == right["actor"]: return "actors_not_distinct" if left.get("role") != "left" or right.get("role") != "right": return "role_orientation_missing" if any(side.get("evidence_status") != "uncorroborated" for side in (left, right)): return "uncorroborated_evidence_required" try: for side in (left, right): if timestamp(side["evidence_available_at"]) > timestamp(side["published_at"]): return "evidence_unavailable_at_publication" hours = abs((timestamp(left["published_at"]) - timestamp(right["published_at"])).total_seconds()) / 3600 except (ValueError, KeyError, TypeError): return "timestamp_missing_or_invalid" if hours > 48: return "outside_48_hour_window" return None def label_bounds(numerator, unresolved, eligible): if not eligible: return None return [numerator / eligible, (numerator + unresolved) / eligible] def compare(pairs, bootstrap=1000, seed=1729): """Compare paired presentation rates using explicit unresolved bounds.""" by_event = defaultdict(list) exclusions = Counter() examples = [] used_ids = set() used_units = set() for pair in pairs: ident = pair["pair_id"] if ident in used_ids: raise ValueError(f"Duplicate pair ID: {ident}") used_ids.add(ident) left, right = pair["left"], pair["right"] units = {left["unit_id"], right["unit_id"]} if len(units) != 2 or units & used_units: raise ValueError("Each text unit can occur in only one audit pair") used_units.update(units) exclusion = match_exclusion(left, right) if exclusion: exclusions[exclusion] += 1 examples.append({"pair_id": ident, "eligible": False, "reason": exclusion}) continue labels = (left["label"], right["label"]) if any(label not in LABELS for label in labels): raise ValueError(f"Unknown evidence judgment in {ident}") values = tuple(None if label == "insufficient_context" else int(label == "asserted") for label in labels) by_event[left["event_id"]].append(values) examples.append({"pair_id": ident, "eligible": True, "event_id": left["event_id"], "left_label": labels[0], "right_label": labels[1]}) all_values = [value for group in by_event.values() for value in group] eligible = len(all_values) sides = [] for index in (0, 1): numer = sum(value[index] == 1 for value in all_values) unresolved = sum(value[index] is None for value in all_values) sides.append({"presented_as_fact": numer, "unresolved": unresolved, "eligible": eligible, "bounds": label_bounds(numer, unresolved, eligible)}) left, right = sides coverage = [v for v in all_values if None not in v] gap = (sum(a - b for a, b in coverage) / len(coverage)) if coverage else None bounds = [left["bounds"][0] - right["bounds"][1], left["bounds"][1] - right["bounds"][0]] if eligible else None # Event-level resampling preserves dependence among pairs in one event. groups = [tuple((a,b) for a,b in group if None not in (a,b)) for group in by_event.values()] interval = None if sum(bool(group) for group in groups) >= 5 and bootstrap: rng = random.Random(seed) samples = [] for _ in range(bootstrap): batch = [value for group in rng.choices(groups, k=len(groups)) for value in group] if batch: samples.append(sum(a-b for a,b in batch) / len(batch)) if samples: samples.sort() interval = [samples[int(.025*(len(samples)-1))], samples[int(.975*(len(samples)-1))]] return { "metric_version": VERSION, "eligible_pairs": eligible, "eligible_events": len(by_event), "complete_pairs": len(coverage), "left": left, "right": right, "gap_bounds": bounds, "complete_pair_gap": gap, "event_bootstrap_interval": interval, "exclusions": dict(sorted(exclusions.items())), "pairs": examples, } def annotated_rates(rows): eligible = [row for row in rows if row["eligible"]] unreviewed = sum(row["status"] != "reviewed" for row in eligible) reviewed = [row for row in eligible if row["status"] == "reviewed"] loaded = sum(row["loaded_wording"] for row in reviewed) counts = Counter(frame for row in reviewed for frame in set(row["frames"])) if set(counts) - set(FRAMES): raise ValueError("Unknown frame") n = len(eligible) return { "eligible": n, "unresolved": unreviewed, "loaded_wording_rate": label_bounds(loaded, unreviewed, n), "frame_prevalence": {frame: label_bounds(counts[frame], unreviewed, n) for frame in FRAMES}, } def canonical_sha(value): return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest() def review_gate(rows, approvals, artifact_sha): """Validate recorded review evidence. This is not identity attestation.""" missing = [] if not rows: missing.append("no_reference_judgments") for row in rows: ident = row["unit_id"] if (row.get("origin") != "authentic" or not str(row.get("source_url", "")).startswith("https://") or not row.get("rights_basis") or not re.fullmatch("[a-f0-9]{64}", str(row.get("source_sha256", "")))): missing.append(f"authentic_rights_and_source_required:{ident}") if row.get("label") not in LABELS: missing.append(f"invalid_label:{ident}") span = row.get("reference_span") if row.get("label") != "insufficient_context": if not span or not valid_span(row, span): missing.append(f"source_span_required:{ident}") by_person = {x["reviewer_id"]: x for x in row.get("reviews", []) if x["origin"] == "human" and x["independent"]} if len(by_person) < 2: missing.append(f"insufficient_human_reviews:{ident}") elif row.get("origin") == "fictional": missing.append(f"fictional_fixture:{ident}") else: decisions = {item["label"] for item in by_person.values()} if len(decisions) == 1 and row.get("label") not in decisions: missing.append(f"reference_disagrees_with_review:{ident}") if len(decisions) > 1: adjudication = row.get("adjudication", {}) if (adjudication.get("reviewer_id") in by_person or not adjudication.get("reviewer_id") or adjudication.get("label") != row.get("label") or not adjudication.get("rationale")): missing.append(f"adjudication_required:{ident}") required = ("methods_reviewer", "independent_reproduction_engineer") people = defaultdict(set) for approval in approvals: if (approval.get("artifact_sha256") == artifact_sha and approval.get("decision") == "approve" and approval.get("origin") == "human" and approval.get("independent") and approval.get("reviewer_id") and approval.get("recorded_at")): people[approval["role"]].add(approval["reviewer_id"]) for role in required: if not people[role]: missing.append(f"approval_required:{role}") if people[required[0]] and people[required[1]] and len(people[required[0]] | people[required[1]]) < 2: missing.append("distinct_release_reviewers_required") return {"ready_for_human_reviewed_release": not missing, "failures": missing, "artifact_sha256": artifact_sha, "verification": "record_validation_only"} def valid_span(row, span): field = {"passage":"text", "context":"context"}.get(span.get("segment")) source = row.get(field) start, end = span.get("start"), span.get("end") return (isinstance(source,str) and type(start) is int and type(end) is int and 0 <= start < end <= len(source) and source[start:end] == span.get("quote"))