from __future__ import annotations import argparse import hashlib import json import sys from datetime import datetime, timezone from pathlib import Path from typing import Any PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from carddemo.parity import build_parity_evidence from carddemo.repository import seed_from_legacy from carddemo.service import CardDemoService DEFAULT_SOURCE_HEAD = "59cc6c2fd7ebd7ef7925cad552a01a4b8b6e4d5e" CLAIM_LIMIT = ( "Executable modern replay over static/source-oracle traces only; " "no live COBOL/CICS runtime replay has been performed." ) EXPECTED_SEED_COUNTS = { "customers": 50, "accounts": 50, "cards": 50, "card_xrefs": 50, "transactions": 300, "transaction_types": 7, "transaction_categories": 18, "disclosure_groups": 51, "transaction_category_balances": 50, "users": 10, "pending_authorization_summaries": 21, "pending_authorization_details": 202, } REQUIRED_TRACE_IDS = { "mq_system_date_cdrd_reply", "mq_account_inquiry_cdra_success_and_invalid", "batch_resource_setup_gdg_vsam_aix_cics", "pending_authorization_cpvs_summary_page", "pending_authorization_cp00_request_response_and_insert", "transaction_type_lookup", } REQUIRED_EDGE_CASE_IDS = { "mq_cdrd_request_payload_ignored", "mq_cdra_inqa_account_key_validation", "batch_gdg_limit_scratch_first_generation", "vsam_esds_rrds_user_security_layout", "transaction_aix_processed_timestamp_key", "cics_file_control_command_set", "pending_authorization_ims_segment_header_offset", "authorization_available_credit_boundary", } def stable_json_hash(payload: Any) -> str: return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode("utf-8")).hexdigest() def write_json(path: Path, payload: Any) -> Path: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8") return path def add_check( checks: list[dict[str, Any]], name: str, passed: bool, *, expected: Any = None, actual: Any = None, details: dict[str, Any] | None = None, ) -> None: row: dict[str, Any] = {"check": name, "passed": bool(passed)} if expected is not None: row["expected"] = expected if actual is not None: row["actual"] = actual if details: row["details"] = details checks.append(row) def trace_expectations(evidence: dict[str, Any]) -> dict[str, dict[str, Any]]: return {row["trace_id"]: row["expected"] for row in evidence["golden_traces"]} def add_runtime_probe( checks: list[dict[str, Any]], runtime_probes: list[dict[str, Any]], trace_id: str, actual: dict[str, Any], expected_by_trace: dict[str, dict[str, Any]], ) -> None: expected = expected_by_trace.get(trace_id, {}) passed = bool(expected) and actual == expected runtime_probes.append( { "trace_id": trace_id, "passed": passed, "expected": expected, "actual": actual, } ) add_check(checks, f"{trace_id}_runtime_probe", passed, expected=expected, actual=actual) def build_runtime_probes(service: CardDemoService, expected_by_trace: dict[str, dict[str, Any]]) -> list[dict[str, Any]]: checks: list[dict[str, Any]] = [] runtime_probes: list[dict[str, Any]] = [] mq_date = service.mq_system_date({"request_message": "IGNR00000000001"}, now="2026-05-23T11:12:13") add_runtime_probe( checks, runtime_probes, "mq_system_date_cdrd_reply", { "legacy_transaction": mq_date["legacy_transaction"], "legacy_program": mq_date["legacy_program"], "reply_queue": mq_date["reply_queue"], "system_date": mq_date["system_date"], "system_time": mq_date["system_time"], "reply_message": mq_date["reply_message"], "request_payload_validated": False, }, expected_by_trace, ) mq_account = service.mq_account_inquiry({"request_message": "INQA00000000001"}) mq_account_not_found = service.mq_account_inquiry({"function": "INQA", "account_id": 99999999999}) mq_account_bad_function = service.mq_account_inquiry({"function": "BAD", "account_id": 1}) add_runtime_probe( checks, runtime_probes, "mq_account_inquiry_cdra_success_and_invalid", { "legacy_transaction": mq_account["legacy_transaction"], "legacy_program": mq_account["legacy_program"], "reply_queue": mq_account["reply_queue"], "request_account_key": mq_account["request"]["account_id_text"], "account_id": mq_account["account_data"]["account_id"], "active_status": mq_account["account_data"]["active_status"], "reply_has_account_label": "ACCOUNT ID : 00000000001" in mq_account["reply_message"], "not_found_reply": mq_account_not_found["reply_message"], "bad_function_reply": mq_account_bad_function["reply_message"], }, expected_by_trace, ) resource_setup = service.batch_resource_setup() gdg_base_setup = service.batch_resource_setup("DEFGDGB") db2_gdg_setup = service.batch_resource_setup("DEFGDGD") esds_rrds_setup = service.batch_resource_setup("ESDSRRDS") tranidx_setup = service.batch_resource_setup("TRANIDX") closefil_setup = service.batch_resource_setup("CLOSEFIL") openfil_setup = service.batch_resource_setup("OPENFIL") add_runtime_probe( checks, runtime_probes, "batch_resource_setup_gdg_vsam_aix_cics", { "resource_count": resource_setup["resource_count"], "base_gdg_names": [row["name"] for row in gdg_base_setup["gdg_bases"]], "db2_first_generation_counts": [ db2_gdg_setup["steps"][1]["record_count"], db2_gdg_setup["steps"][3]["record_count"], db2_gdg_setup["steps"][5]["record_count"], ], "esds_rrds_organizations": [row["organization"] for row in esds_rrds_setup["clusters"]], "tranidx_keys": tranidx_setup["alternate_index"]["keys"], "tranidx_source_count": tranidx_setup["bldindex"]["source_record_count"], "close_code": closefil_setup["cemt_code"], "open_code": openfil_setup["cemt_code"], "file_sets_match": closefil_setup["files"] == openfil_setup["files"], }, expected_by_trace, ) pending_summary = service.pending_authorization_summary(1, page_size=5) add_runtime_probe( checks, runtime_probes, "pending_authorization_cpvs_summary_page", { "summary_count": pending_summary["summary"]["approved_auth_count"], "summary_amount_cents": pending_summary["summary"]["approved_auth_amount_cents"], "returned_authorizations": len(pending_summary["authorizations"]), "next_page": pending_summary["next_page"], "first_transaction_id": pending_summary["authorizations"][0]["transaction_id"], }, expected_by_trace, ) tx_types = service.transaction_types() tx_types_filtered = service.transaction_types(type_filter="01") tx_types_desc_filtered = service.transaction_types(description_filter="%PAYMENT%") tx_types_backward = service.transaction_types(start_key="07", direction="backward", page_size=3) add_runtime_probe( checks, runtime_probes, "transaction_type_lookup", { "legacy_transaction": tx_types["legacy_transaction"], "legacy_program": tx_types["legacy_program"], "type_count": len(tx_types["types"]), "category_count": len(tx_types["categories"]), "page_size": tx_types["page"]["page_size"], "type_filter_result": [row["type_code"] for row in tx_types_filtered["types"]], "description_filter_count": len(tx_types_desc_filtered["types"]), "backward_page_type_codes": [row["type_code"] for row in tx_types_backward["types"]], }, expected_by_trace, ) account_bundle = service.get_account_bundle(1) or {} cards = account_bundle.get("cards", []) card_number = cards[0]["card_number"] if cards else "9680294154603697" cp00_before = service.pending_authorization_summary(1, page_size=1) cp00 = service.process_authorization_request( { "card_number": card_number, "auth_date": "260523", "auth_time": "111213", "card_expiry_date": "1129", "transaction_amount_cents": 100, "merchant_category_code": "5442", "merchant_id": "123501000675423", "merchant_name": "Amazon.com", "merchant_city": "Wilmington", "merchant_state": "DE", "merchant_zip": "19801", "transaction_id": "AUTHREQ00000001", "processing_datetime": "2026-05-23T11:12:13.456", } ) cp00_after = service.pending_authorization_summary(1, page_size=1) cp00_invalid = service.process_authorization_request( { "card_number": "9999999999999999", "transaction_amount_cents": 100, "transaction_id": "AUTHREQBAD0001", } ) add_runtime_probe( checks, runtime_probes, "pending_authorization_cp00_request_response_and_insert", { "approved": cp00["approved"], "response_code": cp00["response"]["auth_resp_code"], "response_reason": cp00["response"]["auth_resp_reason"], "written": cp00["written_to_pending_authorizations"], "approved_count_delta": cp00_after["summary"]["approved_auth_count"] - cp00_before["summary"]["approved_auth_count"], "invalid_card_response_reason": cp00_invalid["response"]["auth_resp_reason"], "invalid_card_written": cp00_invalid["written_to_pending_authorizations"], }, expected_by_trace, ) return checks + runtime_probes def build_static_oracle_replay(source_root: Path, db_path: Path, *, source_head: str = DEFAULT_SOURCE_HEAD) -> dict[str, Any]: source_root = Path(source_root) db_path = Path(db_path) db_path.parent.mkdir(parents=True, exist_ok=True) seed_counts = seed_from_legacy(source_root, db_path, reset=True) evidence = build_parity_evidence(source_root, db_path, source_head=source_head) summary = evidence["summary"] checks: list[dict[str, Any]] = [] actual_seed_counts = {key: seed_counts.get(key) for key in EXPECTED_SEED_COUNTS} add_check( checks, "legacy_seed_count_contract", actual_seed_counts == EXPECTED_SEED_COUNTS, expected=EXPECTED_SEED_COUNTS, actual=actual_seed_counts, ) add_check(checks, "zero_capability_gaps", summary["gap_count"] == 0, expected=0, actual=summary["gap_count"]) add_check(checks, "empty_next_gap_ranking", evidence["next_gap_ranking"] == [], expected=[], actual=evidence["next_gap_ranking"]) add_check( checks, "all_capabilities_static_oracle_or_better", summary["static_oracle_or_better_count"] == summary["capability_count"], expected=summary["capability_count"], actual=summary["static_oracle_or_better_count"], ) add_check( checks, "no_partial_or_inferred_capabilities", summary["partial_or_inferred_count"] == 0, expected=0, actual=summary["partial_or_inferred_count"], ) trace_ids = {row["trace_id"] for row in evidence["golden_traces"]} edge_case_ids = {row["edge_case_id"] for row in evidence["edge_cases"]} missing_traces = sorted(REQUIRED_TRACE_IDS - trace_ids) missing_edge_cases = sorted(REQUIRED_EDGE_CASE_IDS - edge_case_ids) add_check( checks, "required_static_oracle_traces_present", not missing_traces, expected=sorted(REQUIRED_TRACE_IDS), actual=sorted(trace_ids & REQUIRED_TRACE_IDS), details={"missing": missing_traces}, ) add_check( checks, "required_edge_cases_present", not missing_edge_cases, expected=sorted(REQUIRED_EDGE_CASE_IDS), actual=sorted(edge_case_ids & REQUIRED_EDGE_CASE_IDS), details={"missing": missing_edge_cases}, ) add_check( checks, "all_golden_traces_static_oracle_or_better", all(row["proof_grade"] in {"A", "B"} for row in evidence["golden_traces"]), actual={row["trace_id"]: row["proof_grade"] for row in evidence["golden_traces"]}, ) expected_by_trace = trace_expectations(evidence) service = CardDemoService(db_path) probe_rows = build_runtime_probes(service, expected_by_trace) runtime_probe_checks = [row for row in probe_rows if "check" in row] runtime_probes = [row for row in probe_rows if "trace_id" in row] checks.extend(runtime_probe_checks) failed_checks = [row["check"] for row in checks if not row["passed"]] report = { "replay_version": "modern_carddemo_static_oracle_replay_v0", "generated_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "source_root": str(source_root.resolve()), "source_head": source_head, "scratch_db_path": str(db_path.resolve()), "seed_counts": seed_counts, "summary": summary, "capability_count": summary["capability_count"], "grade_counts": summary["grade_counts"], "gap_count": summary["gap_count"], "golden_trace_count": len(evidence["golden_traces"]), "edge_case_count": len(evidence["edge_cases"]), "runtime_probe_count": len(runtime_probes), "checks": checks, "runtime_probes": runtime_probes, "failed_checks": failed_checks, "passed": not failed_checks, "claim_limit": CLAIM_LIMIT, "public_actions_allowed": False, "evidence_hash": stable_json_hash(evidence), } report["replay_hash"] = stable_json_hash(report) return report def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--source-root", type=Path, required=True) parser.add_argument("--db-path", type=Path) parser.add_argument("--out-dir", type=Path, required=True) parser.add_argument("--source-head", default=DEFAULT_SOURCE_HEAD) args = parser.parse_args() args.out_dir.mkdir(parents=True, exist_ok=True) db_path = args.db_path or args.out_dir / "static_oracle_replay.sqlite" report = build_static_oracle_replay(args.source_root, db_path, source_head=args.source_head) report_path = write_json(args.out_dir / "static_oracle_replay.json", report) print( json.dumps( { "replay": str(report_path), "passed": report["passed"], "replay_hash": report["replay_hash"], "failed_checks": report["failed_checks"], "claim_limit": report["claim_limit"], }, indent=2, ) ) if not report["passed"]: raise SystemExit(1) if __name__ == "__main__": main()