FIELDS = {"workload": str, "topology": str, "gate_duration": dict, "readout": str,
          "fidelity_method": str, "conversion": dict, "source_id": str}
def compare(matrix, maximum_compiled_duration_ns):
    errors = []
    durations = {}
    for name, row in matrix.items():
        missing = [field for field, kind in FIELDS.items()
                   if field not in row or type(row[field]) is not kind or not row[field]]
        gate, conversion = row.get("gate_duration", {}), row.get("conversion", {})
        if type(gate.get("value")) not in (int, float) or gate.get("unit") != "ns":
            missing.append("gate_duration_schema")
        if type(conversion.get("count")) is not int or conversion.get("unit") != "two-qubit gates":
            missing.append("conversion_schema")
        if missing:
            errors.append(name + ":" + ",".join(sorted(set(missing))))
        else:
            durations[name] = gate["value"] * conversion["count"]
    eligible = {name: value for name, value in durations.items()
                if value <= maximum_compiled_duration_ns}
    selected = min(eligible, key=eligible.get) if eligible else None
    return {"decision": selected or "not-comparable", "errors": errors,
            "compiled_duration_ns": durations, "eligible": sorted(eligible)}
matrix = {
    "device-a": {"workload": "Bell pair endpoints 0-2", "topology": "line",
                 "gate_duration": {"value": 250, "unit": "ns"}, "readout": "joint Z samples",
                 "fidelity_method": "interleaved RB", "conversion": {"count": 4, "unit": "two-qubit gates"},
                 "source_id": "scenario:device-a calibration"},
    "device-b": {"workload": "Bell pair endpoints 0-2", "topology": "all-to-all",
                 "gate_duration": {"value": 600, "unit": "ns"}, "readout": "joint Z samples",
                 "fidelity_method": "cycle benchmark", "source_id": "scenario:device-b calibration"},
    "device-c": {"workload": "Bell pair endpoints 0-2", "topology": "photonic graph",
                 "gate_duration": {"value": 80, "unit": "ns"}, "readout": "heralded samples",
                 "conversion": {"count": 8, "unit": "two-qubit gates"},
                 "source_id": "scenario:device-c calibration"}}
base_result = compare(matrix, 1200)
bad_a = {**matrix["device-a"], "gate_duration": {"value": 250, "unit": ""}}
bad_result = compare({**matrix, "device-a": bad_a}, 1200)
strict_result = compare(matrix, 900)
assert base_result["decision"] == "device-a" and base_result["eligible"] == ["device-a"]
assert bad_result["decision"] == "not-comparable" and "gate_duration_schema" in bad_result["errors"][0]
assert strict_result["decision"] == "not-comparable"
print(f"PASS: 74 modality matrix selected={base_result['decision']} duration={base_result['compiled_duration_ns']} invalid={bad_result['errors']} budget900ns={strict_result['decision']}")
