ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
python_lock_policy_uv_cache.py
Go to the documentation of this file.
1# SPDX-License-Identifier: MIT
2# Copyright (c) 2026 Brighton Sikarskie
3"""Semantic uv-cache bootstrap, provisioner, and Ansible policy checks."""
4
5from __future__ import annotations
6
7import ast
8import copy
9import hashlib
10from pathlib import Path
11
12import yaml
13from python_lock_policy_uv_cache_contracts import (
14 bootstrap_expected_bodies,
15 bootstrap_module_mutations,
16 mode_execution_references,
17 mode_module_mutations,
18 mutate_named_function_once,
19 portable_execution_references,
20)
21from python_lock_policy_uv_cache_release import (
22 provisioner_findings,
23 provisioner_mutation_failures,
24)
25
26BOOTSTRAP_MODULE_SHA256 = "08ff0ed4479863f0ba63742da1a8f2411d19135301d2f3eebf694a18aaddcb15"
27MODE_TEST_MODULE_SHA256 = "f2fbbd678ea0c8a23a4004788b9881f3b0511c4e2e579e347f5ca590f4a2365f"
28PORTABLE_REGISTRY_DIGEST = "f4716c7f8a12aa6b22c092304d68978b98af975220dbe4099b64f6e8facd3cfe"
29MODE_EXECUTION_REGISTRY_DIGEST = "579c40124d7f2206583682aadf91a241f9363cc2e47826d5810e87e1a8d540ea"
30
31
32def _function(tree: ast.AST, name: str) -> ast.FunctionDef | None:
33 """Return one top-level function definition, rejecting ambiguity."""
34 matches = [
35 node
36 for node in getattr(tree, "body", [])
37 if isinstance(node, ast.FunctionDef) and node.name == name
38 ]
39 return matches[0] if len(matches) == 1 else None
40
41
42def _without_docstring(function: ast.FunctionDef) -> ast.Module:
43 """Return a comparable body without its optional documentation literal."""
44 body = list(function.body)
45 if (
46 body
47 and isinstance(body[0], ast.Expr)
48 and isinstance(body[0].value, ast.Constant)
49 and isinstance(body[0].value.value, str)
50 ):
51 body = body[1:]
52 return ast.Module(body=body, type_ignores=[])
53
54
55def _body_dump(function: ast.FunctionDef) -> str:
56 """Return one formatting-independent function-body identity."""
57 return ast.dump(_without_docstring(function), include_attributes=False)
58
59
60def _expected_body(source: str, name: str) -> str:
61 """Return the semantic body identity from a canonical function fixture."""
62 function = _function(ast.parse(source), name)
63 if function is None:
64 message = f"canonical function fixture is missing {name}"
65 raise ValueError(message)
66 return _body_dump(function)
67
68
69def _direct_call_count(function: ast.FunctionDef, name: str) -> int:
70 """Count direct top-level expression calls within one function body."""
71 return sum(
72 isinstance(statement, ast.Expr)
73 and isinstance(statement.value, ast.Call)
74 and isinstance(statement.value.func, ast.Name)
75 and statement.value.func.id == name
76 for statement in function.body
77 )
78
79
80def _all_call_count(function: ast.FunctionDef, name: str) -> int:
81 """Count calls within one function while excluding nested definitions."""
82 count = 0
83 pending = list(function.body)
84 while pending:
85 node = pending.pop()
86 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
87 continue
88 count += int(
89 isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name
90 )
91 pending.extend(ast.iter_child_nodes(node))
92 return count
93
94
95def _attribute_path(node: ast.AST) -> str:
96 """Return one dotted-name path or an empty string for a dynamic owner."""
97 if isinstance(node, ast.Name):
98 return node.id
99 if isinstance(node, ast.Attribute):
100 parent = _attribute_path(node.value)
101 return f"{parent}.{node.attr}" if parent else ""
102 return ""
103
104
105def _deep_qualified_reference_count(function: ast.FunctionDef, owner: str, name: str) -> int:
106 """Count exact module attributes throughout one selftest function."""
107 return sum(
108 isinstance(node, ast.Attribute)
109 and _attribute_path(node.value) == owner
110 and node.attr == name
111 for node in ast.walk(function)
112 )
113
114
115def _bootstrap_function_findings(tree: ast.Module) -> list[str]:
116 """Bind security-critical bootstrap functions to their reviewed semantics."""
117 findings: list[str] = []
118 for name, source in bootstrap_expected_bodies().items():
119 function = _function(tree, name)
120 if function is None or _body_dump(function) != _expected_body(source, name):
121 findings.append(f"uv bootstrap {name} semantic contract drifted")
122 run_selftest = _function(tree, "run_selftest")
123 if run_selftest is None or not (
124 _direct_call_count(run_selftest, "cache_mode_selftest") == 1
125 and _all_call_count(run_selftest, "cache_mode_selftest") == 1
126 ):
127 findings.append("bootstrap run_selftest does not directly execute cache_mode_selftest once")
128 return findings
129
130
131def _bootstrap_main_guard_findings(tree: ast.Module) -> list[str]:
132 """Bind typed apply-required status to the production script entrypoint."""
133 expected = ast.dump(
134 ast.parse(
135 """
136if __name__ == "__main__":
137 try:
138 raise SystemExit(main())
139 except CacheApplyRequiredError as error:
140 print(f"APPLY REQUIRED: {error}", file=sys.stderr)
141 raise SystemExit(2) from error
142 except BootstrapError as error:
143 print(f"ERROR: {error}", file=sys.stderr)
144 raise SystemExit(1) from error
145"""
146 ).body[0],
147 include_attributes=False,
148 )
149 matches = [
150 statement
151 for statement in tree.body
152 if ast.dump(statement, include_attributes=False) == expected
153 ]
154 classes = [
155 node
156 for node in tree.body
157 if isinstance(node, ast.ClassDef) and node.name == "CacheApplyRequiredError"
158 ]
159 findings = [] if len(matches) == 1 else ["bootstrap apply-required exit contract drifted"]
160 if len(classes) != 1:
161 findings.append("bootstrap CacheApplyRequiredError type is missing or ambiguous")
162 return findings
163
164
165def _bootstrap_verify_dispatch_findings(tree: ast.Module) -> list[str]:
166 """Bind verification to bounded FDs and an authenticated-byte probe."""
167 function = _function(tree, "verify_cached_uv")
168 payload = _function(tree, "validated_cached_payload")
169 required = {
170 "validated_cached_payload": 1,
171 "authenticated_cache_fds": 1,
172 "verify_fd_mode": 2,
173 "probe_authenticated_uv": 1,
174 "verify_fd_unchanged": 2,
175 "verify_fd_path": 2,
176 }
177 if function is None or payload is None:
178 return ["bootstrap verify_cached_uv is missing or ambiguous"]
179 findings = [
180 f"bootstrap verify_cached_uv {name} call chain drifted"
181 for name, expected in required.items()
182 if _all_call_count(function, name) != expected
183 ]
184 findings.extend(
185 f"bootstrap cached payload {name} call chain drifted"
186 for name in ("open_cache_fd", "read_stable_fd")
187 if _all_call_count(payload, name) != 1
188 )
189 return findings
190
191
192def _mode_runner_findings(tree: ast.Module) -> list[str]:
193 """Bind the public runner to every critical adversarial test leg."""
194 expected = """
195def run_mode_selftest():
196 if os.name == "posix":
197 darwin_root_alias_acceptance_selftest()
198 darwin_root_alias_rejection_selftest()
199 cache_mode_convergence_selftest()
200 cache_mode_authentication_selftest()
201 cache_open_flags_selftest()
202 cache_parent_symlink_selftest()
203 cache_parent_swap_selftest()
204 cache_atomic_parent_swap_selftest()
205 cache_nonregular_selftest()
206 cache_stable_read_selftest()
207 cache_verification_fifo_race_selftest()
208 cache_exact_fd_execution_selftest()
209 cache_same_inode_execution_selftest()
210 cache_run_exit_status_selftest()
211 cache_run_signal_status_selftest()
212 portable_readonly_fd_selftest()
213 portable_snapshot_flags_selftest()
214 for attack in ("replace", "symlink", "hardlink", "overwrite", "descriptor"):
215 portable_snapshot_path_attack_selftest(attack)
216 portable_snapshot_unlink_failure_selftest()
217 for target in ("archive", "binary"):
218 cache_mode_path_attack_selftest(target, "symlink", preexisting=True)
219 for replacement in ("symlink", "regular"):
220 cache_mode_path_attack_selftest(target, replacement, preexisting=False)
221 cache_status_contract_selftest()
222 cache_mode_readonly_and_windows_selftest()
223"""
224 runner = _function(tree, "run_mode_selftest")
225 if runner is None or _body_dump(runner) != _expected_body(expected, "run_mode_selftest"):
226 return ["uv mode selftest runner no longer executes every critical leg"]
227 return []
228
229
230def _mode_cache_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
231 """Return critical cache-open/read selftest references."""
232 return {
233 "darwin_root_alias_acceptance_selftest": (
234 ("", "open_simulated_darwin_parent", 1),
235 ("b.bootstrap_uv_exec", "open_parent_components", 1),
236 ("b", "fail", 1),
237 ),
238 "darwin_root_alias_rejection_selftest": (("", "expect_exec_failure", 6),),
239 "cache_mode_convergence_selftest": (("b", "ensure_uv", 1),),
240 "cache_mode_authentication_selftest": (("b", "expect_bootstrap_error", 1),),
241 "cache_open_flags_selftest": (("b", "open_cache_fd", 2),),
242 "cache_parent_symlink_selftest": (
243 ("link", "symlink_to", 1),
244 ("b", "open_cache_fd", 1),
245 ("b", "expect_bootstrap_error", 1),
246 ),
247 "cache_parent_swap_selftest": (
248 ("original_parent", "rename", 1),
249 ("original_parent", "symlink_to", 1),
250 ("b", "normalize_cached_modes", 1),
251 ("b", "expect_bootstrap_error", 1),
252 ),
253 "cache_atomic_parent_swap_selftest": (
254 ("os", "replace", 1),
255 ("original_parent", "rename", 1),
256 ("original_parent", "symlink_to", 1),
257 ("b", "ensure_uv", 1),
258 ("b", "expect_bootstrap_error", 1),
259 ),
260 "cache_nonregular_selftest": (
261 ("os", "mkfifo", 1),
262 ("socket", "socket", 1),
263 ("b", "open_cache_fd", 1),
264 ),
265 "cache_stable_read_selftest": (
266 ("b", "open_cache_fd", 2),
267 ("b", "read_stable_fd", 2),
268 ("b", "expect_bootstrap_error", 1),
269 ("", "expect_concurrent_read_rejected", 2),
270 ),
271 "expect_concurrent_read_rejected": (
272 ("os", "utime", 1),
273 ("b", "open_cache_fd", 1),
274 ("b", "read_stable_fd", 1),
275 ("b", "expect_bootstrap_error", 1),
276 ),
277 "cache_verification_fifo_race_selftest": (
278 ("os", "mkfifo", 1),
279 ("b", "verify_cached_uv", 1),
280 ("b", "expect_bootstrap_error", 1),
281 ),
282 }
283
284
285def _mode_test_body_findings(tree: ast.Module) -> list[str]:
286 """Require each adversarial mode test to retain its critical call chain."""
287 portable_references = portable_execution_references()
288 mode_references = mode_execution_references()
289 required = {
290 **_mode_cache_references(),
291 **mode_references,
292 **portable_references,
293 }
294 findings = [
295 *_registry_findings(portable_references, PORTABLE_REGISTRY_DIGEST, "portable uv execution"),
296 *_registry_findings(mode_references, MODE_EXECUTION_REGISTRY_DIGEST, "uv mode execution"),
297 ]
298 for function_name, references in required.items():
299 function = _function(tree, function_name)
300 if function is None:
301 findings.append(f"uv mode selftest critical function is missing: {function_name}")
302 continue
303 for owner, name, expected in references:
304 actual = (
305 _deep_qualified_reference_count(function, owner, name)
306 if owner
307 else _all_call_count(function, name)
308 )
309 if actual != expected:
310 findings.append(
311 f"uv mode selftest {function_name} {owner}.{name} call chain drifted"
312 )
313 return findings
314
315
316def _registry_findings(
317 references: dict[str, tuple[tuple[str, str, int], ...]],
318 expected_digest: str,
319 label: str,
320) -> list[str]:
321 """Bind one split selftest registry against silent collapse or drift."""
322 digest = hashlib.sha256(repr(references).encode()).hexdigest()
323 if digest != expected_digest:
324 return [f"{label} selftest registry drifted"]
325 return []
326
327
328def bootstrap_uv_findings(bootstrap: str, mode_test: str) -> list[str]:
329 """Return semantic bootstrap/selftest binding findings."""
330 identity_findings = (
331 []
332 if hashlib.sha256(bootstrap.encode()).hexdigest() == BOOTSTRAP_MODULE_SHA256
333 else ["uv bootstrap module byte identity drifted"]
334 )
335 if hashlib.sha256(mode_test.encode()).hexdigest() != MODE_TEST_MODULE_SHA256:
336 identity_findings.append("uv mode selftest module byte identity drifted")
337 try:
338 bootstrap_tree = ast.parse(bootstrap)
339 mode_tree = ast.parse(mode_test)
340 except SyntaxError as exc:
341 return [f"uv bootstrap policy input is invalid Python: {exc}"]
342 return [
343 *identity_findings,
344 *_bootstrap_function_findings(bootstrap_tree),
345 *_bootstrap_main_guard_findings(bootstrap_tree),
346 *_bootstrap_verify_dispatch_findings(bootstrap_tree),
347 *_mode_runner_findings(mode_tree),
348 *_mode_test_body_findings(mode_tree),
349 ]
350
351
352def gate_selftest_findings(source: str) -> list[str]:
353 """Require the real pre-commit gate to execute the provisioner selftest."""
354 start = "_pcc_python_authority() (\n"
355 if source.count(start) != 1:
356 return ["Python-authority gate body is missing or ambiguous"]
357 body, separator, _rest = source.split(start, 1)[1].partition("\n)\n")
358 if not separator:
359 return ["Python-authority gate body is unterminated"]
360 lines = [
361 " ".join(line.strip().split())
362 for line in body.splitlines()
363 if line.strip() and not line.lstrip().startswith("#")
364 ]
365 expected = (
366 "/bin/bash -p scripts/dev/provision_dev_box_toolchain.sh --selftest-uv-cache-contract"
367 )
368 lock_selftest = "python3 scripts/checks/check_python_lock_policy.py --selftest"
369 if lines.count(expected) != 1 or lines.count(lock_selftest) != 1:
370 return ["Python-authority gate does not run both uv-cache contract selftests"]
371 if lines.index(expected) >= lines.index(lock_selftest):
372 return ["provisioner contract selftest does not precede its policy check"]
373 return []
374
375
376def _tasks(document: object) -> list[dict[str, object]]:
377 """Return one typed Ansible task list."""
378 if not isinstance(document, list):
379 return []
380 return [task for task in document if isinstance(task, dict)]
381
382
383def _task_by_register(tasks: list[dict[str, object]], name: str) -> dict[str, object] | None:
384 """Return one task owning an exact Ansible register."""
385 matches = [task for task in tasks if task.get("register") == name]
386 return matches[0] if len(matches) == 1 else None
387
388
389def _task_by_name(tasks: list[dict[str, object]], name: str) -> dict[str, object] | None:
390 """Return one task carrying an exact display name."""
391 matches = [task for task in tasks if task.get("name") == name]
392 return matches[0] if len(matches) == 1 else None
393
394
395def _check_task_findings(check: dict[str, object] | None) -> list[str]:
396 """Validate the forced read-only Ansible check task."""
397 findings: list[str] = []
398 check_argv = [
399 "/bin/bash",
400 "-p",
401 "scripts/dev/provision_dev_box_toolchain.sh",
402 "--check-only",
403 ]
404 if check is None:
405 return ["dev-box Ansible check-mode provisioner task is missing or ambiguous"]
406 command = check.get("ansible.builtin.command")
407 argv = command.get("argv") if isinstance(command, dict) else None
408 if argv != check_argv:
409 findings.append("dev-box Ansible check mode does not use exact read-only argv")
410 if check.get("when") != "ansible_check_mode" or check.get("check_mode") is not False:
411 findings.append("dev-box Ansible check task can skip or escape check mode")
412 if check.get("become") is True:
413 findings.append("dev-box Ansible read-only check unexpectedly escalates privilege")
414 if check.get("changed_when") != "dev_box_provision_check.rc == 2":
415 findings.append("dev-box Ansible drift status is not reported changed")
416 if check.get("failed_when") != "dev_box_provision_check.rc not in [0, 2]":
417 findings.append("dev-box Ansible check task does not fail real errors")
418 return findings
419
420
421def _postcheck_task_findings(task: dict[str, object] | None) -> list[str]:
422 """Bind the post-provision import check to successful cache audit state."""
423 expected_when = "not ansible_check_mode or (dev_box_provision_check.rc | default(0)) == 0"
424 if task is None:
425 return ["dev-box post-provision import task is missing or ambiguous"]
426 if task.get("when") != expected_when:
427 return ["dev-box post-provision import condition drifted"]
428 return []
429
430
431def _apply_task_findings(apply: dict[str, object] | None) -> list[str]:
432 """Validate the disjoint mutating Ansible apply task."""
433 findings: list[str] = []
434 apply_argv = ["/bin/bash", "-p", "scripts/dev/provision_dev_box_toolchain.sh"]
435 if apply is None:
436 return ["dev-box Ansible apply provisioner task is missing or ambiguous"]
437 command = apply.get("ansible.builtin.command")
438 argv = command.get("argv") if isinstance(command, dict) else None
439 if argv != apply_argv:
440 findings.append("dev-box Ansible apply mode does not use exact mutating argv")
441 if apply.get("when") != "not ansible_check_mode":
442 findings.append("dev-box Ansible apply task can execute during check mode")
443 if apply.get("changed_when") != "'->' in dev_box_provision.stdout":
444 findings.append("dev-box Ansible apply change marker drifted")
445 if "failed_when" in apply:
446 findings.append("dev-box Ansible apply task overrides command failure")
447 return findings
448
449
450def _ansible_invocation_findings(tasks: list[dict[str, object]]) -> list[str]:
451 """Reject any third or missing provisioner command boundary."""
452 check_argv = [
453 "/bin/bash",
454 "-p",
455 "scripts/dev/provision_dev_box_toolchain.sh",
456 "--check-only",
457 ]
458 apply_argv = ["/bin/bash", "-p", "scripts/dev/provision_dev_box_toolchain.sh"]
459 invocations = []
460 for task in tasks:
461 command = task.get("ansible.builtin.command")
462 argv = command.get("argv") if isinstance(command, dict) else None
463 if isinstance(argv, list) and "scripts/dev/provision_dev_box_toolchain.sh" in argv:
464 invocations.append(argv)
465 if sorted(invocations) != sorted([check_argv, apply_argv]):
466 return ["dev-box Ansible has an extra or missing provisioner invocation"]
467 return []
468
469
470def dev_box_uv_task_findings(document: object) -> list[str]:
471 """Bind Ansible check/apply modes to exact disjoint provisioner argv."""
472 tasks = _tasks(document)
473 postcheck = _task_by_name(tasks, "Assert the provisioned libclang binding actually imports")
474 return [
475 *_check_task_findings(_task_by_register(tasks, "dev_box_provision_check")),
476 *_apply_task_findings(_task_by_register(tasks, "dev_box_provision")),
477 *_postcheck_task_findings(postcheck),
478 *_ansible_invocation_findings(tasks),
479 ]
480
481
482def uv_cache_policy_findings(root: Path) -> list[str]:
483 """Read and validate every uv-cache control-plane source."""
484 try:
485 bootstrap = (root / "scripts/dev/bootstrap_uv.py").read_text(encoding="utf-8")
486 mode_test = (root / "scripts/dev/bootstrap_uv_mode_selftest.py").read_text(encoding="utf-8")
487 provisioner = (root / "scripts/dev/provision_dev_box_toolchain.sh").read_text(
488 encoding="utf-8"
489 )
490 provisioner_selftest = (
491 root / "scripts/dev/provision_dev_box_toolchain_selftest.bash"
492 ).read_text(encoding="utf-8")
493 gate = (root / "scripts/ci/gates/checks.sh").read_text(encoding="utf-8")
494 transaction = yaml.safe_load(
495 (root / "infra/ansible/roles/dev_box/tasks/transaction.yml").read_text(encoding="utf-8")
496 )
497 except (OSError, UnicodeError, yaml.YAMLError) as exc:
498 return [f"uv-cache policy input is unreadable: {exc}"]
499 return [
500 *bootstrap_uv_findings(bootstrap, mode_test),
501 *provisioner_findings(provisioner, provisioner_selftest),
502 *gate_selftest_findings(gate),
503 *dev_box_uv_task_findings(transaction),
504 ]
505
506
507def _mutate_once(source: str, old: str, new: str) -> str:
508 """Apply one exact mutation and fail if the fixture authority drifted."""
509 if source.count(old) != 1:
510 message = f"selftest mutation anchor count changed: {old!r}"
511 raise ValueError(message)
512 return source.replace(old, new, 1)
513
514
515def _hollow_python_function(source: str, name: str) -> str:
516 """Replace one top-level Python function body with a no-op."""
517 tree = ast.parse(source)
518 function = _function(tree, name)
519 if function is None:
520 message = f"selftest function is missing: {name}"
521 raise ValueError(message)
522 function.body = [ast.Pass()]
523 ast.fix_missing_locations(tree)
524 return ast.unparse(tree)
525
526
527def _hollow_shell_function(source: str, name: str) -> str:
528 """Replace one two-space-indented shell function body with a no-op."""
529 lines = source.splitlines()
530 starts = [index for index, line in enumerate(lines) if line == f" {name}() {{"]
531 if len(starts) != 1:
532 message = f"selftest shell function is missing: {name}"
533 raise ValueError(message)
534 end = next(index for index in range(starts[0] + 1, len(lines)) if lines[index] == " }")
535 replacement = [lines[starts[0]], " :", lines[end]]
536 return "\n".join([*lines[: starts[0]], *replacement, *lines[end + 1 :]]) + "\n"
537
538
539def _bootstrap_source_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
540 """Prove each bootstrap production safeguard is independently bound."""
541 failures: list[str] = []
542 bootstrap_mutations = (
543 *bootstrap_module_mutations(),
544 (
545 " return bootstrap_uv_exec.open_regular_nofollow(path)\n",
546 " return os.open(path, os.O_RDONLY)\n",
547 ),
548 (
549 " bootstrap_uv_exec.write_atomic_nofollow(path, payload, mode)\n",
550 " path.write_bytes(payload)\n",
551 ),
552 (
553 " reopened = open_cache_fd(path)\n",
554 " path_state = os.lstat(path)\n",
555 ),
556 (
557 "if any(getattr(before, field) != getattr(after, field) for field in stable):",
558 "if False:",
559 ),
560 ("if len(payload) > maximum:", "if False:"),
561 (" cache_mode_selftest()\n", " if False:\n cache_mode_selftest()\n"),
562 ('"--check-cache-modes",', '"--disabled-cache-modes",'),
563 (
564 " verify_cached_modes(destination.parent / asset_name, destination)\n",
565 " pass\n",
566 ),
567 (' "--run",\n', ' "--disabled-run",\n'),
568 (
569 " completed = bootstrap_uv_exec.run_uv_snapshot(binary, arguments)\n",
570 " completed = None\n",
571 ),
572 (
573 " return propagate_child_status(completed.returncode)\n",
574 " return completed.returncode\n",
575 ),
576 (
577 " probe_authenticated_uv(binary, version)\n"
578 " verify_fd_unchanged(archive_path, archive_fd, archive_state)\n"
579 " verify_fd_unchanged(destination, destination_fd, installed_state)\n"
580 " verify_fd_path(archive_path, archive_fd, PUBLIC_ARCHIVE_MODE)\n"
581 " verify_fd_path(destination, destination_fd, PUBLIC_EXECUTABLE_MODE)\n",
582 " probe_authenticated_uv(binary, version)\n"
583 " verify_fd_unchanged(archive_path, archive_fd, archive_state)\n"
584 " verify_fd_unchanged(destination, destination_fd, installed_state)\n",
585 ),
586 ("raise SystemExit(2) from error", "raise SystemExit(1) from error"),
587 )
588 failures.extend(
589 f"uv bootstrap mutation passed: {old}"
590 for old, new in bootstrap_mutations
591 if not bootstrap_uv_findings(_mutate_once(bootstrap, old, new), mode_test)
592 )
593 return failures
594
595
596def _mode_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
597 """Prove every mode runner leg and critical test body is load-bearing."""
598 failures = [
599 f"uv mode module mutation passed: {old}"
600 for old, new in mode_module_mutations()
601 if not bootstrap_uv_findings(bootstrap, _mutate_once(mode_test, old, new))
602 ]
603 runner_calls = (
604 " darwin_root_alias_acceptance_selftest()\n",
605 " darwin_root_alias_rejection_selftest()\n",
606 " cache_mode_convergence_selftest()\n",
607 " cache_mode_authentication_selftest()\n",
608 " cache_open_flags_selftest()\n",
609 " cache_parent_symlink_selftest()\n",
610 " cache_parent_swap_selftest()\n",
611 " cache_atomic_parent_swap_selftest()\n",
612 " cache_nonregular_selftest()\n",
613 " cache_stable_read_selftest()\n",
614 " cache_verification_fifo_race_selftest()\n",
615 " cache_exact_fd_execution_selftest()\n",
616 " cache_same_inode_execution_selftest()\n",
617 " cache_run_exit_status_selftest()\n",
618 " cache_run_signal_status_selftest()\n",
619 " portable_readonly_fd_selftest()\n",
620 " portable_snapshot_flags_selftest()\n",
621 " portable_snapshot_unlink_failure_selftest()\n",
622 ' cache_mode_path_attack_selftest(target, "symlink", preexisting=True)\n',
623 " cache_status_contract_selftest()\n",
624 " cache_mode_readonly_and_windows_selftest()\n",
625 )
626 failures.extend(
627 f"uv mode runner mutation passed: {call.strip()}"
628 for call in runner_calls
629 if not bootstrap_uv_findings(bootstrap, _mutate_once(mode_test, call, ""))
630 )
631 return [*failures, *_mode_body_mutation_failures(bootstrap, mode_test)]
632
633
634def _mode_body_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
635 """Prove supported-Python binding and each critical mode-test body."""
636 interpreter_mutations = (
637 "cache_run_exit_status_selftest",
638 "cache_run_signal_status_selftest",
639 "bootstrap_run_status",
640 )
641 failures = [
642 "unsupported hardcoded Python passed the uv mode policy"
643 for name in interpreter_mutations
644 if not bootstrap_uv_findings(
645 bootstrap,
646 mutate_named_function_once(
647 mode_test,
648 name,
649 "sys.executable",
650 '"/usr/bin/python3"',
651 ),
652 )
653 ]
654 critical_tests = (
655 "darwin_root_alias_acceptance_selftest",
656 "darwin_root_alias_rejection_selftest",
657 "cache_mode_convergence_selftest",
658 "cache_mode_authentication_selftest",
659 "cache_open_flags_selftest",
660 "cache_parent_symlink_selftest",
661 "cache_parent_swap_selftest",
662 "cache_atomic_parent_swap_selftest",
663 "cache_nonregular_selftest",
664 "expect_concurrent_read_rejected",
665 "cache_stable_read_selftest",
666 "cache_verification_fifo_race_selftest",
667 "cache_exact_fd_execution_selftest",
668 "cache_same_inode_execution_selftest",
669 "cache_run_exit_status_selftest",
670 "cache_run_signal_status_selftest",
671 "portable_readonly_fd_selftest",
672 "run_portable_snapshot",
673 "portable_snapshot_flags_selftest",
674 "portable_snapshot_path_attack_selftest",
675 "portable_snapshot_unlink_failure_selftest",
676 "cache_mode_path_attack_selftest",
677 "bootstrap_run_status",
678 "cache_status_contract_selftest",
679 "cache_mode_readonly_and_windows_selftest",
680 )
681 failures.extend(
682 f"hollow uv mode selftest passed policy: {name}"
683 for name in critical_tests
684 if not bootstrap_uv_findings(bootstrap, _hollow_python_function(mode_test, name))
685 )
686 return failures
687
688
689def _bootstrap_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
690 """Prove the live bootstrap and every mutation-sensitive seam."""
691 failures = []
692 if bootstrap_uv_findings(bootstrap, mode_test):
693 failures.append("live uv bootstrap semantic contract failed")
694 if not _registry_findings({}, PORTABLE_REGISTRY_DIGEST, "portable uv execution"):
695 failures.append("collapsed portable uv execution registry passed")
696 if not _registry_findings({}, MODE_EXECUTION_REGISTRY_DIGEST, "uv mode execution"):
697 failures.append("collapsed uv mode execution registry passed")
698 return [
699 *failures,
700 *_bootstrap_source_mutation_failures(bootstrap, mode_test),
701 *_mode_mutation_failures(bootstrap, mode_test),
702 ]
703
704
705def _gate_mutation_failures(gate: str) -> list[str]:
706 """Prove the runtime provisioner selftest cannot leave its real gate."""
707 failures = []
708 if gate_selftest_findings(gate):
709 failures.append("live Python-authority uv selftest binding failed")
710 line = (
711 " /bin/bash -p scripts/dev/provision_dev_box_toolchain.sh --selftest-uv-cache-contract\n"
712 )
713 mutated = _mutate_once(gate, line, "")
714 if not gate_selftest_findings(mutated):
715 failures.append("uv gate selftest mutation passed")
716 return failures
717
718
719def _task_copy_with_value(
720 tasks: list[dict[str, object]], register: str, key: str, *, value: object
721) -> list[dict[str, object]]:
722 """Return a deep copy with one registered task field changed."""
723 mutated = copy.deepcopy(tasks)
724 task = _task_by_register(mutated, register)
725 if task is None:
726 message = f"selftest task is missing: {register}"
727 raise ValueError(message)
728 task[key] = value
729 return mutated
730
731
732def _task_copy_with_argv(
733 tasks: list[dict[str, object]], register: str, argv: list[str]
734) -> list[dict[str, object]]:
735 """Return a deep copy with one registered command argv changed."""
736 mutated = copy.deepcopy(tasks)
737 task = _task_by_register(mutated, register)
738 command = task.get("ansible.builtin.command") if task is not None else None
739 if not isinstance(command, dict):
740 message = f"selftest command is missing: {register}"
741 raise TypeError(message)
742 command["argv"] = argv
743 return mutated
744
745
746def _task_copy_named_with_value(
747 tasks: list[dict[str, object]], name: str, key: str, *, value: object
748) -> list[dict[str, object]]:
749 """Return a deep copy with one display-named task field changed."""
750 mutated = copy.deepcopy(tasks)
751 task = _task_by_name(mutated, name)
752 if task is None:
753 message = f"selftest task is missing: {name}"
754 raise ValueError(message)
755 task[key] = value
756 return mutated
757
758
759def _ansible_mutation_documents(
760 tasks: list[dict[str, object]],
761) -> tuple[tuple[str, list[dict[str, object]]], ...]:
762 """Return independent Ansible policy mutations."""
763 apply_argv = ["/bin/bash", "-p", "scripts/dev/provision_dev_box_toolchain.sh"]
764 return (
765 (
766 "drop-check",
767 [
768 task
769 for task in copy.deepcopy(tasks)
770 if task.get("register") != "dev_box_provision_check"
771 ],
772 ),
773 (
774 "check-ensure",
775 _task_copy_with_argv(tasks, "dev_box_provision_check", apply_argv),
776 ),
777 (
778 "check-skip",
779 _task_copy_with_value(tasks, "dev_box_provision_check", "check_mode", value=None),
780 ),
781 (
782 "check-privileged",
783 _task_copy_with_value(tasks, "dev_box_provision_check", "become", value=True),
784 ),
785 (
786 "changed-always",
787 _task_copy_with_value(tasks, "dev_box_provision_check", "changed_when", value=True),
788 ),
789 (
790 "failed-never",
791 _task_copy_with_value(tasks, "dev_box_provision_check", "failed_when", value=False),
792 ),
793 (
794 "apply-during-check",
795 _task_copy_with_value(tasks, "dev_box_provision", "when", value="ansible_check_mode"),
796 ),
797 (
798 "postcheck-unconditional",
799 _task_copy_named_with_value(
800 tasks,
801 "Assert the provisioned libclang binding actually imports",
802 "when",
803 value=True,
804 ),
805 ),
806 (
807 "postcheck-inverted",
808 _task_copy_named_with_value(
809 tasks,
810 "Assert the provisioned libclang binding actually imports",
811 "when",
812 value="ansible_check_mode",
813 ),
814 ),
815 )
816
817
818def _ansible_mutation_failures(document: object) -> list[str]:
819 """Prove skip, argv, status, failure, and apply-boundary mutations fire."""
820 failures = []
821 if dev_box_uv_task_findings(document):
822 failures.append("live dev-box uv Ansible contract failed")
823 documents = _ansible_mutation_documents(_tasks(document))
824 failures.extend(
825 f"uv Ansible mutation passed: {label}"
826 for label, mutated in documents
827 if not dev_box_uv_task_findings(mutated)
828 )
829 return failures
830
831
832def uv_cache_policy_selftest(root: Path) -> list[str]:
833 """Prove each security, status, shell, and Ansible binding leg must fire."""
834 bootstrap = (root / "scripts/dev/bootstrap_uv.py").read_text(encoding="utf-8")
835 mode_test = (root / "scripts/dev/bootstrap_uv_mode_selftest.py").read_text(encoding="utf-8")
836 provisioner = (root / "scripts/dev/provision_dev_box_toolchain.sh").read_text(encoding="utf-8")
837 provisioner_selftest = (
838 root / "scripts/dev/provision_dev_box_toolchain_selftest.bash"
839 ).read_text(encoding="utf-8")
840 gate = (root / "scripts/ci/gates/checks.sh").read_text(encoding="utf-8")
841 transaction = yaml.safe_load(
842 (root / "infra/ansible/roles/dev_box/tasks/transaction.yml").read_text(encoding="utf-8")
843 )
844 return [
845 *_bootstrap_mutation_failures(bootstrap, mode_test),
846 *provisioner_mutation_failures(provisioner, provisioner_selftest),
847 *_gate_mutation_failures(gate),
848 *_ansible_mutation_failures(transaction),
849 ]