Repository navigation
Expand file tree
/
Copy pathverify_release.py
More file actions
executable file
·3470 lines (3226 loc) · 138 KB
/
Copy pathverify_release.py
File metadata and controls
executable file
·3470 lines (3226 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Run reproducible AILM release profiles and emit an evidence receipt.
``quick`` is the developer loop: environment, formatting, lint, typing, all
portable tests excluding recorder replay and prepared publication/template contexts,
and a bounded gate audit. ``full`` is publication
acceptance: the same static checks, the complete coverage suite (including
isolated recorder replay), a repeated locked offline wheel/source-distribution
build with artifact digests, network-recorder claim bindings plus the live cache
audit, a machine-readable gate audit, the generated Lean
bridge plus its build and negative control, hydrated manuscript and documentation
trees, figures and their registry, template Stage 03 rendering, qpdf and structural
PDF checks, then template Stage 04 validation.
The receipt records every command, exit status, duration, log path, interpreter,
deterministic build environment, Git commit, content-sensitive snapshots of
unstaged/staged/untracked state, and the ignored external-call cache that the
full profile consumes. Git, uv, Lake, and qpdf are resolved without caller
``PATH`` and bound by availability, realpath, bytes, digest, and version result.
The distribution step records each package filename,
byte size, and SHA-256 digest in its receipt row. The template checkout is an equally fingerprinted release
input; an explicit ``TEMPLATE_REPO_ROOT`` is final and never silently replaced by
a fallback checkout. ``full`` refuses either dirty input unless the
development-only override is explicit; ``quick`` may start dirty but still fails
if the run changes any recorded input state. Generated output remains under
``output/``; stable publication surfaces are tracked and transient render
products are ignored.
The sidecar interpreter identity and stdlib-only startup are prerequisites:
invoke this script as ``.venv/bin/python -I -S scripts/verify_release.py ...``.
``-I -S`` prevents caller or virtual-environment startup code from executing
before the script can audit the release boundary. Sidecar Python steps use the
same flags and a controlled bootstrap that adds only the audited source and
site-packages directories without processing ``.pth`` files. A non-isolated,
site-enabled, bare-interpreter, or sidecar ``uv run`` invocation is refused
before any inventory or step runs. The two template steps still use that
repository's locked ``uv run`` contract.
"""
from __future__ import annotations
import argparse
import base64
import csv
import hashlib
import json
import os
import pwd
import re
import secrets
import stat
import subprocess
import sys
import time
import tomllib
from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass, replace
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ailm.publication_derivative import (
AttestationResult,
DerivativeContract,
DerivativeState,
)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_RECEIPT = PROJECT_ROOT / "output" / "reports" / "release-receipt.json"
SCHEMA = "ailm-release-receipt-v7"
TEMPLATE_PROJECT = "working/active_inference_language_model"
COMBINED_PDF = PROJECT_ROOT / "output" / "pdf" / "active_inference_language_model_combined.pdf"
DISTRIBUTION_MARKER = "AILM_DISTRIBUTION_ARTIFACT "
RELEASE_UV_CONFIG = PROJECT_ROOT / "release-uv.toml"
CONTROLLED_RUNNER_MARKER = "--_ailm-controlled-python"
ATOMIC_TEMP_HEX_LENGTH = 32
TOOL_VERSION_ARGUMENTS: dict[str, tuple[str, ...]] = {
"git": ("--version",),
"uv": ("--version",),
"lake": ("--version",),
"qpdf": ("--version",),
}
APPROVED_EXECUTABLE_PTH_SHA256 = {
(
"coverage",
"a1_coverage.pth",
): "ef2ed06d19867ec669c09a804060666a9cd5e383af0a9d11aa2de79b77d448e8",
("setuptools", "distutils-precedence.pth"): (
"2638ce9e2500e572a5e0de7faed6661eb569d1b696fcba07b0dd223da5f5d224"
),
}
# Release steps inherit only operating-system context needed to launch local
# tools. Test/build behavior is set below, never inherited. In particular,
# PYTEST_ADDOPTS=--collect-only can otherwise make every pytest gate exit zero
# without executing a test; PYTHONOPTIMIZE can erase assert statements; proxy
# variables can reroute nominally loopback benchmark traffic; and tool-specific
# config variables can replace the checked-in configuration. The dedicated local
# benchmark origin is deliberately inherited, recorded and validated by its owner.
RELEASE_ENV_ALLOWLIST = frozenset(
{
"HOME",
"AILM_OLLAMA_ENDPOINT",
"AILM_GNN_UPSTREAM",
"LANG",
"LC_ALL",
"LC_CTYPE",
"LOGNAME",
"OPENROUTER_API_KEY",
"SHELL",
"TEMP",
"TERM",
"TMP",
"TMPDIR",
"USER",
}
)
PYTEST_PASSED_RE = re.compile(r"(?<!\d)(?P<count>\d+)\s+passed\b")
PYTEST_SKIPPED_RE = re.compile(r"(?<!\d)(?P<count>\d+)\s+skipped\b")
PYTEST_XFAILED_RE = re.compile(r"(?<!\d)(?P<count>\d+)\s+xfailed\b")
COVERAGE_TOTAL_RE = re.compile(r"^TOTAL\s+.*?\s(?P<percent>\d+(?:\.\d+)?)%\s*$", re.MULTILINE)
@dataclass(frozen=True, slots=True)
class Step:
"""One bounded subprocess in a release profile."""
name: str
argv: tuple[str, ...]
timeout_seconds: int
depends_on: tuple[str, ...] = ()
cwd: str | None = None
environment_overrides: tuple[tuple[str, str], ...] = ()
forbid_pytest_skips: bool = False
@dataclass(frozen=True, slots=True)
class RepositoryState:
"""Content-sensitive snapshot of every Git-visible repository state."""
head: str
branch: str
status: tuple[str, ...]
unstaged_sha256: str
staged_sha256: str
untracked_sha256: str
index_flags: tuple[str, ...]
fingerprint: str
@property
def dirty(self) -> bool:
"""Whether tracked, staged, or untracked state differs from ``HEAD``."""
return bool(self.status)
def _login_home() -> Path:
"""Return the account home without trusting an inherited ``HOME`` value."""
return Path(pwd.getpwuid(os.getuid()).pw_dir)
def _trusted_tool_directories() -> tuple[Path, ...]:
"""Return the fixed executable search path, independent of caller ``PATH``."""
home = _login_home()
system_root = Path(Path(sys.executable).anchor)
configured_system_paths = tuple(
Path(path) for path in (os.confstr("CS_PATH") or "").split(os.pathsep) if path
)
candidates = (
*configured_system_paths,
system_root / "usr" / "local" / "bin",
system_root / "usr" / "local" / "sbin",
home / ".local" / "bin",
home / ".cargo" / "bin",
home / ".elan" / "bin",
system_root / "opt" / "homebrew" / "bin",
system_root / "opt" / "homebrew" / "sbin",
system_root / "System" / "Cryptexes" / "App" / "usr" / "bin",
system_root / "usr" / "sbin",
system_root / "sbin",
system_root / "Library" / "Apple" / "usr" / "bin",
system_root / "Library" / "TeX" / "texbin",
)
unique: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
text = str(candidate)
if text not in seen:
seen.add(text)
unique.append(candidate)
return tuple(unique)
def _sanitized_path() -> str:
"""Return the release ``PATH`` assembled only from fixed locations."""
return os.pathsep.join(str(path) for path in _trusted_tool_directories())
def _base_release_environment() -> dict[str, str]:
"""Return approved OS/network context plus a caller-independent executable path."""
environment = {
name: value for name, value in os.environ.items() if name in RELEASE_ENV_ALLOWLIST
}
environment["HOME"] = str(_login_home())
environment["PATH"] = _sanitized_path()
return environment
def _resolve_executable(name: str) -> Path | None:
"""Select one executable only through the fixed release search path.
The returned path deliberately preserves the requested basename. Dispatch
proxies such as elan's ``lake`` change behavior from ``argv[0]``; executing
their resolved ``elan-init`` target is a different command. The tool receipt
separately resolves and fingerprints the exact regular-file target.
"""
if name not in TOOL_VERSION_ARGUMENTS:
raise ValueError(f"unsupported release tool: {name!r}")
for directory in _trusted_tool_directories():
candidate = directory / name
try:
metadata = candidate.stat()
resolved = candidate.resolve(strict=True)
resolved_metadata = resolved.stat()
except (FileNotFoundError, OSError, RuntimeError):
continue
if (
stat.S_ISREG(metadata.st_mode)
and stat.S_ISREG(resolved_metadata.st_mode)
and os.access(candidate, os.X_OK)
):
return candidate.absolute()
return None
def _read_regular_file_identity(path: Path) -> dict[str, object]:
"""Fingerprint one resolved regular file through the descriptor that is read."""
descriptor = os.open(
path,
os.O_RDONLY
| getattr(os, "O_NOFOLLOW", 0)
| getattr(os, "O_CLOEXEC", 0)
| getattr(os, "O_NONBLOCK", 0),
)
try:
metadata = os.fstat(descriptor)
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(f"executable is not a regular file: {path}")
digest = hashlib.sha256()
size = 0
while chunk := os.read(descriptor, 1024 * 1024):
digest.update(chunk)
size += len(chunk)
finally:
os.close(descriptor)
return {
"realpath": str(path),
"sha256": digest.hexdigest(),
"size_bytes": size,
"mode": metadata.st_mode,
"device": metadata.st_dev,
"inode": metadata.st_ino,
}
def _tool_identity(name: str, *, check_version: bool) -> dict[str, object]:
"""Bind one external executable's path, bytes, and version result."""
invocation = _resolve_executable(name)
row: dict[str, object] = {
"name": name,
"available": invocation is not None,
"usable": False,
"path": str(invocation) if invocation is not None else None,
"realpath": None,
"sha256": None,
"size_bytes": 0,
"mode": None,
"device": None,
"inode": None,
"version_argv": None,
"version_checked": check_version,
"version_exit_code": None,
"version_output": None,
"error": None,
}
if invocation is None:
row["error"] = f"{name} was not found in the fixed release search path"
return row
try:
resolved = invocation.resolve(strict=True)
row.update(_read_regular_file_identity(resolved))
except (OSError, ValueError) as error:
row["available"] = False
row["error"] = str(error)
return row
if not check_version:
row["error"] = "version invocation suppressed after an earlier refusal"
return row
argv = (str(invocation), *TOOL_VERSION_ARGUMENTS[name])
version_cwd = PROJECT_ROOT / "formal" if name == "lake" else PROJECT_ROOT
try:
result = subprocess.run(
argv,
cwd=version_cwd,
env=_base_release_environment(),
capture_output=True,
text=True,
check=False,
timeout=30,
)
except (OSError, subprocess.TimeoutExpired) as error:
row["version_argv"] = list(argv)
row["error"] = f"version invocation failed: {error}"
return row
output = (result.stdout + result.stderr).strip()
row.update(
{
"version_argv": list(argv),
"version_exit_code": result.returncode,
"version_output": output[-2000:],
"usable": result.returncode == 0,
"error": None if result.returncode == 0 else "version command returned nonzero",
}
)
return row
def _toolchain_state(*, check_versions: bool) -> dict[str, object]:
"""Fingerprint the fixed external toolchain for the release receipt."""
rows = {
name: _tool_identity(name, check_version=check_versions) for name in TOOL_VERSION_ARGUMENTS
}
encoded = json.dumps(rows, sort_keys=True, separators=(",", ":")).encode("utf-8")
return {
"schema": "ailm-release-toolchain-v2",
"path_policy": "fixed-search-path-preserve-dispatch-basename-v2",
"PATH": _sanitized_path(),
"tools": rows,
"fingerprint": hashlib.sha256(encoded).hexdigest(),
}
def _tool_path(toolchain: Mapping[str, object], name: str) -> str:
"""Return a usable fingerprinted tool path or a fail-closed sentinel."""
tools = toolchain.get("tools")
if not isinstance(tools, Mapping):
raise ValueError("toolchain receipt has no tool map")
row = tools.get(name)
if not isinstance(row, Mapping):
raise ValueError(f"toolchain receipt has no {name!r} entry")
path = row.get("path")
if row.get("usable") is True and isinstance(path, str):
return path
return str(Path(Path(sys.executable).anchor) / "__ailm_missing_or_unusable_tool__" / name)
def _venv_site_packages(root: Path = PROJECT_ROOT) -> Path:
"""Return the sidecar site-packages path without importing :mod:`site`."""
return (
root.resolve()
/ ".venv"
/ "lib"
/ f"python{sys.version_info.major}.{sys.version_info.minor}"
/ "site-packages"
)
def _record_owned_paths(site_packages: Path) -> dict[str, tuple[str, str | None]]:
"""Map installed paths to their distribution and RECORD digest."""
owned: dict[str, tuple[str, str | None]] = {}
for record in sorted(site_packages.glob("*.dist-info/RECORD")):
try:
metadata = record.lstat()
if not stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
continue
distribution = record.parent.name.removesuffix(".dist-info")
metadata_path = record.parent / "METADATA"
if metadata_path.is_file() and not metadata_path.is_symlink():
for line in metadata_path.read_text(
encoding="utf-8", errors="replace"
).splitlines():
if line.startswith("Name: "):
distribution = line.removeprefix("Name: ").strip().casefold()
break
with record.open("r", encoding="utf-8", newline="") as handle:
for row in csv.reader(handle):
if len(row) < 3:
continue
raw_path, digest, _size = row[:3]
if (
raw_path
and not Path(raw_path).is_absolute()
and ".." not in Path(raw_path).parts
):
owned[Path(raw_path).as_posix()] = (distribution, digest or None)
except (OSError, UnicodeError, csv.Error):
continue
return owned
def _record_digest_matches(content: bytes, recorded: str | None) -> bool:
"""Whether a RECORD sha256 entry authenticates ``content``."""
if recorded is None or not recorded.startswith("sha256="):
return False
encoded = base64.urlsafe_b64encode(hashlib.sha256(content).digest()).decode("ascii")
return encoded.rstrip("=") == recorded.removeprefix("sha256=")
def _startup_customization_candidates(site_packages: Path) -> tuple[Path, ...]:
"""Return venv modules that :mod:`site` would import implicitly."""
candidates: list[Path] = []
for stem in ("sitecustomize", "usercustomize"):
candidates.extend(sorted(site_packages.glob(f"{stem}.*")))
package = site_packages / stem
if package.exists() or package.is_symlink():
candidates.append(package)
return tuple(dict.fromkeys(candidates))
def _venv_startup_state(root: Path = PROJECT_ROOT) -> dict[str, object]:
"""Audit every implicit venv startup surface without executing one.
Sidecar commands run with ``-S`` and therefore do not process these files.
The inventory nevertheless fails closed on customizers, symlinked, unsafe,
unowned, or unknown executable ``.pth`` entries so a later command cannot
silently regress to ordinary :mod:`site` startup.
"""
site_packages = _venv_site_packages(root)
errors: list[str] = []
entries: list[dict[str, object]] = []
project = root.resolve()
current = project
for component in site_packages.relative_to(project).parts:
current /= component
try:
component_metadata = current.lstat()
except OSError as error:
errors.append(f"virtual-environment path component is unavailable: {current}: {error}")
break
if not stat.S_ISDIR(component_metadata.st_mode) or stat.S_ISLNK(component_metadata.st_mode):
errors.append(f"virtual-environment path component is not a real directory: {current}")
break
if component_metadata.st_uid not in {0, os.getuid()}:
errors.append(
f"virtual-environment path component has unsafe owner uid "
f"{component_metadata.st_uid}: {current}"
)
break
try:
directory_metadata = site_packages.lstat()
except OSError as error:
return {
"schema": "ailm-venv-startup-surface-v1",
"site_packages": str(site_packages),
"controlled_import_paths": [],
"pth_entries": [],
"customization_modules": [],
"integrity_ok": False,
"errors": [f"site-packages is unavailable: {error}"],
"fingerprint": None,
}
if not stat.S_ISDIR(directory_metadata.st_mode) or stat.S_ISLNK(directory_metadata.st_mode):
errors.append("site-packages is not a real directory")
if directory_metadata.st_uid not in {0, os.getuid()}:
errors.append(f"site-packages has unsafe owner uid {directory_metadata.st_uid}")
customizers = _startup_customization_candidates(site_packages)
if customizers:
errors.extend(
f"implicit Python customization module is present: {path.name}" for path in customizers
)
owned = _record_owned_paths(site_packages)
project_source = (root.resolve() / "src").resolve()
for path in sorted(site_packages.glob("*.pth")):
entry: dict[str, object] = {
"name": path.name,
"owner": None,
"record_sha256": None,
"sha256": None,
"size_bytes": 0,
"mode": None,
"uid": None,
"executable_directives": [],
"path_directives": [],
"inert_under_controlled_startup": True,
"integrity_ok": False,
"errors": [],
}
entry_errors: list[str] = []
try:
metadata = path.lstat()
entry["mode"] = metadata.st_mode
entry["uid"] = metadata.st_uid
if not stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
raise ValueError("entry is not a real regular file")
if metadata.st_uid not in {0, os.getuid()}:
raise ValueError(f"entry has unsafe owner uid {metadata.st_uid}")
if stat.S_IMODE(metadata.st_mode) & 0o111:
raise ValueError("entry has executable filesystem mode")
descriptor = os.open(
path,
os.O_RDONLY
| getattr(os, "O_NOFOLLOW", 0)
| getattr(os, "O_CLOEXEC", 0)
| getattr(os, "O_NONBLOCK", 0),
)
try:
opened_metadata = os.fstat(descriptor)
if not stat.S_ISREG(opened_metadata.st_mode):
raise ValueError("opened entry is not a regular file")
if (opened_metadata.st_dev, opened_metadata.st_ino) != (
metadata.st_dev,
metadata.st_ino,
):
raise ValueError("entry changed while its identity was captured")
bounded = bytearray()
while chunk := os.read(descriptor, 1024 * 1024 + 1 - len(bounded)):
bounded.extend(chunk)
if len(bounded) > 1024 * 1024:
raise ValueError("entry exceeds the bounded startup-surface size")
content = bytes(bounded)
finally:
os.close(descriptor)
entry["size_bytes"] = len(content)
entry["sha256"] = hashlib.sha256(content).hexdigest()
owner = owned.get(path.name)
if owner is None and path.name == "_virtualenv.pth":
sibling = site_packages / "_virtualenv.py"
if content not in {b"import _virtualenv", b"import _virtualenv\n"}:
raise ValueError("canonical uv virtualenv bootstrap content changed")
sibling_metadata = sibling.lstat()
if (
not stat.S_ISREG(sibling_metadata.st_mode)
or stat.S_ISLNK(sibling_metadata.st_mode)
or sibling_metadata.st_uid not in {0, os.getuid()}
):
raise ValueError("canonical uv virtualenv bootstrap module is unsafe")
distribution = "uv-virtualenv-bootstrap"
recorded_digest = None
elif owner is None:
raise ValueError("entry is not owned by an installed distribution RECORD")
else:
distribution, recorded_digest = owner
if not _record_digest_matches(content, recorded_digest):
raise ValueError("entry bytes do not match their distribution RECORD")
entry["owner"] = distribution
entry["record_sha256"] = recorded_digest
executable_lines: list[str] = []
path_lines: list[str] = []
for raw_line in content.decode("utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("import ") or line.startswith("import\t"):
executable_lines.append(line)
else:
path_lines.append(line)
entry["executable_directives"] = executable_lines
entry["path_directives"] = path_lines
if executable_lines and distribution != "uv-virtualenv-bootstrap":
approved_digest = APPROVED_EXECUTABLE_PTH_SHA256.get((distribution, path.name))
if approved_digest is None:
raise ValueError("entry contains an unapproved executable directive")
if entry["sha256"] != approved_digest:
raise ValueError("approved executable entry bytes changed")
for directive in path_lines:
candidate = Path(directive)
if not candidate.is_absolute():
candidate = site_packages / candidate
resolved = candidate.resolve(strict=True)
if resolved != project_source and site_packages not in resolved.parents:
raise ValueError(f"entry exposes an uncontrolled import path: {resolved}")
entry["integrity_ok"] = True
except (OSError, RuntimeError, UnicodeError, ValueError) as error:
entry_errors.append(str(error))
entry["errors"] = entry_errors
errors.extend(f"{path.name}: {error}" for error in entry_errors)
entries.append(entry)
payload = {
"schema": "ailm-venv-startup-surface-v1",
"site_packages": str(site_packages),
"controlled_import_paths": [
str(root.resolve() / "src"),
str(root.resolve()),
str(site_packages),
],
"pth_entries": entries,
"customization_modules": [str(path) for path in customizers],
"integrity_ok": not errors,
"errors": errors,
}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
payload["fingerprint"] = hashlib.sha256(encoded).hexdigest()
return payload
def _startup_errors(state: Mapping[str, object]) -> list[str]:
"""Narrow the startup receipt's error field at each consumption boundary."""
value = state.get("errors")
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
return ["virtual-environment startup receipt has a malformed errors field"]
return value
def _project_python_error(root: Path = PROJECT_ROOT) -> str | None:
"""Explain why this process is not the sidecar's explicitly addressed Python."""
expected = root.resolve() / ".venv" / "bin" / "python"
actual = Path(sys.executable).absolute()
if os.environ.get("UV_RUN_RECURSION_DEPTH") is not None:
return (
"release orchestration was launched through uv run; invoke the sidecar "
f"interpreter directly as {expected}"
)
if actual != expected:
return (
f"release orchestration must be invoked as {expected}; this process is "
f"{actual}. Do not use uv run or a bare Python executable in the sidecar"
)
if not expected.is_file() or not os.access(expected, os.X_OK):
return f"project interpreter is missing or not executable: {expected}"
return None
def _project_python(root: Path = PROJECT_ROOT) -> str:
"""Return the exact sidecar interpreter or fail before building an inventory."""
error = _project_python_error(root)
if error is not None:
raise RuntimeError(error)
return str(root.resolve() / ".venv" / "bin" / "python")
def _isolated_startup_error() -> str | None:
"""Explain why this process began before stdlib-only isolation was established."""
if not sys.flags.isolated or not sys.flags.no_site:
return (
"release orchestration requires isolated, stdlib-only Python startup; invoke "
".venv/bin/python -I -S scripts/verify_release.py so PYTHONPATH, .pth files, "
"sitecustomize, and usercustomize cannot execute before the release boundary"
)
return None
def _controlled_python_argv(kind: str, target: str, *arguments: str) -> tuple[str, ...]:
"""Build one sidecar Python command that never imports :mod:`site`."""
if kind not in {"module", "script"}:
raise ValueError(f"unsupported controlled Python target kind: {kind!r}")
return (
_project_python(),
"-I",
"-S",
"-B",
str(PROJECT_ROOT / "scripts" / "verify_release.py"),
CONTROLLED_RUNNER_MARKER,
kind,
target,
*arguments,
)
def _run_controlled_python(arguments: Sequence[str]) -> int:
"""Run one module or project script with explicit audited import roots."""
startup_error = _isolated_startup_error()
if startup_error is not None:
print(f"controlled Python startup error: {startup_error}", file=sys.stderr)
return 2
interpreter_error = _project_python_error()
if interpreter_error is not None:
print(f"controlled Python startup error: {interpreter_error}", file=sys.stderr)
return 2
startup_state = _venv_startup_state()
if startup_state["integrity_ok"] is not True:
print(
"controlled Python startup error: unsafe virtual-environment startup "
+ "; ".join(_startup_errors(startup_state)),
file=sys.stderr,
)
return 2
if len(arguments) < 2 or arguments[0] not in {"module", "script"}:
print("controlled Python startup error: malformed target", file=sys.stderr)
return 2
kind, target, *target_arguments = arguments
root = PROJECT_ROOT.resolve()
site_packages = _venv_site_packages(root)
sys.path[:0] = [str(root / "src"), str(root), str(site_packages)]
sys.prefix = str(root / ".venv")
sys.exec_prefix = sys.prefix
import runpy
if kind == "module":
if re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", target) is None:
print(f"controlled Python startup error: invalid module {target!r}", file=sys.stderr)
return 2
sys.argv = [target, *target_arguments]
runpy.run_module(target, run_name="__main__", alter_sys=True)
return 0
relative = Path(target)
if relative.is_absolute() or ".." in relative.parts:
print(f"controlled Python startup error: invalid script path {target!r}", file=sys.stderr)
return 2
script = (root / relative).resolve(strict=True)
try:
script.relative_to(root)
except ValueError:
print(
f"controlled Python startup error: script escapes project root: {script}",
file=sys.stderr,
)
return 2
metadata = script.lstat()
if not stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
print(
f"controlled Python startup error: script is not a regular file: {script}",
file=sys.stderr,
)
return 2
sys.argv = [str(script), *target_arguments]
runpy.run_path(str(script), run_name="__main__")
return 0
def _validate_template_root(candidate: Path, *, project_root: Path | None = None) -> Path:
"""Return one exact template checkout or fail without searching elsewhere."""
sidecar = PROJECT_ROOT if project_root is None else project_root
root = candidate.expanduser().resolve()
project_entry = root / "projects" / TEMPLATE_PROJECT
required = (
root / "infrastructure" / "__init__.py",
root / "scripts" / "pipeline" / "stage_03_render.py",
root / "scripts" / "pipeline" / "stage_04_validate.py",
root / "pyproject.toml",
root / "uv.lock",
project_entry,
)
missing = [
str(path.relative_to(root))
for path in required
if not (path.is_dir() if path == project_entry else path.is_file())
]
if missing:
raise RuntimeError(
f"template root {root} is missing required publication files: " + ", ".join(missing)
)
routed_project = project_entry.resolve()
if routed_project != sidecar.resolve():
raise RuntimeError(
f"template root {root} routes {TEMPLATE_PROJECT} to {routed_project}, "
f"not the audited sidecar {sidecar.resolve()}"
)
return root
def _resolve_template_root(project_root: Path | None = None) -> Path:
"""Resolve the template provider, treating an explicit environment value as final."""
sidecar = PROJECT_ROOT if project_root is None else project_root
explicit = os.environ.get("TEMPLATE_REPO_ROOT", "").strip()
if explicit:
return _validate_template_root(Path(explicit), project_root=sidecar)
# The per-machine ``.template-root`` file is the second explicit source and
# equally final. Its grammar restates ailm.template_root.read_template_root_file
# because this runner must stay importable with the standard library alone.
configured = sidecar / ".template-root"
if configured.is_file():
declared_paths = [
line.strip()
for line in configured.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.strip().startswith("#")
]
if len(declared_paths) != 1:
raise RuntimeError(
f"{configured} must declare exactly one template checkout path, "
f"found {len(declared_paths)}"
)
declared = Path(declared_paths[0]).expanduser()
return _validate_template_root(
declared if declared.is_absolute() else configured.parent / declared,
project_root=sidecar,
)
# The candidate order is byte-identical in scripts/z_generate_manuscript_variables.py
# and scripts/generate_figure_registry.py; tests/test_figure_registry.py holds them to it.
candidates = [
*sidecar.parents,
*(parent / "template" for parent in sidecar.parents[2:3]),
_login_home() / "Documents" / "GitHub" / "template",
]
for candidate in candidates:
if (candidate / "infrastructure" / "__init__.py").is_file():
return _validate_template_root(candidate, project_root=sidecar)
raise RuntimeError(
"could not locate the template checkout required for publication; "
"set TEMPLATE_REPO_ROOT to its exact root"
)
def _gnn_upstream_checkout(root: Path = PROJECT_ROOT) -> Path:
"""Return the ignored checkout the conformance arm materializes and reads.
The path carries no tag, so the runner can name the checkout it expects
without reading the pin: the pin's reader is the released ``gnn.importers``,
which the checkout itself supplies.
"""
return root / "refs" / "gnn-upstream" / "checkout"
def _coverage_floor(root: Path = PROJECT_ROOT) -> int:
"""Return the branch-coverage floor declared once in ``pyproject.toml``.
The floor is ``[tool.coverage.report] fail_under``. ``scripts/record_stage0_claims.py``
publishes the same key as ``claim:stage0_coverage_floor_pct``, and pytest-cov
applies it whenever ``--cov`` is passed, so the release step spells the value
out only so the receipt shows which gate ran; it is never a second copy.
Only the ``full`` profile passes ``--cov``; ``quick``, ``measurement`` and
``contract`` pass ``--no-cov``, so a hosted run never evaluates the floor.
That boundary is deliberate and documented rather than annotated here: the
publication artifact contract compares ``pyproject.toml`` byte-for-byte, so a
comment beside ``fail_under`` cannot ship. A hosted coverage job is admitted
only with its own measured duration and receipt.
"""
pyproject = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
try:
floor = pyproject["tool"]["coverage"]["report"]["fail_under"]
except KeyError as error:
raise RuntimeError(
"pyproject.toml declares no [tool.coverage.report] fail_under; the release "
"coverage gate has no floor to enforce"
) from error
if isinstance(floor, bool) or not isinstance(floor, int) or not 0 < floor <= 100:
raise RuntimeError(f"pyproject.toml fail_under is not a percentage: {floor!r}")
return floor
def _quick_test_workers(cpu_count: int | None = None) -> int:
"""Return the ``pytest-xdist`` worker count for the quick profile's test step.
Half the host's cores, at most four and at least one. Each worker runs JAX,
which multi-threads within the process, so a worker per core oversubscribes
the machine; on a three-core hosted macOS runner four workers made the
negative-control subprocess pytest exceed its own timeout, where a serial
step had passed. The receipt records whatever count the host produced.
"""
cores = (os.cpu_count() or 1) if cpu_count is None else cpu_count
return max(1, min(4, cores // 2))
def _coverage_gate_argument(root: Path = PROJECT_ROOT) -> str:
"""The pytest-cov flag for the declared floor, as recorded in the receipt."""
return f"--cov-fail-under={_coverage_floor(root)}"
#: The input-based markers every hosted profile deselects: their checkouts carry
#: neither the publication template, the ignored raw corpora, nor the CUDA
#: plugin. The hosted test arms divide the remaining suite by mark -- quick runs
#: the portable surface, measurement runs the end-to-end measurement gates, and
#: contract runs the wheel and real-socket contract files -- and quick also
#: ignores the documentation file the docs arm owns by path, so a marked test
#: runs in exactly one hosted job. The rest of the marked files stay full-only,
#: where they ran before the splits.
_HOSTED_TEST_EXCLUSIONS = (
"not recorder_replay and not raw_corpus_regeneration and not requires_cuda12 "
"and not publication_context and not template_context"
)
#: The one test the provenance arm runs: the committed resolved manuscript tree
#: equals a fresh resolution at the audited input-commit epoch (issue #12).
PROVENANCE_TEST_NODE = "tests/test_manuscript_tokens.py::test_real_resolved_tree_is_exactly_current"
def build_steps(
profile: str,
*,
template_root: Path | None = None,
toolchain: Mapping[str, object] | None = None,
publication_derivative: Path | None = None,
derivative_output: Path | None = None,
) -> tuple[Step, ...]:
"""Return the deterministic command inventory for a profile."""
if publication_derivative is not None and profile != "full":
raise ValueError("--publication-derivative is valid only with the full profile")
resolved_toolchain = _toolchain_state(check_versions=True) if toolchain is None else toolchain
uv = _tool_path(resolved_toolchain, "uv")
lake = _tool_path(resolved_toolchain, "lake")
qpdf = _tool_path(resolved_toolchain, "qpdf")
# The GNN conformance arm and the full release both need the upstream parser
# extra; every other arm checks the base environment.
environment_extras = ("--extra", "gnn-interop") if profile in {"full", "gnn"} else ()
environment_steps = (
Step("lock", (uv, "lock", "--check"), 120),
Step(
"environment",
(
uv,
"sync",
"--check",
"--locked",
*environment_extras,
"--python",
_project_python(),
),
300,
depends_on=("lock",),
),
Step(
"environment-compatibility",
(uv, "pip", "check", "--python", _project_python()),
120,
depends_on=("environment",),
),
)
# The static checks are their own arms. Each one runs in exactly one hosted
# job, so the measurement and contract test slices do not repeat them: a
# second copy would gate the same bytes again on a second runner.
format_step = Step(
"format",
_controlled_python_argv("module", "ruff", "format", "--check", "src", "scripts", "tests"),
120,
depends_on=("environment-compatibility",),
)
lint_step = Step(
"lint",
_controlled_python_argv("module", "ruff", "check", "src", "scripts", "tests"),
120,
depends_on=("environment-compatibility",),
)
types_step = Step(
"types",
_controlled_python_argv(
"module",
"mypy",
"--explicit-package-bases",
"src/ailm",
"scripts/verify_release.py",
"scripts/verify_network_claim_bindings.py",
"scripts/verify_publication_derivative.py",
"scripts/_publication_execution.py",
"scripts/_publication_bootstrap.py",
"scripts/_publication_artists.py",
"scripts/_publication_controls.py",
"scripts/_publication_snapshot.py",
"scripts/orchestrate_claim_recorders.py",
"scripts/warm_call_cache.py",
"scripts/record_external_benchmark_claims.py",
"scripts/record_synthetic_benchmark_claims.py",
"scripts/record_incontext_benchmark_claims.py",
"scripts/record_logprob_drift_claims.py",
),
1800,
depends_on=("environment-compatibility",),
)
static_steps = (format_step, lint_step, types_step)
web_steps = (
Step(
"web-model",
_controlled_python_argv("script", "scripts/export_web_model.py"),
1800,
depends_on=("environment-compatibility",),
),
Step(
"web-page",
_controlled_python_argv("script", "scripts/build_web_ailm.py"),
300,
depends_on=("web-model",),
),
)
common = environment_steps + static_steps + web_steps
if profile == "quick":
# The static checks are the lint and types arms and the documentation
# checks are the docs arm, so quick does not repeat them: a hosted job
# runs them once, in the job that owns them. Full keeps static_steps
# because publication acceptance re-checks everything in one receipt.
return (