persona_attachment_selection.py (6251B)
1 """Select measured persona evidence from a bounded native audit export.""" 2 3 import json 4 from pathlib import Path 5 import re 6 import tempfile 7 from typing import Any, Callable, NamedTuple 8 9 AUDIT_UUID = r"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}" 10 AUDIT_NAME = re.compile( 11 rf"^(?:Screen before audit_0_{AUDIT_UUID}\.png|" 12 rf"Accessibility tree before audit_0_{AUDIT_UUID}\.txt)$" 13 ) 14 REQUIRED_ROW_KEYS = { 15 "exportedFileName", 16 "suggestedHumanReadableName", 17 "isAssociatedWithFailure", 18 "configurationName", 19 "deviceName", 20 "deviceId", 21 } 22 ALLOWED_ROW_KEYS = REQUIRED_ROW_KEYS | { 23 "timestamp", 24 "repetitionNumber", 25 "arguments", 26 } 27 28 29 class ExtractionTools(NamedTuple): 30 run_json: Callable 31 exact_node: Callable 32 read_json: Callable 33 inventory: Callable 34 digest: Callable 35 load_selected: Callable 36 attempt_id: Callable 37 node_identifier: str 38 node_url: str 39 names: tuple[str, ...] 40 maximum_json_bytes: int 41 maximum_attempt_bytes: int 42 run_export: Callable 43 44 45 def filename(value: object) -> str: 46 if not isinstance(value, str) or not value: 47 raise ValueError("xcresult exported filename is invalid") 48 if len(value.encode("utf-8")) > 255 or Path(value).name != value: 49 raise ValueError("xcresult exported filename is invalid") 50 return value 51 52 53 def row_identity(value: Any) -> tuple[str, str]: 54 if not isinstance(value, dict): 55 raise ValueError("xcresult attachment row is invalid") 56 if not REQUIRED_ROW_KEYS <= value.keys() <= ALLOWED_ROW_KEYS: 57 raise ValueError("xcresult attachment row is invalid") 58 if ( 59 value["isAssociatedWithFailure"] is not False 60 or value["configurationName"] != "Test Scheme Action" 61 ): 62 raise ValueError("xcresult attachment context is invalid") 63 if not all( 64 isinstance(value[k], str) and value[k] 65 for k in ["deviceName", "deviceId", "suggestedHumanReadableName"] 66 ): 67 raise ValueError("xcresult attachment context is invalid") 68 return filename(value["exportedFileName"]), value["suggestedHumanReadableName"] 69 70 71 def group_value(value: Any, tools: ExtractionTools) -> dict: 72 if not isinstance(value, list) or len(value) != 1: 73 raise ValueError("xcresult attachment manifest is invalid") 74 group = value[0] 75 if not isinstance(group, dict) or set(group) != { 76 "testIdentifier", 77 "testIdentifierURL", 78 "attachments", 79 }: 80 raise ValueError("xcresult attachment manifest is invalid") 81 if ( 82 group["testIdentifier"] != tools.node_identifier 83 or group["testIdentifierURL"] != tools.node_url 84 ): 85 raise ValueError("xcresult attachment test binding is invalid") 86 if not isinstance(group["attachments"], list): 87 raise ValueError("xcresult attachment inventory is invalid") 88 return group 89 90 91 def selected_rows( 92 group: dict, inventory: set[str], tools: ExtractionTools 93 ) -> list[dict]: 94 selected, seen = [], set() 95 for row in group["attachments"]: 96 exported, name = row_identity(row) 97 if exported in seen: 98 raise ValueError("xcresult attachment export identity is duplicated") 99 seen.add(exported) 100 if tools.attempt_id(name) is not None: 101 selected.append(row) 102 elif AUDIT_NAME.fullmatch(name) is None: 103 raise ValueError("xcresult contains an unknown diagnostic attachment") 104 if inventory != {"manifest.json", *seen}: 105 raise ValueError("xcresult raw export inventory is invalid") 106 if len(selected) != len(tools.names): 107 raise ValueError("xcresult requires exactly fifteen measured attempts") 108 devices = {(r["deviceName"], r["deviceId"]) for r in group["attachments"]} 109 if len(devices) != 1: 110 raise ValueError("xcresult diagnostics do not bind the attempt device") 111 return selected 112 113 114 def flat_inventory(path: Path, tools: ExtractionTools) -> set[str]: 115 values = tools.inventory(path) 116 if any(kind != 1 or b"/" in name for kind, name, _ in values): 117 raise ValueError("xcresult raw export inventory is invalid") 118 return {name.decode("utf-8") for _, name, _ in values} 119 120 121 def project(raw: Path, selected: Path, tools: ExtractionTools) -> None: 122 # The full raw export retains the existing result-bundle entry/file/total 123 # byte, regular-file, no-follow and stable-read gates, without new limits. 124 tools.digest(raw) 125 _, value = tools.read_json(raw / "manifest.json", tools.maximum_json_bytes) 126 group = group_value(value, tools) 127 rows = selected_rows(group, flat_inventory(raw, tools), tools) 128 for row in rows: 129 name = row["exportedFileName"] 130 payload, _ = tools.read_json(raw / name, tools.maximum_attempt_bytes) 131 (selected / name).write_bytes(payload) 132 (selected / "manifest.json").write_text( 133 json.dumps([{**group, "attachments": rows}]), encoding="utf-8" 134 ) 135 136 137 def extract( 138 result_bundle: Path, 139 suite: dict, 140 tools: ExtractionTools, 141 *, 142 require_measured_network: bool, 143 ): 144 tools.exact_node( 145 tools.run_json( 146 [ 147 "xcrun", 148 "xcresulttool", 149 "get", 150 "test-results", 151 "tests", 152 "--path", 153 str(result_bundle), 154 ], 155 tools.maximum_json_bytes, 156 ) 157 ) 158 with ( 159 tempfile.TemporaryDirectory() as raw_directory, 160 tempfile.TemporaryDirectory() as selected_directory, 161 ): 162 raw, selected = Path(raw_directory), Path(selected_directory) 163 tools.run_export( 164 [ 165 "xcrun", 166 "xcresulttool", 167 "export", 168 "attachments", 169 "--test-id", 170 tools.node_url, 171 "--path", 172 str(result_bundle), 173 "--output-path", 174 str(raw), 175 ], 176 ) 177 project(raw, selected, tools) 178 # This parser still requires exactly fifteen canonical, bounded, 179 # measured attempts and a strict sixteen-entry selected inventory. 180 return tools.load_selected( 181 selected, suite, require_measured_network=require_measured_network 182 )