3"""Semantic uv-cache bootstrap, provisioner, and Ansible policy checks."""
5from __future__
import annotations
10from pathlib
import Path
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,
21from python_lock_policy_uv_cache_release
import (
23 provisioner_mutation_failures,
26BOOTSTRAP_MODULE_SHA256 =
"08ff0ed4479863f0ba63742da1a8f2411d19135301d2f3eebf694a18aaddcb15"
27MODE_TEST_MODULE_SHA256 =
"f2fbbd678ea0c8a23a4004788b9881f3b0511c4e2e579e347f5ca590f4a2365f"
28PORTABLE_REGISTRY_DIGEST =
"f4716c7f8a12aa6b22c092304d68978b98af975220dbe4099b64f6e8facd3cfe"
29MODE_EXECUTION_REGISTRY_DIGEST =
"579c40124d7f2206583682aadf91a241f9363cc2e47826d5810e87e1a8d540ea"
32def _function(tree: ast.AST, name: str) -> ast.FunctionDef |
None:
33 """Return one top-level function definition, rejecting ambiguity."""
36 for node
in getattr(tree,
"body", [])
37 if isinstance(node, ast.FunctionDef)
and node.name == name
39 return matches[0]
if len(matches) == 1
else None
42def _without_docstring(function: ast.FunctionDef) -> ast.Module:
43 """Return a comparable body without its optional documentation literal."""
44 body = list(function.body)
47 and isinstance(body[0], ast.Expr)
48 and isinstance(body[0].value, ast.Constant)
49 and isinstance(body[0].value.value, str)
52 return ast.Module(body=body, type_ignores=[])
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)
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)
64 message = f
"canonical function fixture is missing {name}"
65 raise ValueError(message)
66 return _body_dump(function)
69def _direct_call_count(function: ast.FunctionDef, name: str) -> int:
70 """Count direct top-level expression calls within one function body."""
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
80def _all_call_count(function: ast.FunctionDef, name: str) -> int:
81 """Count calls within one function while excluding nested definitions."""
83 pending = list(function.body)
86 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
89 isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == name
91 pending.extend(ast.iter_child_nodes(node))
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):
99 if isinstance(node, ast.Attribute):
100 parent = _attribute_path(node.value)
101 return f
"{parent}.{node.attr}" if parent
else ""
105def _deep_qualified_reference_count(function: ast.FunctionDef, owner: str, name: str) -> int:
106 """Count exact module attributes throughout one selftest function."""
108 isinstance(node, ast.Attribute)
109 and _attribute_path(node.value) == owner
110 and node.attr == name
111 for node
in ast.walk(function)
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
127 findings.append(
"bootstrap run_selftest does not directly execute cache_mode_selftest once")
131def _bootstrap_main_guard_findings(tree: ast.Module) -> list[str]:
132 """Bind typed apply-required status to the production script entrypoint."""
136if __name__ == "__main__":
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
147 include_attributes=
False,
151 for statement
in tree.body
152 if ast.dump(statement, include_attributes=
False) == expected
156 for node
in tree.body
157 if isinstance(node, ast.ClassDef)
and node.name ==
"CacheApplyRequiredError"
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")
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")
170 "validated_cached_payload": 1,
171 "authenticated_cache_fds": 1,
173 "probe_authenticated_uv": 1,
174 "verify_fd_unchanged": 2,
177 if function
is None or payload
is None:
178 return [
"bootstrap verify_cached_uv is missing or ambiguous"]
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
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
192def _mode_runner_findings(tree: ast.Module) -> list[str]:
193 """Bind the public runner to every critical adversarial test leg."""
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()
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"]
230def _mode_cache_references() -> dict[str, tuple[tuple[str, str, int], ...]]:
231 """Return critical cache-open/read selftest references."""
233 "darwin_root_alias_acceptance_selftest": (
234 (
"",
"open_simulated_darwin_parent", 1),
235 (
"b.bootstrap_uv_exec",
"open_parent_components", 1),
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),
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),
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),
260 "cache_nonregular_selftest": (
262 (
"socket",
"socket", 1),
263 (
"b",
"open_cache_fd", 1),
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),
271 "expect_concurrent_read_rejected": (
273 (
"b",
"open_cache_fd", 1),
274 (
"b",
"read_stable_fd", 1),
275 (
"b",
"expect_bootstrap_error", 1),
277 "cache_verification_fifo_race_selftest": (
279 (
"b",
"verify_cached_uv", 1),
280 (
"b",
"expect_bootstrap_error", 1),
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()
290 **_mode_cache_references(),
292 **portable_references,
295 *_registry_findings(portable_references, PORTABLE_REGISTRY_DIGEST,
"portable uv execution"),
296 *_registry_findings(mode_references, MODE_EXECUTION_REGISTRY_DIGEST,
"uv mode execution"),
298 for function_name, references
in required.items():
299 function = _function(tree, function_name)
301 findings.append(f
"uv mode selftest critical function is missing: {function_name}")
303 for owner, name, expected
in references:
305 _deep_qualified_reference_count(function, owner, name)
307 else _all_call_count(function, name)
309 if actual != expected:
311 f
"uv mode selftest {function_name} {owner}.{name} call chain drifted"
316def _registry_findings(
317 references: dict[str, tuple[tuple[str, str, int], ...]],
318 expected_digest: 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"]
328def bootstrap_uv_findings(bootstrap: str, mode_test: str) -> list[str]:
329 """Return semantic bootstrap/selftest binding findings."""
330 identity_findings = (
332 if hashlib.sha256(bootstrap.encode()).hexdigest() == BOOTSTRAP_MODULE_SHA256
333 else [
"uv bootstrap module byte identity drifted"]
335 if hashlib.sha256(mode_test.encode()).hexdigest() != MODE_TEST_MODULE_SHA256:
336 identity_findings.append(
"uv mode selftest module byte identity drifted")
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}"]
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),
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")
359 return [
"Python-authority gate body is unterminated"]
361 " ".join(line.strip().split())
362 for line
in body.splitlines()
363 if line.strip()
and not line.lstrip().startswith(
"#")
366 "/bin/bash -p scripts/dev/provision_dev_box_toolchain.sh --selftest-uv-cache-contract"
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"]
376def _tasks(document: object) -> list[dict[str, object]]:
377 """Return one typed Ansible task list."""
378 if not isinstance(document, list):
380 return [task
for task
in document
if isinstance(task, dict)]
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
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
395def _check_task_findings(check: dict[str, object] |
None) -> list[str]:
396 """Validate the forced read-only Ansible check task."""
397 findings: list[str] = []
401 "scripts/dev/provision_dev_box_toolchain.sh",
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")
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"
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"]
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"]
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")
450def _ansible_invocation_findings(tasks: list[dict[str, object]]) -> list[str]:
451 """Reject any third or missing provisioner command boundary."""
455 "scripts/dev/provision_dev_box_toolchain.sh",
458 apply_argv = [
"/bin/bash",
"-p",
"scripts/dev/provision_dev_box_toolchain.sh"]
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"]
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")
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),
482def uv_cache_policy_findings(root: Path) -> list[str]:
483 """Read and validate every uv-cache control-plane source."""
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(
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")
497 except (OSError, UnicodeError, yaml.YAMLError)
as exc:
498 return [f
"uv-cache policy input is unreadable: {exc}"]
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),
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)
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)
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)
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}() {{"]
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"
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(),
545 " return bootstrap_uv_exec.open_regular_nofollow(path)\n",
546 " return os.open(path, os.O_RDONLY)\n",
549 " bootstrap_uv_exec.write_atomic_nofollow(path, payload, mode)\n",
550 " path.write_bytes(payload)\n",
553 " reopened = open_cache_fd(path)\n",
554 " path_state = os.lstat(path)\n",
557 "if any(getattr(before, field) != getattr(after, field) for field in stable):",
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",'),
564 " verify_cached_modes(destination.parent / asset_name, destination)\n",
567 (
' "--run",\n',
' "--disabled-run",\n'),
569 " completed = bootstrap_uv_exec.run_uv_snapshot(binary, arguments)\n",
570 " completed = None\n",
573 " return propagate_child_status(completed.returncode)\n",
574 " return completed.returncode\n",
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",
586 (
"raise SystemExit(2) from error",
"raise SystemExit(1) from error"),
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)
596def _mode_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
597 """Prove every mode runner leg and critical test body is load-bearing."""
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))
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",
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,
""))
631 return [*failures, *_mode_body_mutation_failures(bootstrap, mode_test)]
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",
642 "unsupported hardcoded Python passed the uv mode policy"
643 for name
in interpreter_mutations
644 if not bootstrap_uv_findings(
646 mutate_named_function_once(
650 '"/usr/bin/python3"',
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",
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))
689def _bootstrap_mutation_failures(bootstrap: str, mode_test: str) -> list[str]:
690 """Prove the live bootstrap and every mutation-sensitive seam."""
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")
700 *_bootstrap_source_mutation_failures(bootstrap, mode_test),
701 *_mode_mutation_failures(bootstrap, mode_test),
705def _gate_mutation_failures(gate: str) -> list[str]:
706 """Prove the runtime provisioner selftest cannot leave its real gate."""
708 if gate_selftest_findings(gate):
709 failures.append(
"live Python-authority uv selftest binding failed")
711 " /bin/bash -p scripts/dev/provision_dev_box_toolchain.sh --selftest-uv-cache-contract\n"
713 mutated = _mutate_once(gate, line,
"")
714 if not gate_selftest_findings(mutated):
715 failures.append(
"uv gate selftest mutation passed")
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)
726 message = f
"selftest task is missing: {register}"
727 raise ValueError(message)
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
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)
753 message = f
"selftest task is missing: {name}"
754 raise ValueError(message)
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"]
769 for task
in copy.deepcopy(tasks)
770 if task.get(
"register") !=
"dev_box_provision_check"
775 _task_copy_with_argv(tasks,
"dev_box_provision_check", apply_argv),
779 _task_copy_with_value(tasks,
"dev_box_provision_check",
"check_mode", value=
None),
783 _task_copy_with_value(tasks,
"dev_box_provision_check",
"become", value=
True),
787 _task_copy_with_value(tasks,
"dev_box_provision_check",
"changed_when", value=
True),
791 _task_copy_with_value(tasks,
"dev_box_provision_check",
"failed_when", value=
False),
794 "apply-during-check",
795 _task_copy_with_value(tasks,
"dev_box_provision",
"when", value=
"ansible_check_mode"),
798 "postcheck-unconditional",
799 _task_copy_named_with_value(
801 "Assert the provisioned libclang binding actually imports",
807 "postcheck-inverted",
808 _task_copy_named_with_value(
810 "Assert the provisioned libclang binding actually imports",
812 value=
"ansible_check_mode",
818def _ansible_mutation_failures(document: object) -> list[str]:
819 """Prove skip, argv, status, failure, and apply-boundary mutations fire."""
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))
825 f
"uv Ansible mutation passed: {label}"
826 for label, mutated
in documents
827 if not dev_box_uv_task_findings(mutated)
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")
845 *_bootstrap_mutation_failures(bootstrap, mode_test),
846 *provisioner_mutation_failures(provisioner, provisioner_selftest),
847 *_gate_mutation_failures(gate),
848 *_ansible_mutation_failures(transaction),