lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/receipt.py ADDED
@@ -0,0 +1,2385 @@
1
+ # lean-pkg receipt slurm -- a lower-tier receipt from a finished Slurm job
2
+ """`lean-pkg receipt slurm --job J --log PATH --commit SHA [--stdout PATH] [--stderr PATH] [--checker TEXT]
3
+ [--repo DIR] [--redact REGEX ...] [--sacct-file F] [--seal-sacct [--user NAME]] [--out PATH] [--append-readme [--readme-heading TEXT]
4
+ [--readme-line TEXT ...] [--tar-sha256 HEX]] [--json]` (#70): turn a Slurm verification job (its accounting,
5
+ its verify log, its stdout and stderr) into a lower-tier receipt in exactly the shape `gate --receipt`
6
+ validates. It never reads or writes a registry.
7
+ `--template` prints SBATCH_TEMPLATE, a minimal sbatch wrapper that emits every line read below; `--check` (preflight)
8
+ runs every check below that the job's files decide, writes nothing, and names every problem (field report).
9
+
10
+ Checks, all run before anything is written (every failed check is listed; any one refuses, exit 1):
11
+
12
+ 1. Job state: `sacct -j J --format=JobID,State,ExitCode,Elapsed,TotalCPU -P -n` (or that output saved to
13
+ `--sacct-file`, for a host without Slurm; the first three columns suffice, other columns need sacct's
14
+ header line, else `unexpected sacct format`). The main job line (JobID
15
+ equal to J, not a `.batch` or `.extern` step) must say State `COMPLETED` and ExitCode `0:0`.
16
+ 2. Seal. With `--stdout` (the job's `.out` file): its one `verify-log-sha256` line must equal the SHA-256
17
+ of the raw verify log, and its `pre-manifest-sha256` and `post-manifest-sha256` lines must be equal and
18
+ equal the SHA-256 of `lake-manifest.json` committed at the commit. A stdout line is `KEY VALUE` or
19
+ `KEY: VALUE`. Without `--stdout` (fallback): the verify log itself must hold exactly one
20
+ `verify-log-sha256: <hex>` line equal to the SHA-256 of the log with that line removed; the manifest
21
+ check is skipped and says so.
22
+ 3. `--stderr` (the job's `.err` file), when given, must be empty.
23
+ 4. Fields: `lean_toolchain` is `lean-toolchain` committed at the commit and `mathlib_rev` the `mathlib`
24
+ package's rev in `lake-manifest.json` committed there, `none` when that manifest lists no `mathlib`
25
+ package (a package without Mathlib), else (no readable manifest) the log's `mathlib-rev:`; a log
26
+ `lean-toolchain:` / `mathlib-rev:` line that disagrees refuses. `sorry_count` is the log's
27
+ `sorry-count:` line (refused when the log has more `declaration uses 'sorry'` lines than it declares), else
28
+ the number of `declaration uses 'sorry'` lines, counted only when the log shows the
29
+ build finished (`Build completed successfully` or `lake build: ok`; neither refuses); it must be 0. `axioms` is the
30
+ log's `axioms:` line (refused when it omits an axiom the log's own `#print axioms` output reports), else the
31
+ union of its `#print axioms` output (`depends on axioms: [...]`, `does not depend on any axioms`); none of
32
+ either refuses. Names are compared without a universe suffix (`Classical.choice.{u}` is `Classical.choice`).
33
+ `checker` is `--checker`, else the log's `checker:`. A root-package module the log shows Lake restored
34
+ (`Reused`, `Replayed`, `Unpacked`; inside the template's `lean-pkg-build:` markers when present; not after
35
+ the module's own `Built` line, which is a warning replay) refuses: its sorry warning need not be in the log
36
+ (lake_hygiene, `lake_cache_check`).
37
+ Optional log lines `commit:`, `job-id:`, `generated-at:`, `src-head:` (the template's SRC_MODE=clone: the
38
+ full SHA, must be --commit) must agree / parse. A log with no `commit:` line is
39
+ refused without --stdout (the in-log seal binds it to nothing) and WARNed with it (`log_commit_bound: false`).
40
+ Every field but `checker` is read from the RAW log. Without `generated-at:` the
41
+ receipt is stamped with the time of writing; a re-run whose receipt matches the one already written in
42
+ every other field keeps that file's `generated_at` (#85), anything else differing is refused.
43
+ 5. Redaction: the per-job temporary prefixes (DEFAULT_REDACTIONS) and every `--redact REGEX` are replaced
44
+ in the log text; a redaction that removes or alters a line the parser reads refuses (parse_raw_log). The
45
+ public-safety scanner (plus this machine's user and host names and a bare home directory, `_scanner`) then
46
+ runs over the redacted log, the receipt JSON and the README block. Any blocking hit refuses, naming the
47
+ families only. A committed symlink at the commit resolving into `.lean-receipts/` refuses (gate refuses it).
48
+
49
+ Output: `job_id` is `slurm-<J>`; the redacted log `<c12>-slurm-<J>-verify.redacted.log` and the receipt
50
+ `<c12>-slurm-<J>.json` (the name `gate` stores it under) go to `<repo>/.lean-receipts/` (`--out PATH` names
51
+ the receipt, the log goes beside it). `report_sha256` is the SHA-256 of the redacted log as written. With
52
+ `--compress-log` the log is written as `<...>-verify.redacted.log.gz` (deterministic gzip) instead: `report_sha256`
53
+ is still the SHA-256 of the uncompressed log, and the additive `report_compressed` {format: gzip, sha256 of the
54
+ .gz, bytes = the decoded length, not the .gz size} binds the .gz (restore: `gzip -dc X.log.gz > X.log`). A
55
+ differing file already at either path is refused. The README entry block is printed, and with
56
+ `--append-readme` appended to `README.md` beside the receipt. With `--stdout` the seal evidence is persisted
57
+ (#72): the receipt gains the additive keys `job_stdout_sha256` (the job stdout file) and `manifest_sha256`
58
+ (`lake-manifest.json` at the commit), which `gate` ignores, and the README block a `- Seal:` line naming both.
59
+ `--artifacts DIR` (with --stdout; also under --check): the job's artifact seal (the template's ARTIFACTS_DIR):
60
+ sha256(DIR/artifacts.sha256) must be the stdout's `artifacts-manifest-sha256` line and every file under DIR is
61
+ rehashed against that manifest (check_artifacts); the receipt gains `artifacts_manifest_sha256` and the manifest
62
+ is written beside it as an evidence file. Without the flag nothing changes.
63
+ Container (#236, container.py): when the log has the template's `container-engine:`, `container-image:` and
64
+ `container-image-sha256:` (a SIF file) or `container-oci-digest:` (an OCI image) lines, the receipt gains the
65
+ additive `container` {engine, image_sha256 or oci_digest, ref (a home directory shown as ~)}; with --stdout the
66
+ job stdout must carry the same digest line exactly once (an edited line on either side refuses). A log without
67
+ container lines gives a receipt without the key, as before.
68
+ Claim axioms (AX1, claim_axioms.py): when the log has the template's `claim-axioms:` / `claim-missing:` /
69
+ `claim-axioms-done:` lines (ClaimAxioms.lean run after the build on every claim of claims.yaml), the receipt
70
+ gains the additive `claim_axioms` {checked, nonstandard [{decl, axioms}], missing}. A missing claim, a claim on
71
+ sorryAx, a claim of claims.yaml at the commit without a line, an incomplete probe, or a name whose `#print axioms`
72
+ output in the same log disagrees refuses; a redaction that alters one of those lines refuses. A log without them
73
+ gives a receipt without the key, as before.
74
+ Hypotheses section (proposal 0003 stage H1, hypotheses.py): the template's `hyp-probe/1` section (HypProbe.lean,
75
+ after the claim-axioms lines; the Challenge built into a side log, never into this log) is checked for structure
76
+ only: a section without `hyp-done`, counts that do not match it, a line printed twice, a malformed line, a line
77
+ after `hyp-done`, or a redaction that alters a section line refuses. No receipt key: `report_sha256` seals it. A
78
+ log without the section is accepted unchanged.
79
+ Sacct seal (`--seal-sacct`, optional): the job's accounting record is sealed into the receipt exactly as
80
+ `receipt comparator --seal-sacct` seals a comparator receipt (sacct_seal_record): live sacct runs SLURM_SEAL_QUERY
81
+ with zoned times (or `--sacct-file`, saved with its header); Start..End must contain the log's `generated-at:`
82
+ line (required) and the account must be this one (live) or `--user`. The normalized record
83
+ `<c12>-slurm-<J>-sacct.txt` is written beside the receipt and the additive `slurm_sacct` block (slurm-sacct-seal/1)
84
+ binds it; gate_mod.validate_receipt (gate, receipt check, ...) then checks a present block with sacct_seal_problem
85
+ against the record committed at HEAD. Without the flag nothing changes.
86
+ Everything after the executor's own terminal-state check (2. to 5. and the output) is `produce`, shared with
87
+ `receipt systemd` (receipt_systemd.py), which hands it an `Evidence` with its job identity, check lines, README
88
+ lines and extra evidence files.
89
+ """
90
+
91
+ from __future__ import annotations
92
+
93
+ import argparse
94
+ import datetime as dt
95
+ import getpass
96
+ import hashlib
97
+ import json
98
+ import os
99
+ import pathlib
100
+ import re
101
+ import shutil
102
+ import socket
103
+ import subprocess
104
+ import sys
105
+
106
+ from . import claim_axioms as ca
107
+ from . import gate as gate_mod
108
+ from . import core
109
+ from . import container as ctr
110
+ from . import hypotheses as hyp
111
+ from . import lake_hygiene as lh
112
+ from . import public_safety as ps
113
+
114
+ SHA_KEY = "verify-log-sha256"
115
+ # Without --compress-log, a redacted log above this size gets a stderr WARN naming the flag (GitHub refuses a
116
+ # file over 100 MiB); the output is never changed silently.
117
+ LARGE_LOG_WARN_BYTES = 90 << 20
118
+ PRE_KEY, POST_KEY = "pre-manifest-sha256", "post-manifest-sha256"
119
+ LOG_KEYS = ("lean-toolchain", "mathlib-rev", "checker", "sorry-count", "axioms", "commit", "job-id",
120
+ "generated-at", "src-head", *ctr.LOG_KEYS)
121
+ # (regex, replacement): the per-job temporary account prefix and the scratch user directory a Slurm verify
122
+ # script prints (`/tmp/<account>-job-...`, `/tmp/<account>-job123/`, `/scratch/<user>/`).
123
+ USER_TOKEN = "<USER>"
124
+ DEFAULT_REDACTIONS = (
125
+ (r"/tmp/[^/\s<>]+?-job(?=[-\d])", f"/tmp/{USER_TOKEN}-job"),
126
+ (r"/scratch/[^/\s<>]+/", f"/scratch/{USER_TOKEN}/"),
127
+ )
128
+ REDACT_TOKEN = "<redacted>"
129
+ SACCT_FORMAT = "JobID,State,ExitCode,Elapsed,TotalCPU"
130
+ SACCT_TIMEOUT = 60
131
+ _KEY_LINE = re.compile(r"^([a-z0-9-]+):[ \t]*(.*?)[ \t]*$")
132
+ _SHA_LINE = re.compile(rb"^" + SHA_KEY.encode() + rb":[ \t]*([0-9A-Fa-f]{64})[ \t]*\r?$")
133
+ _HEX64 = re.compile(r"[0-9a-fA-F]{64}")
134
+ # Lean 4 prints ``declaration uses `sorry` `` (backticks, every toolchain from v4.29 on); older or
135
+ # re-quoted logs use 'sorry'. Matching only the quoted form left real warnings uncounted (review finding).
136
+ _SORRY_RE = re.compile(r"declaration uses ['`]sorry['`]")
137
+ # Evidence that the build ran to the end, so the absence of sorry warnings is a measured 0 (#82): Lake's own
138
+ # summary line, or the `lake build: ok` line the lab's verify script prints.
139
+ _BUILD_DONE_RE = re.compile(r"Build completed successfully|^lake build: ok\b", re.M)
140
+ _DEPENDS_RE = re.compile(r"depends on axioms:\s*\[([^\]]*)\]")
141
+ _NO_AXIOMS_RE = re.compile(r"does not depend on any axioms")
142
+
143
+ # `receipt slurm --template` (field report): a minimal sbatch wrapper that emits exactly what the receipt reads,
144
+ # so the first long job is receiptable. tests/test_receipt_slurm.py runs it against a fake build.
145
+ SBATCH_TEMPLATE = r"""#!/bin/bash
146
+ # verify.sbatch: a Lean verification job whose files `lean-pkg receipt slurm` accepts
147
+ # (printed by `lean-pkg receipt slurm --template`). Submit it from the package checkout:
148
+ #
149
+ # sbatch verify.sbatch
150
+ # lean-pkg receipt slurm --check --log verify-J.log --stdout verify-J.out --stderr verify-J.err --commit SHA
151
+ # lean-pkg receipt slurm --job J --log verify-J.log --stdout verify-J.out --stderr verify-J.err --commit SHA
152
+ #
153
+ # Run --check on the files of a short trial job before the long one: it names every line still missing.
154
+ # What the receipt reads; keep these lines as they are:
155
+ # stdout (.out): exactly one line each of pre-manifest-sha256, post-manifest-sha256, verify-log-sha256
156
+ # (and container-image-sha256 or container-oci-digest when the tools run in a container)
157
+ # stderr (.err): empty, so every tool writes into the log, never to the job's stderr
158
+ # the log: one line each of checker:, sorry-count:, axioms: (and lean-toolchain:, commit:, job-id:,
159
+ # generated-at:, which must agree with the commit and the job), the claim-axioms lines of
160
+ # every claim in claims.yaml (read from the built environment after the build), the hyp-probe/1
161
+ # section after them (the Challenge is built into $WORK/hyp-challenge-build.log, not this
162
+ # log), the build between the lean-pkg-build: begin / end lines, and no root-package module Lake restored instead of
163
+ # compiling (`Reused`, `Replayed`, `Unpacked`): its sorry warning need not be in the log
164
+ # the job: sacct State COMPLETED, ExitCode 0:0 (any failed step fails the job: set -e)
165
+ #SBATCH --job-name=lean-verify
166
+ #SBATCH --output=verify-%j.out
167
+ #SBATCH --error=verify-%j.err
168
+ #SBATCH --nodes=1
169
+ #SBATCH --ntasks=1
170
+ #SBATCH --cpus-per-task=4
171
+ #SBATCH --mem=16G
172
+ #SBATCH --time=02:00:00
173
+ # An inherited locale the node does not have (C.UTF-8, say) makes bash and other tools print a warning on
174
+ # stderr, which the receipt refuses (stderr must be empty; it is never filtered). The C locale is set for the
175
+ # job's own shell here and again below for every tool it starts; drop neither line.
176
+ #SBATCH --export=ALL,LC_ALL=C,LANG=C,PYTHONUTF8=1
177
+ # Add the partition, account or QOS lines your site requires.
178
+
179
+ set -euo pipefail
180
+ # Exact runtime: the C locale before any tool runs (an sbatch --export on the command line replaces the line above).
181
+ export LC_ALL=C LANG=C PYTHONUTF8=1
182
+ unset LANGUAGE
183
+
184
+ # The package's own commands (placeholders; edit them here or set them when submitting).
185
+ VERIFY_CMD=${VERIFY_CMD:-"lake build"}
186
+ # a file of `#print axioms Name` lines for the theorems the receipt covers. `lake lean FILE`, not
187
+ # `lake env lean FILE`: under `lake env` a dependency's build directory holding the package's own namespace
188
+ # comes first on LEAN_PATH and would be loaded instead (the check below refuses that too).
189
+ AXIOMS_CMD=${AXIOMS_CMD:-"lake lean Verify/Axioms.lean"}
190
+ # prints the LEAN_PATH the audit runs under, for the shadowing check
191
+ LEAN_PATH_CMD=${LEAN_PATH_CMD:-"lake env printenv LEAN_PATH"}
192
+ CHECKER=${CHECKER:-"verify.sbatch (lake build; #print axioms)"}
193
+ # Run the tools inside the job container when the node needs one, e.g. RUN="apptainer exec lean.sif".
194
+ RUN=${RUN:-}
195
+ # The container image the tools run in, recorded in the log and on stdout (the receipt's `container` key).
196
+ # CONTAINER_IMAGE: the Apptainer or Singularity .sif file (default: the first word of RUN ending in .sif), or an
197
+ # OCI image name for podman or docker. CONTAINER_ENGINE: apptainer, singularity, podman or docker (default: the
198
+ # first word of RUN). Before the build the job takes the SIF file's sha256, or the OCI image's digest
199
+ # (`podman image inspect`, `docker image inspect`); the log names the image with a home directory shown as ~.
200
+ CONTAINER_IMAGE=${CONTAINER_IMAGE:-}
201
+ CONTAINER_ENGINE=${CONTAINER_ENGINE:-}
202
+ # How the tree committed at COMMIT reaches the work directory. archive (the default): `git archive`, so the
203
+ # job's tree has no .git. clone: a new repository there holding only COMMIT and its history (fetched over the
204
+ # file transport from the submitting checkout, never the network; its own object store, so nothing is shared
205
+ # with the checkout and no untracked or ignored file comes along), checked out at COMMIT; the job fails unless
206
+ # HEAD is COMMIT and `git status` is empty. Use clone for a VERIFY_CMD that reads `git rev-parse HEAD`.
207
+ SRC_MODE=${SRC_MODE:-archive}
208
+ # Optional: a tarball (any compression tar reads) holding .lake/packages, the dependencies' checkouts and
209
+ # builds, restored before the build so the job need not fetch and build Mathlib again. Only .lake/packages is
210
+ # taken from it (anything else in it is ignored); the job fails when the restore changed anything else in the
211
+ # tree, or when a dependency's build directory holds one of the package's root namespaces. The package itself
212
+ # is still compiled fresh: the checks below are unchanged. The log records the tarball's sha256, never its path.
213
+ # The tarball must hold what the audit imports, not only the build target's cone (`import Mathlib` needs every
214
+ # Mathlib module built); check it before submitting, on the login node (reads, builds and writes nothing):
215
+ # lean-pkg receipt slurm --preflight-deps --deps-tar T --commit SHA [--entries 'Verify/**/*.lean' ...]
216
+ DEPS_TAR=${DEPS_TAR:-}
217
+ # Optional artifact seal: ARTIFACTS_DIR, a directory relative to the job's package tree ($SRC; relative to $WORK
218
+ # with ARTIFACTS_BASE=work) that the build or the audit fills. After the audit every regular file under it is
219
+ # copied to ARTIFACTS_OUT (default $OUT_DIR/artifacts-<J>; must not exist yet) with a manifest artifacts.sha256
220
+ # there: one line per file, sorted by path, `<relative path> <size> <sha256>`. The manifest's sha256 goes on
221
+ # stdout beside the seal lines (artifacts-manifest-sha256), so `lean-pkg receipt slurm --artifacts DIR`
222
+ # rehashes a collected copy against the job's own manifest. A symlink or special file under the directory, a
223
+ # file name holding a newline, or a copy that does not rehash to the manifest fails the job.
224
+ ARTIFACTS_DIR=${ARTIFACTS_DIR:-}
225
+ ARTIFACTS_BASE=${ARTIFACTS_BASE:-src}
226
+
227
+ JOB=${SLURM_JOB_ID:?run this under sbatch}
228
+ PKG_DIR=${PKG_DIR:-${SLURM_SUBMIT_DIR:-$PWD}}
229
+ COMMIT=${COMMIT:-$(git -C "$PKG_DIR" rev-parse HEAD)}
230
+ OUT_DIR=${OUT_DIR:-${SLURM_SUBMIT_DIR:-$PWD}}
231
+ LOG="$OUT_DIR/verify-$JOB.log"
232
+ ARTIFACTS_OUT=${ARTIFACTS_OUT:-$OUT_DIR/artifacts-$JOB}
233
+ ARTIFACTS_MANIFEST=artifacts.sha256
234
+
235
+ # Node-local work directory. The receipt redacts /tmp/<user>-job<J> and /scratch/<user>/ by itself; a
236
+ # path elsewhere that appears in the log needs `--redact REGEX` at receipt time.
237
+ WORK=${SLURM_TMPDIR:-/tmp/${USER:-user}-job-$JOB}
238
+ STAGE="$WORK/src"
239
+ DEPS_STAGE="$WORK/deps"
240
+ # Lake's local artifact cache restores a module built earlier (`Reused`) without its sorry warning, so the job
241
+ # gets an empty cache of its own and the cache switched off. LAKE_CACHE_DIR="" would NOT disable it (Lake then
242
+ # uses .lake/cache), and a lakefile's `enableArtifactCache = true` wins over LAKE_ARTIFACT_CACHE=false: the
243
+ # empty directory leaves it nothing to restore. (--no-cache / LAKE_NO_CACHE only govern downloads.)
244
+ export LAKE_CACHE_DIR="$WORK/lake-cache"
245
+ export LAKE_ARTIFACT_CACHE=false
246
+ rm -rf "$STAGE" "$DEPS_STAGE" "$LAKE_CACHE_DIR"
247
+ mkdir -p "$STAGE" "$LAKE_CACHE_DIR"
248
+ trap 'rm -rf "$STAGE" "$DEPS_STAGE" "$LAKE_CACHE_DIR" "$WORK/claim-axioms" "$WORK/hyp-probe"' EXIT
249
+ # Stage the Lean runtime (the elan toolchain) and the Mathlib cache node-local before the build, e.g.
250
+ # copy the toolchain under "$WORK/elan" and export ELAN_HOME="$WORK/elan" PATH="$WORK/elan/bin:$PATH";
251
+ # a shared filesystem under many parallel readers is slow and can fail the build.
252
+ export MATHLIB_CACHE_DIR=${MATHLIB_CACHE_DIR:-$WORK/mathlib-cache}
253
+ # Mathlib-heavy packages can exhaust the node's file table (fs.file-max) at higher thread counts;
254
+ # /proc/sys/fs/file-nr goes into the log before and after the build.
255
+ export LEAN_NUM_THREADS=${LEAN_NUM_THREADS:-3}
256
+
257
+ # Required-executable probe, before the work: every host tool this script runs, and the first word of each
258
+ # command it runs under $RUN (with `lean` beside a `lake` one), must resolve with `type -P` (not `command -v`:
259
+ # a shell keyword or function is not an executable). A missing one fails the job here, with nothing built.
260
+ # Add more with EXTRA_TOOLS (host) or RUN_TOOLS (under $RUN), e.g. RUN_TOOLS=python3.
261
+ HOST_TOOLS="git tar sha256sum find sort xargs awk sed grep cut tr cp mkdir rm ls cat ${EXTRA_TOOLS:-}"
262
+ run_tools="${RUN_TOOLS:-}"
263
+ for c in "$VERIFY_CMD" "$AXIOMS_CMD" "$LEAN_PATH_CMD"; do
264
+ for w in $c; do
265
+ case "$w" in *=*) continue ;; esac
266
+ run_tools="$run_tools $w"
267
+ if [ "$w" = lake ]; then run_tools="$run_tools lean"; fi
268
+ break
269
+ done
270
+ done
271
+ missing=""
272
+ for t in $HOST_TOOLS; do
273
+ type -P "$t" >/dev/null || missing="$missing $t"
274
+ done
275
+ for t in $($RUN bash -c 'for c in "$@"; do type -P "$c" >/dev/null || echo "$c"; done' _ $run_tools); do
276
+ missing="$missing $t${RUN:+ (under RUN)}"
277
+ done
278
+ if [ -n "$missing" ]; then
279
+ echo "error: runtime preflight: executable(s) not found:$missing" >&2
280
+ exit 1
281
+ fi
282
+
283
+ # The container image identity, before anything runs in it (CONTAINER_IMAGE above).
284
+ if [ -z "$CONTAINER_IMAGE" ]; then
285
+ for w in $RUN; do
286
+ case "$w" in *.sif) CONTAINER_IMAGE=$w; break ;; esac
287
+ done
288
+ fi
289
+ container_key=""
290
+ if [ -n "$CONTAINER_IMAGE" ]; then
291
+ if [ -z "$CONTAINER_ENGINE" ]; then
292
+ for w in $RUN; do CONTAINER_ENGINE=${w##*/}; break; done
293
+ fi
294
+ case "$CONTAINER_ENGINE" in
295
+ apptainer|singularity)
296
+ if [ ! -f "$CONTAINER_IMAGE" ]; then
297
+ echo "error: CONTAINER_IMAGE: no SIF file $CONTAINER_IMAGE" >&2
298
+ exit 1
299
+ fi
300
+ container_key=container-image-sha256
301
+ container_digest=$(sha256sum "$CONTAINER_IMAGE" | cut -d' ' -f1)
302
+ ;;
303
+ podman)
304
+ container_key=container-oci-digest
305
+ container_digest=$(podman image inspect --format '{{.Digest}}' "$CONTAINER_IMAGE")
306
+ ;;
307
+ docker)
308
+ container_key=container-oci-digest
309
+ container_digest=$(docker image inspect --format '{{index .RepoDigests 0}}' "$CONTAINER_IMAGE")
310
+ container_digest=${container_digest##*@}
311
+ ;;
312
+ *)
313
+ echo "error: CONTAINER_ENGINE is apptainer, singularity, podman or docker, not '$CONTAINER_ENGINE'" >&2
314
+ exit 1
315
+ ;;
316
+ esac
317
+ case "$container_key $container_digest" in
318
+ "container-image-sha256 "[0-9a-f]*|"container-oci-digest sha256:"[0-9a-f]*) ;;
319
+ *)
320
+ echo "error: no digest for the container image $CONTAINER_IMAGE" >&2
321
+ exit 1
322
+ ;;
323
+ esac
324
+ container_ref=$CONTAINER_IMAGE
325
+ case "$container_ref" in
326
+ "${HOME:-/nonexistent}"/*) container_ref="~/${container_ref#"$HOME"/}" ;;
327
+ esac
328
+ echo "$container_key $container_digest"
329
+ fi
330
+
331
+ # The committed tree at COMMIT, never the working tree.
332
+ case "$SRC_MODE" in
333
+ archive)
334
+ git -C "$PKG_DIR" archive --format=tar "$COMMIT:./" | tar -xf - -C "$STAGE"
335
+ SRC="$STAGE"
336
+ ;;
337
+ clone)
338
+ COMMIT=$(git -C "$PKG_DIR" rev-parse --verify --quiet "$COMMIT^{commit}")
339
+ prefix=$(git -C "$PKG_DIR" rev-parse --show-prefix)
340
+ # No template hooks, no hooks at checkout, only the file transport.
341
+ git init -q --template= "$STAGE"
342
+ GIT_ALLOW_PROTOCOL=file git -C "$STAGE" -c protocol.version=2 fetch -q --no-tags --no-recurse-submodules \
343
+ "$(git -C "$PKG_DIR" rev-parse --show-toplevel)" "$COMMIT"
344
+ git -C "$STAGE" -c core.hooksPath=/dev/null -c advice.detachedHead=false checkout -q --detach FETCH_HEAD
345
+ SRC="$STAGE${prefix:+/${prefix%/}}"
346
+ ;;
347
+ *)
348
+ echo "error: SRC_MODE is archive or clone, not '$SRC_MODE'" >&2
349
+ exit 1
350
+ ;;
351
+ esac
352
+ cd "$SRC"
353
+ echo "pre-manifest-sha256 $(sha256sum lake-manifest.json | cut -d' ' -f1)"
354
+ deps_restore=none
355
+ if [ -n "$DEPS_TAR" ]; then
356
+ deps_restore="tar $(sha256sum "$DEPS_TAR" | cut -d' ' -f1)"
357
+ fi
358
+
359
+ {
360
+ echo "commit: $COMMIT"
361
+ echo "job-id: $JOB"
362
+ echo "lean-toolchain: $(cat lean-toolchain)"
363
+ echo "checker: $CHECKER"
364
+ echo "lean-num-threads: $LEAN_NUM_THREADS"
365
+ echo "runtime-preflight: ok (LC_ALL=$LC_ALL LANG=$LANG PYTHONUTF8=$PYTHONUTF8; tools:$(echo $run_tools | tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//;s/^/ /'))"
366
+ echo "fs-file-nr-before: $(cat /proc/sys/fs/file-nr 2>/dev/null || echo unavailable)"
367
+ echo "lake-cache-dir: fresh (empty, job-local)"
368
+ echo "lake-artifact-cache: $LAKE_ARTIFACT_CACHE"
369
+ echo "src-mode: $SRC_MODE"
370
+ if [ "$SRC_MODE" = clone ]; then
371
+ echo "src-head: $(git rev-parse HEAD)"
372
+ fi
373
+ echo "deps-restore: $deps_restore"
374
+ if [ -n "$container_key" ]; then
375
+ echo "container-engine: $CONTAINER_ENGINE"
376
+ echo "container-image: $container_ref"
377
+ echo "$container_key: $container_digest"
378
+ fi
379
+ } >"$LOG"
380
+ if [ "$SRC_MODE" = clone ]; then
381
+ if [ "$(git rev-parse HEAD)" != "$COMMIT" ]; then
382
+ echo "error: the clone's HEAD is not COMMIT $COMMIT" >>"$LOG"
383
+ exit 1
384
+ fi
385
+ if [ -n "$(git -C "$STAGE" status --porcelain --untracked-files=all --ignored)" ]; then
386
+ echo "error: the clone at COMMIT is not clean (git status --porcelain is not empty)" >>"$LOG"
387
+ exit 1
388
+ fi
389
+ fi
390
+ """ + lh.SHADOW_CHECK_SH + ca.job_sh() + hyp.job_sh() + r"""# The dependency restore may change .lake/packages and nothing else: a listing and the content hashes of the
391
+ # rest of the tree (.lake itself aside, which it may create) are compared before and after. (No directory
392
+ # sizes or times: creating .lake changes those of the package directory on some filesystems.)
393
+ deps_snapshot() {
394
+ find . -path ./.lake/packages -prune -o -path ./.lake -o -printf '%y %m %p -> %l\n' | LC_ALL=C sort
395
+ find . -path ./.lake/packages -prune -o -type f -print0 | LC_ALL=C sort -z | xargs -0 -r sha256sum
396
+ }
397
+ if [ -n "$DEPS_TAR" ]; then
398
+ if [ -L .lake ] || [ -e .lake/packages ] || [ -L .lake/packages ]; then
399
+ echo "error: DEPS_TAR: the committed tree already holds .lake/packages (or .lake is a symlink)" >>"$LOG"
400
+ exit 1
401
+ fi
402
+ before=$(deps_snapshot | sha256sum)
403
+ mkdir -p "$DEPS_STAGE"
404
+ tar -xf "$DEPS_TAR" -C "$DEPS_STAGE" --no-same-owner
405
+ if [ -L "$DEPS_STAGE/.lake" ] || [ -L "$DEPS_STAGE/.lake/packages" ] || [ ! -d "$DEPS_STAGE/.lake/packages" ]; then
406
+ echo "error: DEPS_TAR holds no .lake/packages directory (a symlink is not one)" >>"$LOG"
407
+ exit 1
408
+ fi
409
+ mkdir -p .lake
410
+ mv "$DEPS_STAGE/.lake/packages" .lake/packages
411
+ rm -rf "$DEPS_STAGE"
412
+ if [ "$(deps_snapshot | sha256sum)" != "$before" ]; then
413
+ echo "error: DEPS_TAR: the restore changed the tree outside .lake/packages" >>"$LOG"
414
+ exit 1
415
+ fi
416
+ # A dependency's build directory holding a root namespace would shadow the package (see LEAN_PATH below).
417
+ shadowed=""
418
+ for r in $(lake_root_namespaces); do
419
+ hit=$(find .lake/packages \( -path "*/build/lib/lean/$r" -o -path "*/build/lib/lean/$r.olean" \
420
+ -o -path "*/build/lib/lean/$r.ilean" \) -print -quit)
421
+ if [ -n "$hit" ]; then
422
+ echo "deps-restore-shadow: $hit" >>"$LOG"
423
+ shadowed="$shadowed $r"
424
+ fi
425
+ done
426
+ if [ -n "$shadowed" ]; then
427
+ echo "error: DEPS_TAR: a dependency's build directory holds the package's root namespace(s):$shadowed" >>"$LOG"
428
+ exit 1
429
+ fi
430
+ echo "deps-restore-check: ok (only .lake/packages changed; no root namespace in it)" >>"$LOG"
431
+ fi
432
+ if [ -e .lake/build ] || [ -n "$(ls -A "$LAKE_CACHE_DIR")" ]; then
433
+ echo "error: not a fresh build: the committed tree holds .lake/build, or the Lake cache is not empty" >>"$LOG"
434
+ exit 1
435
+ fi
436
+ echo "lean-pkg-build: begin" >>"$LOG"
437
+ $RUN bash -c "$VERIFY_CMD" >>"$LOG" 2>&1
438
+ echo "lean-pkg-build: end" >>"$LOG"
439
+ # A root-package module Lake restored instead of compiling fails the job: its sorry warning need not be in the
440
+ # log. (Lake prints such a job only when it has output, or with -v; the empty cache is the real defence.) A
441
+ # cache line after the module's own Built is Lake re-printing its stored warnings, not a restore.
442
+ restored=""
443
+ for m in $(sed -n '/^lean-pkg-build: begin$/,/^lean-pkg-build: end$/p' "$LOG" \
444
+ | grep -oE '\[[0-9]+/[0-9]+\]( \(Optional\))? (Built|Reused|Replayed|Unpacked) [^ ]+' \
445
+ | awk '{m = $NF; sub(/:.*$/, "", m); if ($(NF - 1) == "Built") b[m] = 1; else if (!(m in b)) print m}' \
446
+ | sort -u || true); do
447
+ if [ -n "$(find . -path ./.lake -prune -o -path "*/${m//.//}.lean" -print -quit 2>/dev/null)" ] \
448
+ || lake_root_namespaces | grep -qxF "${m%%.*}"; then
449
+ restored="$restored $m"
450
+ fi
451
+ done
452
+ if [ -n "$restored" ]; then
453
+ echo "error: Lake restored root-package module(s) instead of compiling them:$restored" >>"$LOG"
454
+ exit 1
455
+ fi
456
+ # LEAN_PATH: Lake lists the package's own lib directory last and Lean loads <R>/ from the first entry holding
457
+ # it, so a dependency's build directory holding the package's namespace is refused before the audit. The
458
+ # check runs here, outside $RUN: with a container, bind the work directory at the same path.
459
+ lean_path=$($RUN bash -c "$LEAN_PATH_CMD")
460
+ if ! lake_shadow_check "$lean_path" >>"$LOG"; then
461
+ echo "error: a LEAN_PATH entry shadows the package's own modules (lean-path-shadow lines above)" >>"$LOG"
462
+ exit 1
463
+ fi
464
+ $RUN bash -c "$AXIOMS_CMD" >>"$LOG" 2>&1
465
+ # Every claim's axioms, read from the built environment (claim_axioms_run above; not only the printed ones).
466
+ claim_axioms_run "$LOG" "$WORK/claim-axioms" "$lean_path"
467
+ # The hyp-probe/1 section (proposal 0003): every claim's Prop hypotheses, and with conditional claims the
468
+ # Challenge facts. The Challenge is built into the side log $WORK/hyp-challenge-build.log, never into $LOG.
469
+ hypotheses_run "$LOG" "$WORK/hyp-probe" "$lean_path" "$WORK/hyp-challenge-build.log"
470
+ echo "fs-file-nr-after: $(cat /proc/sys/fs/file-nr 2>/dev/null || echo unavailable)" >>"$LOG"
471
+
472
+ # The artifact seal (ARTIFACTS_DIR above). artifacts_list DIR: the manifest lines of the regular files under DIR,
473
+ # sorted by path (C locale), the manifest itself left out.
474
+ artifacts_list() {
475
+ (cd "$1" && find . -path "./$ARTIFACTS_MANIFEST" -prune -o -type f -print0 | LC_ALL=C sort -z \
476
+ | while IFS= read -r -d '' f; do
477
+ printf '%s %s %s\n' "${f#./}" "$(stat -c %s "$f")" "$(sha256sum <"$f" | cut -d' ' -f1)"
478
+ done)
479
+ }
480
+ artifacts_sha=""
481
+ if [ -n "$ARTIFACTS_DIR" ]; then
482
+ case "$ARTIFACTS_BASE" in
483
+ src) abase="$SRC" ;;
484
+ work) abase="$WORK" ;;
485
+ *) echo "error: ARTIFACTS_BASE is src or work, not '$ARTIFACTS_BASE'" >>"$LOG"; exit 1 ;;
486
+ esac
487
+ case "/$ARTIFACTS_DIR/" in
488
+ //*|*/../*) echo "error: ARTIFACTS_DIR must be a relative path without '..'" >>"$LOG"; exit 1 ;;
489
+ esac
490
+ adir="$abase/$ARTIFACTS_DIR"
491
+ if [ ! -d "$adir" ] || [ "$(realpath -e "$adir")" != "$(realpath -m -s "$(realpath -e "$abase")/$ARTIFACTS_DIR")" ]; then
492
+ echo "error: ARTIFACTS_DIR is not a directory under $ARTIFACTS_BASE (or a path component is a symlink)" >>"$LOG"
493
+ exit 1
494
+ fi
495
+ bad=$(find "$adir" ! -type f ! -type d -print -quit)
496
+ if [ -n "$bad" ]; then
497
+ echo "error: ARTIFACTS_DIR holds a symlink or special file: ${bad#"$adir"/}" >>"$LOG"
498
+ exit 1
499
+ fi
500
+ if [ -n "$(find "$adir" -name $'*[\n\r]*' -print -quit)" ]; then
501
+ echo "error: ARTIFACTS_DIR holds a file name with a newline" >>"$LOG"
502
+ exit 1
503
+ fi
504
+ if [ -e "$adir/$ARTIFACTS_MANIFEST" ]; then
505
+ echo "error: ARTIFACTS_DIR already holds $ARTIFACTS_MANIFEST, the manifest's own name" >>"$LOG"
506
+ exit 1
507
+ fi
508
+ if [ -e "$ARTIFACTS_OUT" ] || [ -L "$ARTIFACTS_OUT" ]; then
509
+ echo "error: ARTIFACTS_OUT already exists; the job never overwrites artifacts" >>"$LOG"
510
+ exit 1
511
+ fi
512
+ mkdir -p "$(dirname "$ARTIFACTS_OUT")"
513
+ mkdir "$ARTIFACTS_OUT"
514
+ artifacts_list "$adir" >"$ARTIFACTS_OUT/$ARTIFACTS_MANIFEST"
515
+ cp -R "$adir/." "$ARTIFACTS_OUT/"
516
+ # the copy is what is collected: it must rehash to the manifest taken from the job's own tree
517
+ if ! artifacts_list "$ARTIFACTS_OUT" | cmp -s - "$ARTIFACTS_OUT/$ARTIFACTS_MANIFEST"; then
518
+ echo "error: the copy in ARTIFACTS_OUT does not rehash to the manifest of ARTIFACTS_DIR" >>"$LOG"
519
+ exit 1
520
+ fi
521
+ artifacts_sha=$(sha256sum "$ARTIFACTS_OUT/$ARTIFACTS_MANIFEST" | cut -d' ' -f1)
522
+ echo "artifacts-manifest: $(wc -l <"$ARTIFACTS_OUT/$ARTIFACTS_MANIFEST") file(s) from $ARTIFACTS_BASE/$ARTIFACTS_DIR, sha256 $artifacts_sha" >>"$LOG"
523
+ fi
524
+
525
+ # The key lines, from Lean's own output in the log: sorry-count may not be lower than the
526
+ # `declaration uses `sorry`` warnings (either quote style), and axioms may not leave out a `#print axioms` result.
527
+ sorry=$(grep -c -E "declaration uses ['\`]sorry['\`]" "$LOG" || true)
528
+ # (newlines joined first: Lean wraps a long axiom list over several lines)
529
+ axioms=$(tr '\n' ' ' <"$LOG" | grep -o 'depends on axioms: \[[^]]*\]' | sed -e 's/^[^[]*\[//' -e 's/\]$//' \
530
+ | tr ',' '\n' | tr -d ' ' | grep -v '^$' | sort -u | paste -sd, - || true)
531
+ {
532
+ echo "sorry-count: $sorry"
533
+ if [ -n "$axioms" ]; then
534
+ echo "axioms: $axioms"
535
+ elif grep -q 'does not depend on any axioms' "$LOG"; then
536
+ echo "axioms: none"
537
+ fi
538
+ echo "generated-at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
539
+ } >>"$LOG"
540
+
541
+ # The seal: nothing may write to the log after this line.
542
+ if [ -n "$artifacts_sha" ]; then
543
+ echo "artifacts-manifest-sha256 $artifacts_sha"
544
+ fi
545
+ echo "post-manifest-sha256 $(sha256sum lake-manifest.json | cut -d' ' -f1)"
546
+ echo "verify-log-sha256 $(sha256sum "$LOG" | cut -d' ' -f1)"
547
+ """
548
+
549
+
550
+ # --------------------------------------------------------------------------
551
+ # job state
552
+
553
+ def sacct_text(job: str, sacct_file: str | None) -> tuple[str | None, str | None]:
554
+ """(sacct output, refusal): the saved file, else `sacct` run on this host."""
555
+ if sacct_file is not None:
556
+ p = pathlib.Path(sacct_file)
557
+ if not p.is_file():
558
+ raise core.UsageError(f"--sacct-file {sacct_file}: no such file")
559
+ return p.read_text(encoding="utf-8", errors="replace"), None
560
+ exe = shutil.which("sacct")
561
+ if exe is None:
562
+ return None, ("sacct is not on PATH; on a host without Slurm save the output of "
563
+ f"`sacct -j {job} --format={SACCT_FORMAT} -P -n` on the cluster and pass --sacct-file")
564
+ try:
565
+ p = subprocess.run([exe, "-j", job, f"--format={SACCT_FORMAT}", "-P", "-n"],
566
+ capture_output=True, text=True, timeout=SACCT_TIMEOUT)
567
+ except (OSError, subprocess.TimeoutExpired) as e:
568
+ return None, f"sacct could not run: {e}"
569
+ if p.returncode != 0:
570
+ return None, f"sacct exited {p.returncode}: {(p.stderr or p.stdout).strip() or 'no output'}"
571
+ return p.stdout, None
572
+
573
+
574
+ # The states `sacct` reports (Slurm job_state_reason names aside); a second column that is none of them
575
+ # means the file was saved with another --format, so positions cannot be trusted.
576
+ SACCT_STATES = frozenset({
577
+ "BOOT_FAIL", "CANCELLED", "COMPLETED", "COMPLETING", "CONFIGURING", "DEADLINE", "FAILED", "NODE_FAIL",
578
+ "OUT_OF_MEMORY", "PENDING", "PREEMPTED", "REQUEUED", "REQUEUE_FED", "REQUEUE_HOLD", "RESIZING", "REVOKED",
579
+ "RUNNING", "SIGNALING", "SPECIAL_EXIT", "STAGE_OUT", "STOPPED", "SUSPENDED", "TIMEOUT"})
580
+ _EXIT_RE = re.compile(r"\d+:\d+")
581
+ # columns check_job reads when a header line names them (read by name only: positional files have five)
582
+ SACCT_OPTIONAL = ("elapsed", "total_cpu", "start", "end", "user", "nodelist")
583
+
584
+
585
+ def check_job(job: str, text: str) -> tuple[dict | None, str | None]:
586
+ """({job_id, state, exit_code, elapsed, total_cpu}, refusal) from `JobID|State|ExitCode[|Elapsed|TotalCPU]`.
587
+ A header line (sacct without -n) naming JobID, State and ExitCode locates the columns by name, in any
588
+ order. Without one the positions are checked: a second column that is not a Slurm state or a third that
589
+ is not N:N is refused as an unexpected format, never read as an unclean finish."""
590
+ want = {"jobid": "job_id", "state": "state", "exitcode": "exit_code", "elapsed": "elapsed",
591
+ "totalcpu": "total_cpu", "start": "start", "end": "end", "user": "user", "nodelist": "nodelist"}
592
+ index = {"job_id": 0, "state": 1, "exit_code": 2, "elapsed": 3, "total_cpu": 4}
593
+ header = False
594
+ expected = (f"`{SACCT_FORMAT}` with -P -n, or any --format with a header line naming JobID, State and "
595
+ f"ExitCode (sacct -P without -n)")
596
+ for raw in text.splitlines():
597
+ cols = [c.strip() for c in raw.split("|")]
598
+ names = [c.replace(" ", "").lower() for c in cols]
599
+ if {"jobid", "state", "exitcode"} <= set(names):
600
+ index = {want[n]: i for i, n in enumerate(names) if n in want}
601
+ header = True
602
+ continue
603
+ if len(cols) < 3 or cols[index["job_id"]] != job:
604
+ continue
605
+ cols += [""] * (max(index.values()) + 1 - len(cols))
606
+ seen = {k: (cols[i] or None) if k in SACCT_OPTIONAL else cols[i]
607
+ for k, i in index.items()}
608
+ for k in ("elapsed", "total_cpu"): # the extra columns appear only when a header names them
609
+ seen.setdefault(k, None)
610
+ state = seen["state"].split()[0] if seen["state"] else ""
611
+ if not header and (state not in SACCT_STATES or not _EXIT_RE.fullmatch(seen["exit_code"])):
612
+ return None, (f"sacct: unexpected sacct format: the job {job} line reads State={seen['state']!r}, "
613
+ f"ExitCode={seen['exit_code']!r}, which are not a Slurm state and an N:N exit code; "
614
+ f"expected {expected}")
615
+ bad = []
616
+ if state != "COMPLETED":
617
+ bad.append(f"State={seen['state'] or '(empty)'}")
618
+ if seen["exit_code"] != "0:0":
619
+ bad.append(f"ExitCode={seen['exit_code'] or '(empty)'}")
620
+ if bad:
621
+ return seen, (f"sacct: job {job} is not a clean finish ({', '.join(bad)}); "
622
+ f"a receipt needs State=COMPLETED and ExitCode=0:0")
623
+ return seen, None
624
+ return None, (f"sacct: no main job line for job {job} (expected `{job}|COMPLETED|0:0|...` among the "
625
+ f"`{SACCT_FORMAT}` lines, or a header line naming JobID, State and ExitCode)")
626
+
627
+
628
+ # --------------------------------------------------------------------------
629
+ # sacct seal of a comparator receipt's Slurm claim
630
+ #
631
+ # A comparator receipt's job_id comes from SLURM_JOB_ID, which any shell can set. `comparator-receipt
632
+ # --seal-sacct R` corroborates it after the job finished, the way `receipt slurm` corroborates a lower-tier
633
+ # job: the accounting record must show that job COMPLETED with exit 0:0, between a Start and an End that
634
+ # contain the receipt's generated_at, and (when sacct runs live) under the sealing account and on the
635
+ # receipt's node. The record is written, normalized to the columns below and UTC times, to
636
+ # .lean-receipts/<c12>-comparator-sacct.txt and bound by its SHA-256 in the receipt's `slurm_sacct` block.
637
+ # Only a sealed receipt backs a coverage `compute` job (coverage.slurm_job_of); user and node names are
638
+ # checked, never written.
639
+ # `receipt slurm --seal-sacct` seals a lower-tier receipt the same way while writing it: the same checks, the
640
+ # same record format and the same `slurm_sacct` block (file .lean-receipts/<c12>-slurm-<J>-sacct.txt), with
641
+ # job J taken from job_id `slurm-J` and the run time from the verify log's `generated-at:` line; gate
642
+ # (gate_mod.validate_receipt) then checks a present block with sacct_seal_problem against the record committed at
643
+ # HEAD (committed_sacct_seal_problem).
644
+
645
+ SACCT_SEAL_SCHEMA = "slurm-sacct-seal/1"
646
+ SACCT_SEAL_FORMAT = "JobID,State,ExitCode,Start,End,Elapsed"
647
+ SACCT_SEAL_QUERY = SACCT_SEAL_FORMAT + ",User,NodeList"
648
+ # sacct prints Start/End in the cluster's local time without a zone; this format adds the offset
649
+ SACCT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
650
+ SACCT_SEAL_SUFFIX = "-comparator-sacct.txt"
651
+ SLURM_SACCT_SUFFIX = "sacct.txt" # receipt slurm: <c12>-slurm-<J>-sacct.txt beside the receipt
652
+ # receipt slurm --seal-sacct runs sacct itself: the seal's columns plus TotalCPU for the README entry
653
+ SLURM_SEAL_QUERY = "JobID,State,ExitCode,Start,End,Elapsed,TotalCPU,User,NodeList"
654
+ SACCT_SEAL_KEYS = ("schema", "job", "file", "sha256", "state", "exit_code", "start", "end", "elapsed")
655
+ _OFFSET_RE = re.compile(r"([+-])(\d{2})(\d{2})$")
656
+
657
+
658
+ def sacct_time(value) -> dt.datetime | None:
659
+ """A Start/End value with its zone: epoch seconds, or ISO-8601 with Z or an offset (+HHMM or +HH:MM).
660
+ None for a naive time (sacct's default), Unknown, None or anything else: never guessed."""
661
+ s = str(value or "").strip()
662
+ if re.fullmatch(r"\d{9,11}", s):
663
+ return dt.datetime.fromtimestamp(int(s), dt.timezone.utc)
664
+ s = _OFFSET_RE.sub(r"\1\2:\3", s[:-1] + "+00:00" if s.endswith("Z") else s)
665
+ try:
666
+ v = dt.datetime.fromisoformat(s)
667
+ except ValueError:
668
+ return None
669
+ return v if v.tzinfo is not None else None
670
+
671
+
672
+ def sacct_seal_text(job: str, seen: dict, start, end) -> str:
673
+ """The normalized record written beside the receipt: a header and the main job line, UTC times."""
674
+ def iso(t):
675
+ return t.astimezone(dt.timezone.utc).isoformat(timespec="seconds")
676
+ return (SACCT_SEAL_FORMAT.replace(",", "|") + "\n"
677
+ + "|".join([job, "COMPLETED", "0:0", iso(start), iso(end), str(seen.get("elapsed") or "")]) + "\n")
678
+
679
+
680
+ def comparator_slurm_job(rec: dict) -> str | None:
681
+ """The bare Slurm job number a comparator receipt claims: job_id J with host_policy `Slurm job J ...`
682
+ (what the runner writes when SLURM_JOB_ID is set), else None."""
683
+ job = rec.get("job_id") if isinstance(rec, dict) else None
684
+ if isinstance(job, str) and re.fullmatch(r"\d+(?:_\d+)?", job) \
685
+ and str(rec.get("host_policy") or "").startswith(f"Slurm job {job} "):
686
+ return job
687
+ return None
688
+
689
+
690
+ def lower_slurm_job(rec: dict) -> str | None:
691
+ """The bare Slurm job number a lower-tier receipt names: job_id `slurm-J` (what `receipt slurm` writes),
692
+ J a job or array-task number; never a comparator receipt's."""
693
+ if not isinstance(rec, dict) or rec.get("schema") in core.COMPARATOR_SCHEMAS:
694
+ return None
695
+ m = re.fullmatch(r"slurm-(\d+(?:_\d+)?)", str(rec.get("job_id") or ""))
696
+ return m.group(1) if m else None
697
+
698
+
699
+ def sacct_seal_job(rec: dict) -> tuple[str | None, str]:
700
+ """(job, kind) for a `slurm_sacct` seal: a comparator receipt's Slurm claim (comparator_slurm_job), else a
701
+ lower-tier receipt's job_id `slurm-J` (lower_slurm_job); kind is "comparator" or "lower-tier"."""
702
+ job = comparator_slurm_job(rec)
703
+ if job is not None:
704
+ return job, "comparator"
705
+ job = lower_slurm_job(rec)
706
+ return job, ("lower-tier" if job is not None else "comparator")
707
+
708
+
709
+ def sacct_window_problem(job: str, rec: dict, start, end, kind: str = "comparator") -> str | None:
710
+ """The run must lie inside the job: Start <= generated_at <= End, both times with a zone."""
711
+ query = SACCT_SEAL_QUERY if kind == "comparator" else SLURM_SEAL_QUERY
712
+ if start is None or end is None:
713
+ return (f"sacct: job {job} has no zoned Start/End (got Start={start!r}, End={end!r}); save it with "
714
+ f"`SLURM_TIME_FORMAT={SACCT_TIME_FORMAT} sacct -j {job} --format={query} -P`")
715
+ what = "comparator run" if kind == "comparator" else "verify run"
716
+ try:
717
+ at = core.parse_ts(rec.get("generated_at"))
718
+ except (ValueError, TypeError):
719
+ return f"{kind} receipt generated_at {rec.get('generated_at')!r} is not a timestamp"
720
+ if not start <= at <= end:
721
+ return (f"sacct: job {job} ran {start.isoformat()} .. {end.isoformat()}, which does not contain the "
722
+ f"{what} (generated_at {at.isoformat()}); this record is of another run")
723
+ return None
724
+
725
+
726
+ def sacct_seal_problem(rec: dict, sealed: bytes | None) -> str | None:
727
+ """Why the receipt's `slurm_sacct` block does not corroborate its Slurm claim, or None when it does:
728
+ the block is well formed, `sealed` (the bytes of block.file) hashes to block.sha256, parses (check_job)
729
+ as job J COMPLETED 0:0, J is the receipt's job, and Start..End contain generated_at. The receipt is a
730
+ comparator receipt claiming Slurm job J, or a lower-tier receipt with job_id `slurm-J` (sacct_seal_job)."""
731
+ job, kind = sacct_seal_job(rec)
732
+ if job is None:
733
+ return ("the receipt does not claim a Slurm job (job_id J with host_policy `Slurm job J ...`, or a "
734
+ "lower-tier job_id slurm-J)")
735
+ block = rec.get("slurm_sacct")
736
+ if not isinstance(block, dict):
737
+ if kind == "lower-tier":
738
+ return (f"no sacct seal: slurm_sacct is not a block; rewrite the receipt with `lean-pkg receipt "
739
+ f"slurm --seal-sacct` where sacct sees job {job} (or with --sacct-file)")
740
+ return (f"no sacct seal: job_id {job} comes from SLURM_JOB_ID, which any shell can set; after the job "
741
+ f"finished run `comparator-receipt --seal-sacct <receipt>` where sacct sees job {job}")
742
+ missing = [k for k in SACCT_SEAL_KEYS if k not in block]
743
+ if missing or block.get("schema") != SACCT_SEAL_SCHEMA:
744
+ return f"slurm_sacct is not a {SACCT_SEAL_SCHEMA} block (missing {', '.join(missing) or 'schema'})"
745
+ if str(block["job"]) != job:
746
+ return f"slurm_sacct seals job {block['job']!r}, the receipt claims job {job}"
747
+ rel = str(block["file"])
748
+ if not rel.startswith(".lean-receipts/") or ".." in rel.split("/") or "\\" in rel:
749
+ return f"slurm_sacct.file must be under .lean-receipts/, got {rel!r}"
750
+ if sealed is None:
751
+ return f"slurm_sacct.file {rel} is not committed at HEAD"
752
+ if hashlib.sha256(sealed).hexdigest() != str(block["sha256"]).lower():
753
+ return f"slurm_sacct.file {rel} does not hash to slurm_sacct.sha256"
754
+ seen, why = check_job(job, sealed.decode("utf-8", "replace"))
755
+ if why:
756
+ return why
757
+ start, end = sacct_time(seen.get("start")), sacct_time(seen.get("end"))
758
+ why = sacct_window_problem(job, rec, start, end, kind)
759
+ if why:
760
+ return why
761
+ if (block["state"], block["exit_code"]) != ("COMPLETED", "0:0") or \
762
+ sacct_time(block["start"]) != start or sacct_time(block["end"]) != end:
763
+ return f"slurm_sacct's fields differ from the sealed record {rel}"
764
+ return None
765
+
766
+
767
+ def committed_sacct_seal_problem(repo: pathlib.Path, rec: dict, rev: str = "HEAD") -> str | None:
768
+ """sacct_seal_problem against the record committed at `rev` (default HEAD) of the package checkout `repo`:
769
+ the bytes of slurm_sacct.file read from git, never from the working tree (an uncommitted record is None)."""
770
+ block = rec.get("slurm_sacct") if isinstance(rec, dict) else None
771
+ rel = block.get("file") if isinstance(block, dict) and isinstance(block.get("file"), str) else None
772
+ sealed = core.git_show_bytes(repo, f"./{rel}", rev) if rel and rel.startswith(".lean-receipts/") else None
773
+ return sacct_seal_problem(rec, sealed)
774
+
775
+
776
+ def sacct_seal_query(job: str, query: str) -> tuple[str | None, str | None]:
777
+ """(output, refusal) of live `sacct -j J --format=QUERY -P` with zoned times (SLURM_TIME_FORMAT); the
778
+ header line stays, so check_job reads the columns by name."""
779
+ exe = shutil.which("sacct")
780
+ if exe is None:
781
+ return None, (f"sacct is not on PATH; on the cluster save `SLURM_TIME_FORMAT={SACCT_TIME_FORMAT} "
782
+ f"sacct -j {job} --format={query} -P` and pass --sacct-file")
783
+ try:
784
+ p = subprocess.run([exe, "-j", job, f"--format={query}", "-P"], capture_output=True,
785
+ text=True, timeout=SACCT_TIMEOUT,
786
+ env={**os.environ, "SLURM_TIME_FORMAT": SACCT_TIME_FORMAT})
787
+ except (OSError, subprocess.TimeoutExpired) as e:
788
+ return None, f"sacct could not run: {e}"
789
+ if p.returncode != 0:
790
+ return None, f"sacct exited {p.returncode}: {(p.stderr or p.stdout).strip() or 'no output'}"
791
+ return p.stdout, None
792
+
793
+
794
+ def sacct_seal_record(job: str, rec: dict, seen: dict, *, live: bool, user: str | None, rel: str,
795
+ kind: str = "comparator") -> tuple[dict, bytes]:
796
+ """The checks of a seal after check_job accepted `seen` (job J COMPLETED 0:0): Start..End contain the
797
+ receipt's generated_at, the account (--user, else this one with live sacct) and the receipt's host where
798
+ known. Returns (the `slurm_sacct` block naming `rel`, the normalized record's bytes); raises core.Fail
799
+ (`...; not sealed`) otherwise. Shared by `comparator-receipt --seal-sacct` and `receipt slurm --seal-sacct`."""
800
+ start, end = sacct_time(seen.get("start")), sacct_time(seen.get("end"))
801
+ why = sacct_window_problem(job, rec, start, end, kind)
802
+ if why:
803
+ raise core.Fail(why + "; not sealed")
804
+ checks = {}
805
+ account = user or (getpass.getuser() if live else None)
806
+ if seen.get("user") and account:
807
+ if seen["user"] != account:
808
+ raise core.Fail(f"sacct: job {job} ran under another account than {'--user' if user else 'this one'};"
809
+ f" not sealed")
810
+ checks["user"] = "matched"
811
+ else:
812
+ checks["user"] = "not checked"
813
+ checks["node"] = sacct_node_check(job, str(rec.get("host") or ""), str(seen.get("nodelist") or ""),
814
+ labelled=bool(rec.get("host_label")))
815
+ body = sacct_seal_text(job, seen, start, end).encode()
816
+ block = {"schema": SACCT_SEAL_SCHEMA, "job": job, "file": rel, "sha256": hashlib.sha256(body).hexdigest(),
817
+ "state": "COMPLETED", "exit_code": "0:0",
818
+ "start": start.astimezone(dt.timezone.utc).isoformat(timespec="seconds"),
819
+ "end": end.astimezone(dt.timezone.utc).isoformat(timespec="seconds"),
820
+ "elapsed": seen.get("elapsed") or "", "checks": checks,
821
+ "source": "sacct" if live else "sacct-file"}
822
+ return block, body
823
+
824
+
825
+ HASHED_HOST_RE = re.compile(r"h-[0-9a-f]{12}")
826
+ _NODE_RE = re.compile(r"[A-Za-z0-9._-]+")
827
+
828
+
829
+ def sacct_node_check(job: str, host: str, nodes: str, labelled: bool = False) -> str:
830
+ """The node check of the seal: "matched", "not checked (...)", or a refusal. The runner names its host
831
+ by a label (#208): `h-` + 12 hex of the SHA-256 of the lower-cased host name, compared with the label of
832
+ the NodeList entry and of its first DNS label; an operator's --host-label cannot be compared; a bare host
833
+ name (a receipt by lean-pkg 0.10.0 or earlier) is compared by its first DNS label. A node range
834
+ (`node[01-02]`) is not expanded."""
835
+ if not host or not nodes:
836
+ return "not checked"
837
+ if not _NODE_RE.fullmatch(nodes):
838
+ return "not checked (node range)"
839
+ if HASHED_HOST_RE.fullmatch(host):
840
+ from .receipt_systemd import host_label as hashed_host_label
841
+ ok = host in {hashed_host_label(nodes), hashed_host_label(nodes.split(".")[0])}
842
+ elif labelled:
843
+ return "not checked (host label)"
844
+ else:
845
+ ok = nodes.split(".")[0].lower() == host.split(".")[0].lower()
846
+ if not ok:
847
+ raise core.Fail(f"sacct: job {job} ran on another node than the receipt's host; not sealed")
848
+ return "matched"
849
+
850
+
851
+ def seal_comparator_sacct(receipt_path: pathlib.Path, sacct_file: str | None = None,
852
+ user: str | None = None) -> dict:
853
+ """`comparator-receipt --seal-sacct R`: corroborate R's Slurm claim with the job's accounting record and
854
+ seal it (see the section comment). Refuses (core.Fail, nothing written) unless the record shows the
855
+ receipt's job COMPLETED 0:0 in a window containing the run, under this account (live sacct) and on the
856
+ receipt's host when the receipt names it. Writes the normalized record beside R and the `slurm_sacct`
857
+ block into R. A receipt sealed with the same record already is left as it is."""
858
+ try:
859
+ rec = json.loads(receipt_path.read_text())
860
+ except (OSError, ValueError) as e:
861
+ raise core.Fail(f"--seal-sacct {receipt_path}: not a readable JSON receipt ({e})") from None
862
+ if not isinstance(rec, dict) or rec.get("schema") not in core.COMPARATOR_SCHEMAS:
863
+ raise core.Fail(f"--seal-sacct {receipt_path}: not a comparator receipt")
864
+ if rec.get("partial") or rec.get("test_only"):
865
+ raise core.Fail(f"--seal-sacct {receipt_path}: a partial or test-only receipt is not evidence; not sealed")
866
+ job = comparator_slurm_job(rec)
867
+ if job is None:
868
+ raise core.Fail(f"--seal-sacct {receipt_path}: the receipt does not claim a Slurm job (job_id "
869
+ f"{rec.get('job_id')!r}, host_policy {rec.get('host_policy')!r}); nothing to seal")
870
+ commit = str(rec.get("commit") or "")
871
+ if not re.fullmatch(r"[0-9a-f]{40}", commit):
872
+ raise core.Fail(f"--seal-sacct {receipt_path}: receipt commit is not a 40-hex sha")
873
+ if sacct_file is None:
874
+ text, why = sacct_seal_query(job, SACCT_SEAL_QUERY)
875
+ if why:
876
+ raise core.Fail(why)
877
+ live = True
878
+ else:
879
+ text, _ = sacct_text(job, sacct_file)
880
+ live = False
881
+ seen, why = check_job(job, text)
882
+ if why:
883
+ raise core.Fail(why + "; not sealed")
884
+ rel = f".lean-receipts/{commit[:12]}{SACCT_SEAL_SUFFIX}"
885
+ out = receipt_path.parent / pathlib.PurePosixPath(rel).name
886
+ block, body = sacct_seal_record(job, rec, seen, live=live, user=user, rel=rel)
887
+ old = rec.get("slurm_sacct")
888
+ if isinstance(old, dict) and {k: old.get(k) for k in SACCT_SEAL_KEYS} == {k: block[k] for k in SACCT_SEAL_KEYS} \
889
+ and out.is_file() and out.read_bytes() == body:
890
+ return {"ok": True, "receipt": str(receipt_path), "sacct": str(out), "sealed": False, "slurm_sacct": old}
891
+ if isinstance(old, dict):
892
+ raise core.Fail(f"--seal-sacct {receipt_path}: already sealed with another record ({old.get('file')}); "
893
+ f"not resealed")
894
+ if out.is_symlink() or (out.exists() and out.read_bytes() != body):
895
+ raise core.Fail(f"{out} exists with other bytes; not overwritten")
896
+ rec["slurm_sacct"] = block
897
+ out.write_bytes(body)
898
+ tmp = receipt_path.with_name(receipt_path.name + ".tmp")
899
+ tmp.write_text(json.dumps(rec, indent=2, sort_keys=True) + "\n")
900
+ os.replace(tmp, receipt_path)
901
+ return {"ok": True, "receipt": str(receipt_path), "sacct": str(out), "sealed": True, "slurm_sacct": block}
902
+
903
+ # --------------------------------------------------------------------------
904
+ # seals
905
+
906
+ def check_self_hash(raw: bytes) -> str | None:
907
+ """Fallback seal: exactly one `verify-log-sha256: <hex>` line in the log, equal to sha256(raw minus that line)."""
908
+ lines = raw.split(b"\n")
909
+ keep, found = [], []
910
+ for i, line in enumerate(lines):
911
+ m = _SHA_LINE.match(line)
912
+ if m:
913
+ found.append(m.group(1).decode().lower())
914
+ continue
915
+ keep.append(line + (b"\n" if i < len(lines) - 1 else b""))
916
+ if not found:
917
+ return (f"verify log: no `{SHA_KEY}: <64 hex>` line (pass the job's stdout with --stdout when the "
918
+ f"seal is printed there)")
919
+ if len(found) > 1:
920
+ return f"verify log: {len(found)} `{SHA_KEY}` lines; exactly one is allowed"
921
+ actual = hashlib.sha256(b"".join(keep)).hexdigest()
922
+ if actual != found[0]:
923
+ return (f"verify log: {SHA_KEY} line says {found[0][:12]}…, but the log without that line hashes "
924
+ f"to {actual[:12]}…; the log was changed after it was sealed")
925
+ return None
926
+
927
+
928
+ def stdout_values(text: str, key: str) -> list[str]:
929
+ """The values of the job-stdout lines `KEY VALUE` / `KEY: VALUE` (key first on the line)."""
930
+ rx = re.compile(r"^\s*" + re.escape(key) + r":?[ \t]+(\S+)")
931
+ return [m.group(1) for m in map(rx.match, text.splitlines()) if m]
932
+
933
+
934
+ def _one_hex(text: str, key: str, refusals: list[str]) -> str | None:
935
+ vals = stdout_values(text, key)
936
+ if len(vals) != 1:
937
+ refusals.append(f"job stdout: {len(vals)} `{key}` line(s); exactly one is required")
938
+ return None
939
+ if not _HEX64.fullmatch(vals[0]):
940
+ refusals.append(f"job stdout: `{key}` is not 64 hex characters")
941
+ return None
942
+ return vals[0].lower()
943
+
944
+
945
+ def check_stdout(text: str, raw_sha: str, manifest: bytes | None, c12: str | None,
946
+ refusals: list[str], checks: list[str]) -> None:
947
+ """The operator's seal: verify-log-sha256 in the job stdout = sha256(raw log); pre- and post-manifest
948
+ hashes equal and equal to lake-manifest.json committed at the commit."""
949
+ seal = _one_hex(text, SHA_KEY, refusals)
950
+ if seal is not None:
951
+ if seal != raw_sha:
952
+ refusals.append(f"job stdout: {SHA_KEY} {seal[:12]}… is not the raw verify log's sha256 "
953
+ f"{raw_sha[:12]}…; the log is not the one the job sealed")
954
+ else:
955
+ checks.append(f"✓ seal: job stdout {SHA_KEY} = sha256(raw verify log) {raw_sha[:12]}…")
956
+ pre, post = _one_hex(text, PRE_KEY, refusals), _one_hex(text, POST_KEY, refusals)
957
+ if pre is None or post is None:
958
+ return
959
+ if pre != post:
960
+ refusals.append(f"job stdout: {PRE_KEY} {pre[:12]}… != {POST_KEY} {post[:12]}…; the manifest "
961
+ f"changed during the job")
962
+ return
963
+ if c12 is None:
964
+ return
965
+ if manifest is None:
966
+ refusals.append(f"no lake-manifest.json committed at {c12}; cannot check {PRE_KEY}")
967
+ return
968
+ man = hashlib.sha256(manifest).hexdigest()
969
+ if pre != man:
970
+ refusals.append(f"job stdout: manifest sha256 {pre[:12]}… is not lake-manifest.json committed at "
971
+ f"{c12} ({man[:12]}…)")
972
+ else:
973
+ checks.append(f"✓ manifest: pre = post = lake-manifest.json at {c12} ({man[:12]}…)")
974
+
975
+
976
+ # --------------------------------------------------------------------------
977
+ # the artifact seal (--artifacts)
978
+
979
+ ARTIFACTS_KEY = "artifacts-manifest-sha256"
980
+ ARTIFACTS_MANIFEST = "artifacts.sha256"
981
+ ARTIFACTS_RECEIPT_KEY = "artifacts_manifest_sha256"
982
+ HASH_CHUNK = 1 << 20
983
+ _MANIFEST_LINE = re.compile(rb"(.+) (0|[1-9][0-9]*) ([0-9a-f]{64})")
984
+
985
+
986
+ def _named(kind: str, names: list[str], limit: int = 5) -> str:
987
+ shown = ", ".join(names[:limit]) + (f" (+{len(names) - limit} more)" if len(names) > limit else "")
988
+ return f"{len(names)} {kind} file(s): {shown}"
989
+
990
+
991
+ def _bad_rel(rel: str) -> bool:
992
+ """A manifest path that is not a plain relative path inside the directory (absolute, empty, `.`/`..`
993
+ components, a backslash, a NUL)."""
994
+ parts = rel.split("/")
995
+ return (not rel or rel.startswith("/") or "\\" in rel or "\0" in rel
996
+ or any(x in ("", ".", "..") for x in parts))
997
+
998
+
999
+ def parse_artifacts_manifest(data: bytes, manifest_name: str) -> tuple[dict[str, tuple[int, str]], list[str]]:
1000
+ """({relative path: (size, sha256)}, problems) for the job's `<path> <size> <sha256>` lines: sorted by path
1001
+ (bytes), no duplicate, no path traversal, the manifest itself not listed, a final newline."""
1002
+ problems: list[str] = []
1003
+ entries: dict[str, tuple[int, str]] = {}
1004
+ if data and not data.endswith(b"\n"):
1005
+ problems.append(f"{manifest_name}: no final newline (a truncated copy?)")
1006
+ lines = data.split(b"\n")
1007
+ if lines and lines[-1] == b"":
1008
+ lines.pop()
1009
+ prev = None
1010
+ dups: list[str] = []
1011
+ bad: list[str] = []
1012
+ unsorted = False
1013
+ for n, line in enumerate(lines, 1):
1014
+ m = _MANIFEST_LINE.fullmatch(line)
1015
+ if not m:
1016
+ problems.append(f"{manifest_name} line {n}: not `<relative path> <size> <sha256>`")
1017
+ continue
1018
+ try:
1019
+ rel = m.group(1).decode("utf-8")
1020
+ except UnicodeDecodeError:
1021
+ problems.append(f"{manifest_name} line {n}: the path is not UTF-8")
1022
+ continue
1023
+ if _bad_rel(rel) or rel == manifest_name:
1024
+ bad.append(rel)
1025
+ continue
1026
+ if rel in entries:
1027
+ dups.append(rel)
1028
+ continue
1029
+ if prev is not None and m.group(1) < prev:
1030
+ unsorted = True
1031
+ prev = m.group(1)
1032
+ entries[rel] = (int(m.group(2)), m.group(3).decode())
1033
+ if bad:
1034
+ problems.append(f"{manifest_name}: {_named('path-traversal or invalid', bad)} (absolute, `..`, `.` or "
1035
+ f"empty components, or the manifest itself)")
1036
+ if dups:
1037
+ problems.append(f"{manifest_name}: {_named('duplicate', dups)}; each path is listed once")
1038
+ if unsorted:
1039
+ problems.append(f"{manifest_name}: the lines are not sorted by path (the job writes them sorted)")
1040
+ return entries, problems
1041
+
1042
+
1043
+ def walk_artifacts(root: pathlib.Path, manifest_name: str) -> tuple[dict[str, int], list[str], list[str]]:
1044
+ """({relative path: size} of every regular file under root, symlinks, special files); never follows a
1045
+ symlink. The manifest at the top is left out."""
1046
+ files: dict[str, int] = {}
1047
+ links: list[str] = []
1048
+ special: list[str] = []
1049
+ stack = [""]
1050
+ while stack:
1051
+ rel_dir = stack.pop()
1052
+ with os.scandir(root / rel_dir if rel_dir else root) as it:
1053
+ for e in it:
1054
+ rel = f"{rel_dir}/{e.name}" if rel_dir else e.name
1055
+ st = e.stat(follow_symlinks=False)
1056
+ if e.is_symlink():
1057
+ links.append(rel)
1058
+ elif e.is_dir(follow_symlinks=False):
1059
+ stack.append(rel)
1060
+ elif e.is_file(follow_symlinks=False):
1061
+ if rel != manifest_name:
1062
+ files[rel] = st.st_size
1063
+ else:
1064
+ special.append(rel)
1065
+ return files, sorted(links), sorted(special)
1066
+
1067
+
1068
+ def hash_file(path: pathlib.Path) -> str:
1069
+ """sha256 of a regular file read in 1 MiB chunks, opened without following a symlink."""
1070
+ h = hashlib.sha256()
1071
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
1072
+ with os.fdopen(fd, "rb") as f:
1073
+ while chunk := f.read(HASH_CHUNK):
1074
+ h.update(chunk)
1075
+ return h.hexdigest()
1076
+
1077
+
1078
+ def check_artifacts(root: pathlib.Path, manifest_name: str, stdout_text: str, refusals: list[str],
1079
+ checks: list[str]) -> tuple[bytes | None, dict | None]:
1080
+ """--artifacts DIR (the job's artifact seal): the manifest's sha256 must be the job stdout's one
1081
+ `artifacts-manifest-sha256` line (the stdout is bound by the stdout seal and sacct), and every file under DIR
1082
+ is rehashed in 1 MiB chunks against it: a missing, extra or changed file, a symlink, a special file, a
1083
+ path-traversal or duplicate manifest entry refuses. Previously copied files are adopted only by this rehash
1084
+ against the job's own manifest, never by another collection attempt's hashes. Returns (manifest bytes,
1085
+ summary) when every check passed, else (None, None)."""
1086
+ shown = manifest_name
1087
+ n0 = len(refusals)
1088
+ if root.is_symlink() or not root.is_dir():
1089
+ refusals.append(f"--artifacts {root.name}: not a directory (a symlink is not one)")
1090
+ return None, None
1091
+ mpath = root / manifest_name
1092
+ if mpath.is_symlink() or not mpath.is_file():
1093
+ refusals.append(f"--artifacts: no regular file {shown} in the directory (the job's manifest; a symlink is "
1094
+ f"not one)")
1095
+ return None, None
1096
+ data = mpath.read_bytes()
1097
+ actual = hashlib.sha256(data).hexdigest()
1098
+ sealed = _one_hex(stdout_text, ARTIFACTS_KEY, refusals)
1099
+ if sealed is not None and sealed != actual:
1100
+ refusals.append(f"--artifacts: {shown} hashes to {actual[:12]}…, not the job stdout's {ARTIFACTS_KEY} "
1101
+ f"{sealed[:12]}…; it is not the manifest the job wrote")
1102
+ entries, problems = parse_artifacts_manifest(data, shown)
1103
+ refusals += [f"--artifacts: {x}" for x in problems]
1104
+ try:
1105
+ files, links, special = walk_artifacts(root, manifest_name)
1106
+ except OSError as e:
1107
+ refusals.append(f"--artifacts: cannot list the directory: {e}")
1108
+ return None, None
1109
+ if links:
1110
+ refusals.append(f"--artifacts: {_named('symlink', links)}; the seal binds regular files only")
1111
+ if special:
1112
+ refusals.append(f"--artifacts: {_named('special', special)}; the seal binds regular files only")
1113
+ missing = sorted(set(entries) - set(files))
1114
+ extra = sorted(set(files) - set(entries))
1115
+ if missing:
1116
+ refusals.append(f"--artifacts: {_named('missing', missing)} (in {shown}, not in the directory)")
1117
+ if extra:
1118
+ refusals.append(f"--artifacts: {_named('extra', extra)} (in the directory, not in {shown})")
1119
+ changed: list[str] = []
1120
+ total = 0
1121
+ for rel in sorted(set(entries) & set(files)):
1122
+ size, digest = entries[rel]
1123
+ total += files[rel]
1124
+ if files[rel] != size:
1125
+ changed.append(rel)
1126
+ continue
1127
+ try:
1128
+ if hash_file(root / rel) != digest:
1129
+ changed.append(rel)
1130
+ except OSError as e:
1131
+ refusals.append(f"--artifacts: {rel}: cannot be read ({e.__class__.__name__})")
1132
+ if changed:
1133
+ refusals.append(f"--artifacts: {_named('changed', changed)} (size or sha256 differs from {shown})")
1134
+ if len(refusals) > n0:
1135
+ return None, None
1136
+ checks.append(f"✓ artifacts: {shown} sha256 = job stdout {ARTIFACTS_KEY} {actual[:12]}…; {len(entries)} "
1137
+ f"file(s), {total} bytes rehashed, none missing, extra or changed")
1138
+ return data, {"files": len(entries), "bytes": total, "manifest": shown, "manifest_sha256": actual}
1139
+
1140
+
1141
+ # --------------------------------------------------------------------------
1142
+ # the verify log
1143
+
1144
+ def redact(text: str, extra: list[re.Pattern], defaults=DEFAULT_REDACTIONS) -> tuple[str, int]:
1145
+ """(text with the executor's built-in redactions (default: the Slurm per-job prefixes) and every --redact
1146
+ match replaced, replacements made)."""
1147
+ n_total = 0
1148
+ for rx, repl in defaults:
1149
+ text, n = re.subn(rx, repl, text)
1150
+ n_total += n
1151
+ for rx in extra:
1152
+ text, n = rx.subn(REDACT_TOKEN, text)
1153
+ n_total += n
1154
+ return text, n_total
1155
+
1156
+
1157
+ def lines_differing(a: str, b: str) -> int:
1158
+ la, lb = a.splitlines(), b.splitlines()
1159
+ return sum(1 for x, y in zip(la, lb, strict=False) if x != y) + abs(len(la) - len(lb))
1160
+
1161
+
1162
+ def parse_log(text: str) -> tuple[dict, list[str]]:
1163
+ """(key -> value, refusals) for the recognised `key: value` lines of the (redacted) log, plus the derived
1164
+ `sorry-count` and `axioms` when the log has no such line."""
1165
+ values: dict[str, list[str]] = {}
1166
+ for line in text.splitlines():
1167
+ m = _KEY_LINE.match(line.rstrip("\r"))
1168
+ if m and m.group(1) in LOG_KEYS:
1169
+ values.setdefault(m.group(1), []).append(m.group(2))
1170
+ out, refusals = {}, []
1171
+ for key in LOG_KEYS:
1172
+ got = values.get(key, [])
1173
+ if len(got) > 1:
1174
+ refusals.append(f"verify log: `{key}:` appears {len(got)} times; exactly one is allowed")
1175
+ elif got:
1176
+ out[key] = got[0]
1177
+ for key in ("lean-toolchain", "mathlib-rev", "checker"):
1178
+ if key in out and not out[key]:
1179
+ refusals.append(f"verify log: `{key}:` is empty")
1180
+ del out[key]
1181
+ if "sorry-count" in out:
1182
+ if not re.fullmatch(r"\d+", out["sorry-count"]):
1183
+ refusals.append(f"verify log: `sorry-count:` is not a non-negative integer: {out['sorry-count']!r}")
1184
+ out["sorry-count"] = None
1185
+ else:
1186
+ out["sorry-count"] = int(out["sorry-count"])
1187
+ # A declared count comes from the job's own script (often an inventory of declarations); Lean's
1188
+ # warnings in the same log are the ground truth, and the script may have missed a declaration
1189
+ # (a `lemma` outside a theorem-only inventory, field report). Never accept fewer than Lean printed.
1190
+ warned = len(_SORRY_RE.findall(text))
1191
+ if warned > out["sorry-count"]:
1192
+ refusals.append(f"verify log: `sorry-count: {out['sorry-count']}` but the log has {warned} "
1193
+ f"`declaration uses 'sorry'` warning(s); a declared count may not hide Lean's own "
1194
+ f"warnings (check what the script's inventory leaves out)")
1195
+ elif _SORRY_RE.search(text) or _BUILD_DONE_RE.search(text):
1196
+ out["sorry-count"] = len(_SORRY_RE.findall(text))
1197
+ else:
1198
+ # no count and no sign the build finished: a cut-short or wrong log would read as 0 (#82)
1199
+ refusals.append("verify log: no `sorry-count:` line and no build-completion line (`Build completed "
1200
+ "successfully` or `lake build: ok`); the sorry count is unknown")
1201
+ out["sorry-count"] = None
1202
+ if out.get("sorry-count"):
1203
+ refusals.append(f"verify log: sorry count is {out['sorry-count']}; gate requires 0")
1204
+ printed = [[_no_universe(a) for a in parse_axioms(m)] for m in _DEPENDS_RE.findall(text)]
1205
+ if "axioms" in out:
1206
+ out["axioms"] = [_no_universe(a) for a in parse_axioms(out["axioms"])]
1207
+ # Like sorry-count: a declared list comes from the job's script; Lean's own `#print axioms` output in
1208
+ # the same log may not name an axiom the list leaves out.
1209
+ missing = sorted({a for lst in printed for a in lst} - set(out["axioms"]))
1210
+ if missing:
1211
+ refusals.append(f"verify log: `axioms:` omits {', '.join(missing)}, which the log's own `#print axioms` "
1212
+ f"output reports; a declared list may not hide Lean's output (check what the script's "
1213
+ f"inventory leaves out)")
1214
+ else:
1215
+ found = printed
1216
+ if not found and not _NO_AXIOMS_RE.search(text):
1217
+ refusals.append("verify log: no `axioms:` line and no `#print axioms` output "
1218
+ "(`depends on axioms: [...]` / `does not depend on any axioms`)")
1219
+ else:
1220
+ union: list[str] = []
1221
+ for lst in found:
1222
+ union += [a for a in lst if a not in union]
1223
+ out["axioms"] = union
1224
+ if "generated-at" in out:
1225
+ try:
1226
+ core.parse_ts(out["generated-at"])
1227
+ except (ValueError, TypeError):
1228
+ refusals.append(f"verify log: `generated-at:` is not an ISO-8601 timestamp: {out['generated-at']!r}")
1229
+ del out["generated-at"]
1230
+ return out, refusals
1231
+
1232
+
1233
+ # The log keys whose value the receipt takes from the raw log; `checker:` and the container image ref are
1234
+ # published as redacted (REDACTED_KEYS).
1235
+ RAW_KEYS = ("lean-toolchain", "mathlib-rev", "sorry-count", "axioms", "commit", "job-id", "generated-at",
1236
+ "src-head", ctr.ENGINE_KEY, *ctr.DIGEST_KEYS)
1237
+ REDACTED_KEYS = ("checker", ctr.REF_KEY)
1238
+
1239
+
1240
+ def _evidence_counts(text: str) -> tuple[int, int, int, int]:
1241
+ """(sorry warnings, `#print axioms` lists, no-axioms lines, build-completion lines) in a log text."""
1242
+ return (len(_SORRY_RE.findall(text)), len(_DEPENDS_RE.findall(text)), len(_NO_AXIOMS_RE.findall(text)),
1243
+ len(_BUILD_DONE_RE.findall(text)))
1244
+
1245
+
1246
+ def _key_lines(text: str, key: str) -> list[str]:
1247
+ """The values of the log's `key:` lines, as written (a declared line removed by a redaction differs even
1248
+ when the derived value happens to agree)."""
1249
+ out = []
1250
+ for line in text.splitlines():
1251
+ m = _KEY_LINE.match(line.rstrip("\r"))
1252
+ if m and m.group(1) == key:
1253
+ out.append(m.group(2))
1254
+ return out
1255
+
1256
+
1257
+ def parse_raw_log(raw_text: str, redacted: str) -> tuple[dict, list[str]]:
1258
+ """parse_log on the RAW log (review finding 3: a broad --redact must never delete the sorry or axiom
1259
+ evidence before it is counted), with `checker:` taken from the redacted log (the published text). A
1260
+ redaction that removed or altered a line the parser reads (Lean's sorry warnings, `#print axioms` output,
1261
+ a build-completion line, or any `key: value` line but `checker:`) refuses."""
1262
+ fields, problems = parse_log(raw_text)
1263
+ red_fields, _red_problems = parse_log(redacted)
1264
+ for key in REDACTED_KEYS:
1265
+ if key in red_fields:
1266
+ fields[key] = red_fields[key]
1267
+ else:
1268
+ fields.pop(key, None)
1269
+ changed = [k for k in RAW_KEYS if fields.get(k) != red_fields.get(k)
1270
+ or _key_lines(raw_text, k) != _key_lines(redacted, k)]
1271
+ names = ("`declaration uses sorry` warnings", "`#print axioms` results", "`does not depend on any axioms` lines",
1272
+ "build-completion lines")
1273
+ changed += [n for n, a, b in zip(names, _evidence_counts(raw_text), _evidence_counts(redacted), strict=False) if a != b]
1274
+ if ca.claim_lines(raw_text) != ca.claim_lines(redacted):
1275
+ changed.append("claim-axioms lines")
1276
+ if changed:
1277
+ problems.append(f"redaction changed what the receipt is read from: {', '.join(changed)} differ between the "
1278
+ f"raw and the redacted log; narrow the --redact pattern so it leaves those lines intact")
1279
+ return fields, problems
1280
+
1281
+
1282
+ def _no_universe(name: str) -> str:
1283
+ """`Classical.choice.{u}` -> `Classical.choice`: Lean may print an axiom with its universe parameters; it is
1284
+ the same axiom, so lists are compared by the bare name."""
1285
+ return re.sub(r"\.\{[^{}]*\}$", "", name)
1286
+
1287
+
1288
+ def parse_axioms(value: str) -> list[str]:
1289
+ """`propext, Quot.sound, Classical.choice` (brackets optional, commas and/or spaces); `none` or empty: []."""
1290
+ inner = value.strip().removeprefix("[").removesuffix("]").strip()
1291
+ if inner.casefold() in ("", "none"):
1292
+ return []
1293
+ out: list[str] = []
1294
+ for a in re.split(r"[,\s]+", inner):
1295
+ if a and a not in out:
1296
+ out.append(a)
1297
+ return out
1298
+
1299
+
1300
+ def manifest_mathlib_rev(manifest: bytes | None) -> str | None:
1301
+ """The mathlib rev the manifest pins, `none` (gate_mod.NO_MATHLIB) when it is readable and lists no mathlib
1302
+ package, None when absent or unreadable."""
1303
+ return gate_mod.manifest_mathlib(manifest)
1304
+
1305
+
1306
+ # --------------------------------------------------------------------------
1307
+ # the command
1308
+
1309
+ def resolve_commit(repo: pathlib.Path, sha: str) -> str | None:
1310
+ p = core.git(repo, "rev-parse", "--verify", "--quiet", f"{sha}^{{commit}}")
1311
+ return p.stdout.strip() if p.returncode == 0 and p.stdout.strip() else None
1312
+
1313
+
1314
+ def package_path_hint(repo: pathlib.Path, commit: str) -> str:
1315
+ """Why `lean-toolchain` is absent at --commit for this --repo: the commit's files are read at the path of
1316
+ --repo inside its git repository (`git rev-parse --show-prefix`), so a copy of the package placed at another
1317
+ path of the same repository (a frozen review packet, say) reads nothing. Names that path and the paths at
1318
+ which the commit does hold a `lean-toolchain` (at most five), all relative to the repository root."""
1319
+ p = core.git(repo, "rev-parse", "--show-prefix")
1320
+ prefix = p.stdout.strip() if p.returncode == 0 else ""
1321
+ ls = core.git(repo, "ls-tree", "-r", "--full-tree", "--name-only", "-z", commit)
1322
+ names = ls.stdout.split("\0") if ls.returncode == 0 else []
1323
+ found = sorted({n[:-len("lean-toolchain")] or "./" for n in names
1324
+ if n == "lean-toolchain" or n.endswith("/lean-toolchain")})
1325
+ where = ", ".join(found[:5]) + (f" (and {len(found) - 5} more)" if len(found) > 5 else "") if found else "no path"
1326
+ return (f" (--repo is `{prefix or './'}` in its git repository and the commit's files are read there; "
1327
+ f"at {commit[:12]} a lean-toolchain is committed at: {where}; pass the package directory of a "
1328
+ f"checkout at its committed path, not a copy placed elsewhere)")
1329
+
1330
+
1331
+ def commit_package_files(repo: pathlib.Path, commit: str, refusals: list[str]) -> tuple[str | None, bytes | None]:
1332
+ """(lean-toolchain, lake-manifest.json) committed at `commit`, read relative to the package directory
1333
+ --repo (which may be a subdirectory of its repository); an absent lean-toolchain is a refusal naming where
1334
+ the commit does hold one."""
1335
+ toolchain = None
1336
+ blob = core.git_show_bytes(repo, "./lean-toolchain", commit)
1337
+ if blob is None:
1338
+ refusals.append(f"no lean-toolchain committed at {commit[:12]}" + package_path_hint(repo, commit))
1339
+ else:
1340
+ toolchain = blob.decode("utf-8", "replace").strip()
1341
+ return toolchain, core.git_show_bytes(repo, "./lake-manifest.json", commit)
1342
+
1343
+
1344
+ # Local identity tokens shorter than this, or in this list, are never blocking tokens (too common in logs).
1345
+ IDENTITY_MIN_LEN = 3
1346
+ IDENTITY_STOPWORDS = frozenset({
1347
+ "admin", "build", "builder", "ci", "default", "docker", "false", "guest", "home", "host", "lean", "linux",
1348
+ "local", "localhost", "localdomain", "main", "nobody", "none", "null", "root", "runner", "server", "test",
1349
+ "true", "ubuntu", "user", "users", "worker"})
1350
+ # A home directory with or without a trailing slash (the shared built-in family needs the slash).
1351
+ HOME_DIR_RE = r"(?<![A-Za-z0-9_.-])/(?:home|Users)/[A-Za-z0-9._-]+(?![A-Za-z0-9._-])"
1352
+
1353
+
1354
+ def local_identity() -> dict[str, str]:
1355
+ """{token: label}: this machine's user name (getpass.getuser(), $USER, $LOGNAME) and host name
1356
+ (socket.gethostname(), full and its first label), derived when the receipt is written, never stored.
1357
+ Labels name the source, never the value."""
1358
+ found: dict[str, str] = {}
1359
+ users = []
1360
+ try:
1361
+ users.append(getpass.getuser())
1362
+ except Exception: # no passwd entry and no environment variable: nothing to derive
1363
+ pass
1364
+ users += [os.environ.get("USER") or "", os.environ.get("LOGNAME") or ""]
1365
+ try:
1366
+ host = socket.gethostname() or ""
1367
+ except OSError:
1368
+ host = ""
1369
+ for label, values in (("local user name", users), ("local host name", [host, host.split(".")[0]])):
1370
+ for v in values:
1371
+ v = (v or "").strip()
1372
+ if (len(v) >= IDENTITY_MIN_LEN and v.casefold() not in IDENTITY_STOPWORDS
1373
+ and re.search(r"[A-Za-z]", v)):
1374
+ found.setdefault(v, label)
1375
+ return found
1376
+
1377
+
1378
+ def _scanner(repo: pathlib.Path) -> ps.Scanner:
1379
+ sc = ps.Scanner({}, repo, None)
1380
+ sc.emails = set() # a receipt declares no address: every one is a hit
1381
+ extra = [ps.Pattern("home-path", "builtin", re.compile(HOME_DIR_RE))] # same family as the shared one
1382
+ for tok, label in local_identity().items():
1383
+ rx = re.compile(r"(?<![A-Za-z0-9_])" + re.escape(tok) + r"(?![A-Za-z0-9_])", re.I)
1384
+ extra.append(ps.Pattern(label, "derived", rx))
1385
+ sc.patterns = sc.patterns + extra
1386
+ sc._active = {}
1387
+ for problem in sc.problems:
1388
+ print(f"lean-pkg: WARN {problem}", file=sys.stderr)
1389
+ return sc
1390
+
1391
+
1392
+ def blocking_families(sc: ps.Scanner, text: str) -> list[str]:
1393
+ return sorted({ps.PATTERNS_FILE if pat.kind == "file" else pat.label
1394
+ for _n, pat, _ex in sc.scan_text(text) if pat.severity == ps.BLOCK})
1395
+
1396
+
1397
+ def _shown(path: pathlib.Path, repo: pathlib.Path) -> str:
1398
+ """The path relative to the repository when inside it, else its file name (never an absolute path,
1399
+ which would carry a user name into the README)."""
1400
+ try:
1401
+ return path.resolve().relative_to(repo.resolve()).as_posix()
1402
+ except ValueError:
1403
+ return path.name
1404
+
1405
+
1406
+ def _same_or_absent(path: pathlib.Path, data: bytes) -> str | None:
1407
+ if path.is_symlink():
1408
+ return f"{path.name}: a symlink is in the way; nothing written"
1409
+ if path.exists() and path.read_bytes() != data:
1410
+ return f"{path.name} already exists with different content; remove it first (nothing written)"
1411
+ return None
1412
+
1413
+
1414
+ def _other_form_problem(path: pathlib.Path, log_bytes: bytes, report_sha: str) -> str | None:
1415
+ """The sealed log in the form this run does not write (.log beside a --compress-log run, .log.gz beside a
1416
+ plain one) is left alone when it holds the same log, else refused: gate checks every copy it finds."""
1417
+ if path.is_symlink():
1418
+ return f"{path.name}: a symlink is in the way; nothing written"
1419
+ if not path.exists():
1420
+ return None
1421
+ if path.name.endswith(gate_mod.REPORT_GZ_SUFFIX):
1422
+ try:
1423
+ same = gate_mod.gunzip_digest(path, len(log_bytes), path.name) == (report_sha, len(log_bytes))
1424
+ except core.Fail:
1425
+ same = False
1426
+ else:
1427
+ same = path.read_bytes() == log_bytes
1428
+ return None if same else (f"{path.name} already exists with a different log; remove it first "
1429
+ f"(nothing written)")
1430
+
1431
+
1432
+ def _kept_fallback_time(path: pathlib.Path, receipt: dict) -> str | None:
1433
+ """#85: the `generated_at` of the receipt already at `path` when it is identical to `receipt` but for that
1434
+ field (same keys, same order, same values) and that field is a valid timestamp, else None. Only used when the
1435
+ new `generated_at` came from the clock, so an identical re-run in a later second is not refused."""
1436
+ if path.is_symlink() or not path.is_file():
1437
+ return None
1438
+ try:
1439
+ old = json.loads(path.read_text(encoding="utf-8"))
1440
+ except (OSError, UnicodeDecodeError, ValueError):
1441
+ return None
1442
+ if not isinstance(old, dict) or list(old) != list(receipt) or not isinstance(old.get("generated_at"), str):
1443
+ return None
1444
+ try:
1445
+ core.parse_ts(old["generated_at"])
1446
+ except (ValueError, TypeError):
1447
+ return None
1448
+ if any(old[k] != v for k, v in receipt.items() if k != "generated_at"):
1449
+ return None
1450
+ return old["generated_at"]
1451
+
1452
+
1453
+ def _write(path: pathlib.Path, data: bytes) -> None:
1454
+ tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}")
1455
+ tmp.write_bytes(data)
1456
+ os.replace(tmp, path)
1457
+
1458
+
1459
+ def readme_block(*, commit: str, heading: str, executor_lines: list[str], receipt: dict, log_name: str,
1460
+ raw_sha: str, n_diff: int, redaction_note: str, extra: list[str], seal: dict | None = None,
1461
+ evidence_lines: list[str] | None = None, log_commit_bound: bool | None = None) -> str:
1462
+ """The `.lean-receipts/README.md` entry, in the field operator's block shape: the executor's own lines
1463
+ (job or unit state), then checker, log, any further evidence lines, and the seal. `seal`
1464
+ ({job_stdout_sha256, manifest_sha256}, only with --stdout) adds the line naming what the seal was checked
1465
+ against. `log_commit_bound` False (the verify log has no `commit:` line) adds a WARN line, so the README
1466
+ entry keeps the limitation the run's stderr WARN states (field report)."""
1467
+ axioms = ", ".join(receipt["axioms"]) or "none"
1468
+ # The heading gets the commit prefix itself; a --readme-heading that already starts with this commit
1469
+ # (`4095a30`: ... or 4095a30: ...) would print it twice (field report). Any other SHA is kept.
1470
+ m = re.match(r"`?([0-9a-f]{7,40})`?:\s*", heading)
1471
+ if m and commit.startswith(m.group(1)):
1472
+ heading = heading[m.end():]
1473
+ lines = [f"## `{commit[:7]}`: {heading}", "", *executor_lines,
1474
+ f"- Checker: {receipt['checker']}; sorry_count 0; axioms {axioms}.",
1475
+ f"- Log: `{log_name}`, SHA-256 `{receipt['report_sha256']}` (= `report_sha256`);",
1476
+ f" raw log SHA-256 `{raw_sha}` ({n_diff} line(s) differ: {redaction_note})."]
1477
+ lines += evidence_lines or []
1478
+ if log_commit_bound is False:
1479
+ lines.append(f"- WARN: {NO_COMMIT_LINE} (`log_commit_bound: false`).")
1480
+ if seal:
1481
+ lines.append(f"- Seal: job stdout SHA-256 `{seal['job_stdout_sha256']}` carries {SHA_KEY} = raw log "
1482
+ f"SHA-256 `{raw_sha}`; lake-manifest.json SHA-256 `{seal['manifest_sha256']}` (pre = post).")
1483
+ return "\n".join(lines + [x for x in extra if x.strip()]) + "\n"
1484
+
1485
+
1486
+ def common_usage(args) -> list[re.Pattern]:
1487
+ """The usage checks every `receipt` form shares (exit 2); returns the compiled --redact patterns."""
1488
+ if args.commit_sha is not None and (not args.commit_sha.strip() or args.commit_sha.startswith("-")):
1489
+ raise core.UsageError(f"--commit must name a commit, got {args.commit_sha!r}")
1490
+ if args.tar_sha256 is not None and not _HEX64.fullmatch(args.tar_sha256):
1491
+ raise core.UsageError("--tar-sha256 must be 64 hex characters")
1492
+ if args.checker is not None and not args.checker.strip():
1493
+ raise core.UsageError("--checker must not be empty")
1494
+ extra = []
1495
+ for r in args.redact or []:
1496
+ try:
1497
+ extra.append(re.compile(r))
1498
+ except re.error as e:
1499
+ raise core.UsageError(f"--redact {r!r} is not a valid regular expression ({e.msg})") from None
1500
+ return extra
1501
+
1502
+
1503
+ def repo_dir(args) -> pathlib.Path:
1504
+ repo = pathlib.Path(args.repo or ".").expanduser()
1505
+ if not repo.is_dir():
1506
+ raise core.UsageError(f"--repo {repo}: not a directory")
1507
+ return repo
1508
+
1509
+
1510
+ class Evidence:
1511
+ """What an executor (`receipt slurm`, `receipt systemd`) hands the shared pipeline in `produce`: its job
1512
+ identity, the refusals and check lines of its own terminal-state checks (listed first), its README lines,
1513
+ and the extra evidence files and receipt keys it persists."""
1514
+
1515
+ def __init__(self, *, verb: str, job_id: str, refusals: list[str], checks: list[str],
1516
+ executor_lines, default_heading: str, check_log_job_id, json_extra: dict,
1517
+ redactions=DEFAULT_REDACTIONS, redaction_note: str = "per-job paths redacted",
1518
+ stdout_check=None, evidence_files=(), redact_help: str = "add a --redact REGEX for it",
1519
+ receipt_extra: dict | None = None, sacct_seal=None):
1520
+ self.verb, self.job_id = verb, job_id
1521
+ self.refusals, self.checks = refusals, checks
1522
+ self.executor_lines = executor_lines # (receipt file name, tar clause) -> list[str]
1523
+ self.default_heading = default_heading
1524
+ self.check_log_job_id = check_log_job_id # the log's `job-id:` value -> refusal or None
1525
+ self.json_extra = json_extra
1526
+ self.redactions, self.redaction_note = redactions, redaction_note
1527
+ self.stdout_check = stdout_check # (job stdout text, refusals, checks) -> None
1528
+ # (suffix, bytes, receipt key, README line template with {name} and {sha}): written beside the receipt
1529
+ # as `<c12>-<slug>-<suffix>`, its SHA-256 stored under the receipt key
1530
+ self.evidence_files = list(evidence_files)
1531
+ self.redact_help = redact_help
1532
+ self.receipt_extra = dict(receipt_extra or {}) # additive receipt keys (e.g. `producer`), gate ignores
1533
+ # `receipt slurm --seal-sacct`: (receipt, record's .lean-receipts/ path) -> (slurm_sacct block, record
1534
+ # bytes), raising core.Fail; the record is written beside the receipt as `<c12>-<slug>-sacct.txt`
1535
+ self.sacct_seal = sacct_seal
1536
+
1537
+
1538
+ def check_seal(paths: dict, raw: bytes, manifest: bytes | None, c12: str | None, refusals: list[str],
1539
+ checks: list[str], stdout_check=None) -> dict | None:
1540
+ """The seal (stdout, else the in-log fallback) and the empty stderr; returns the seal evidence persisted
1541
+ with --stdout (#72), else None."""
1542
+ raw_sha = hashlib.sha256(raw).hexdigest()
1543
+ seal = None
1544
+ if "--stdout" in paths:
1545
+ out_raw = paths["--stdout"].read_bytes()
1546
+ out_text = out_raw.decode("utf-8", errors="replace")
1547
+ check_stdout(out_text, raw_sha, manifest, c12, refusals, checks)
1548
+ if stdout_check:
1549
+ stdout_check(out_text, refusals, checks)
1550
+ seal = {"job_stdout_sha256": hashlib.sha256(out_raw).hexdigest(),
1551
+ "manifest_sha256": hashlib.sha256(manifest).hexdigest() if manifest is not None else None}
1552
+ else:
1553
+ why = check_self_hash(raw)
1554
+ if why:
1555
+ refusals.append(why)
1556
+ else:
1557
+ checks.append(f"✓ seal: in-log {SHA_KEY} (fallback; no --stdout)")
1558
+ checks.append("· manifest: not checked (no --stdout)")
1559
+ if "--stderr" in paths:
1560
+ n = paths["--stderr"].stat().st_size
1561
+ if n:
1562
+ refusals.append(f"job stderr is not empty ({n} bytes); a clean job writes nothing there")
1563
+ else:
1564
+ checks.append("✓ stderr: empty")
1565
+ else:
1566
+ checks.append("· stderr: not checked (no --stderr)")
1567
+ return seal
1568
+
1569
+
1570
+ def check_fields(fields: dict, *, commit: str | None, toolchain: str | None, manifest: bytes | None,
1571
+ checker_flag: str | None, check_log_job_id, refusals: list[str]) -> tuple[str | None, str | None]:
1572
+ """(mathlib_rev, checker): the log's fields against the commit and the flags. Without a commit (preflight
1573
+ without --commit) the commit-side comparisons are skipped."""
1574
+ c12 = commit[:12] if commit else None
1575
+ if toolchain is not None and "lean-toolchain" in fields and fields["lean-toolchain"] != toolchain:
1576
+ refusals.append(f"toolchain mismatch: verify log says {fields['lean-toolchain']!r}, "
1577
+ f"lean-toolchain committed at {c12} says {toolchain!r}")
1578
+ mathlib = manifest_mathlib_rev(manifest)
1579
+ if mathlib and "mathlib-rev" in fields and fields["mathlib-rev"] != mathlib:
1580
+ refusals.append(f"mathlib mismatch: verify log says {fields['mathlib-rev']!r}, lake-manifest.json "
1581
+ f"committed at {c12} " + (f"has no mathlib package (the log line is then "
1582
+ f"`mathlib-rev: {gate_mod.NO_MATHLIB}`, or none at all)"
1583
+ if mathlib == gate_mod.NO_MATHLIB else f"says {mathlib!r}"))
1584
+ # a package without Mathlib: `none` is read from the manifest itself, so the log needs no line for it
1585
+ mathlib = mathlib or fields.get("mathlib-rev")
1586
+ if commit is not None and not mathlib:
1587
+ refusals.append(f"no mathlib rev: no `mathlib` package in lake-manifest.json at {c12} and no "
1588
+ f"`mathlib-rev:` line in the verify log")
1589
+ checker = checker_flag.strip() if checker_flag else fields.get("checker")
1590
+ if not checker:
1591
+ refusals.append("no checker: pass --checker TEXT (the exact checker command or mode) or print a "
1592
+ "`checker:` line in the verify log")
1593
+ if commit is not None and "commit" in fields:
1594
+ claimed = fields["commit"].lower()
1595
+ if len(claimed) < 7 or not commit.startswith(claimed):
1596
+ refusals.append(f"verify log: `commit:` {fields['commit']!r} is not --commit {c12}")
1597
+ # `src-head:` (the template's SRC_MODE=clone): the HEAD of the job's clone, a full SHA that must be --commit.
1598
+ if commit is not None and "src-head" in fields and fields["src-head"].lower() != commit.lower():
1599
+ refusals.append(f"verify log: `src-head:` {fields['src-head']!r} is not --commit {c12} (the job's clone "
1600
+ f"was not checked out at the commit)")
1601
+ if "job-id" in fields and check_log_job_id is not None:
1602
+ why = check_log_job_id(fields["job-id"])
1603
+ if why:
1604
+ refusals.append(why)
1605
+ return mathlib, checker
1606
+
1607
+
1608
+ NO_COMMIT_LINE = ("the verify log has no commit: line; it is bound to the commit only through "
1609
+ "lake-manifest.json")
1610
+
1611
+
1612
+ def commit_line_binding(fields: dict, commit: str | None, stdout_seal: bool, refusals: list[str],
1613
+ checks: list[str]) -> bool | None:
1614
+ """The verify log's own binding to --commit (review finding 5): a `commit:` line must equal --commit
1615
+ (check_fields refuses a mismatch). Without one, the fallback seal (no --stdout: only the log's own hash)
1616
+ binds the log to nothing, so it refuses; with --stdout the manifest seal is the only binding: `produce`
1617
+ prints a stderr WARN and `log_commit_bound: false`. Returns True / False, None without a resolved commit."""
1618
+ if commit is None:
1619
+ return None
1620
+ if "commit" in fields:
1621
+ claimed = fields["commit"].lower()
1622
+ if len(claimed) >= 7 and commit.startswith(claimed):
1623
+ checks.append(f"✓ log: `commit:` line = --commit {commit[:12]}")
1624
+ return True
1625
+ return False # check_fields has refused the mismatch
1626
+ if not stdout_seal:
1627
+ refusals.append(f"verify log: no `commit:` line; with the in-log fallback seal (no --stdout) nothing "
1628
+ f"binds the log to --commit {commit[:12]} (print `commit: <sha>` in the log, as the "
1629
+ f"--template does, or pass the job's stdout with --stdout)")
1630
+ return False
1631
+ checks.append(f"· log: no `commit:` line; {NO_COMMIT_LINE.split('; ', 1)[1]}")
1632
+ return False
1633
+
1634
+
1635
+ def evidence_symlink_problem(repo: pathlib.Path, commit: str | None) -> str | None:
1636
+ """Review finding 1: a committed symlink at --commit that resolves into .lean-receipts/ (gate refuses it:
1637
+ a later "evidence" edit would change what the build reads)."""
1638
+ if commit is None:
1639
+ return None
1640
+ try:
1641
+ links = core.evidence_symlinks(core.bound_tree(repo, commit))
1642
+ except core.Fail as e:
1643
+ return str(e)
1644
+ if links:
1645
+ return (f"symlinks at {commit[:12]} point into .lean-receipts/: {', '.join(links)}; gate refuses such a "
1646
+ f"commit (the evidence-only rule would let the target change); replace them with the files")
1647
+ return None
1648
+
1649
+
1650
+ def lake_cache_check(repo: pathlib.Path, commit: str | None, raw_text: str, refusals: list[str],
1651
+ checks: list[str]) -> None:
1652
+ """A root-package module the log shows Lake restored (Reused, Replayed, Unpacked) instead of compiling
1653
+ refuses: its sorry warning need not be in the log (lake_hygiene). Root modules: the tracked .lean sources
1654
+ and lean_lib roots at the commit (without one, of the checkout)."""
1655
+ try:
1656
+ if commit is not None:
1657
+ tracked = list(core.bound_tree(repo, commit))
1658
+ toml, lean = (core.git_show_bytes(repo, f"./{n}", commit) for n in ("lakefile.toml", "lakefile.lean"))
1659
+ else:
1660
+ p = core.git(repo, "ls-files", "--", ".")
1661
+ tracked = p.stdout.splitlines() if p.returncode == 0 else []
1662
+ toml, lean = ((repo / n).read_bytes() if (repo / n).is_file() else None
1663
+ for n in ("lakefile.toml", "lakefile.lean"))
1664
+ except core.Fail as e:
1665
+ refusals.append(str(e))
1666
+ return
1667
+ files = lh.tracked_lean_files(tracked)
1668
+ roots = lh.package_roots(*(b.decode("utf-8", "replace") if b is not None else None for b in (toml, lean)),
1669
+ files)
1670
+ found, ok = lh.cache_reuse_problems(raw_text, files, roots)
1671
+ refusals += found
1672
+ checks += ok
1673
+
1674
+
1675
+ def container_evidence(fields: dict, paths: dict, refusals: list[str], checks: list[str]) -> dict | None:
1676
+ """The additive `container` value (#236, container.from_log): the verify log's container lines, and with
1677
+ --stdout the job stdout's matching digest line. None when the job names no container."""
1678
+ values = None
1679
+ if "--stdout" in paths:
1680
+ out_text = paths["--stdout"].read_bytes().decode("utf-8", errors="replace")
1681
+
1682
+ def values(key: str) -> list[str]:
1683
+ return stdout_values(out_text, key)
1684
+ return ctr.from_log(fields, values, refusals, checks)
1685
+
1686
+
1687
+ def claim_axioms_evidence(repo: pathlib.Path, commit: str | None, raw_text: str, refusals: list[str],
1688
+ checks: list[str]) -> dict | None:
1689
+ """The receipt's additive `claim_axioms` key (claim_axioms.judge) from the RAW log's claim-axioms lines,
1690
+ every claim of claims.yaml committed at the commit required (no commit: not required).
1691
+ None, with a `·` line, when the log has no such line (an older verify script): the receipt is as before."""
1692
+ required = None
1693
+ blob = core.git_show_bytes(repo, "./claims.yaml", commit) if commit else None
1694
+ summary, found, lines = ca.judge(raw_text, None)
1695
+ if summary is None:
1696
+ if blob is not None:
1697
+ checks.append("· claim axioms: no claim-axioms lines in the verify log (a verify script without the "
1698
+ "probe); only the `#print axioms` output is read, for the theorems it prints")
1699
+ return None
1700
+ if commit is not None:
1701
+ required, problems = ca.required_claims(blob)
1702
+ refusals += problems
1703
+ summary, found, lines = ca.judge(raw_text, required)
1704
+ refusals += found
1705
+ checks += lines
1706
+ if summary["nonstandard"] and not found:
1707
+ checks.append("· claim axioms beyond propext, Quot.sound, Classical.choice: "
1708
+ + "; ".join(f"{e['decl']} ({', '.join(e['axioms'])})" for e in summary["nonstandard"][:10])
1709
+ + " (gate refuses them unless gate.axioms_allowed lists them)")
1710
+ return summary
1711
+
1712
+
1713
+ def hypotheses_evidence(repo: pathlib.Path, commit: str | None, raw_text: str, redacted: str,
1714
+ refusals: list[str], checks: list[str]) -> None:
1715
+ """The `hyp-probe/1` section's write-time structure check (hypotheses.judge_structure) on the RAW log, with
1716
+ the redacted log's section lines required equal. No receipt key (report_sha256 seals the section); a log
1717
+ without the section adds nothing, unless claims.yaml at the commit uses the conditional-claim keys (a `·`
1718
+ line)."""
1719
+ blob = core.git_show_bytes(repo, "./claims.yaml", commit) if commit else None
1720
+ _summary, found, lines = hyp.judge_structure(raw_text, blob, redacted)
1721
+ refusals += found
1722
+ checks += lines
1723
+
1724
+
1725
+ def produce(args, ev: Evidence, repo: pathlib.Path, paths: dict, extra: list[re.Pattern]) -> int:
1726
+ """The shared second half of every `receipt` form: commit facts, the seal, the verify log's fields, redaction,
1727
+ the public-safety scan, and (when nothing refused) the receipt, the redacted log, the executor's evidence
1728
+ files and the README entry. Every check runs before anything is written."""
1729
+ refusals, checks = ev.refusals, ev.checks
1730
+ slug = gate_mod.receipt_job_slug(ev.job_id)
1731
+ commit = resolve_commit(repo, args.commit_sha)
1732
+ c12 = commit[:12] if commit else None
1733
+ toolchain = manifest = None
1734
+ if commit is None:
1735
+ refusals.append(f"--commit {args.commit_sha}: not a commit in the --repo checkout "
1736
+ f"(default the current directory)")
1737
+ else:
1738
+ toolchain, manifest = commit_package_files(repo, commit, refusals)
1739
+
1740
+ raw = paths["--log"].read_bytes()
1741
+ raw_sha = hashlib.sha256(raw).hexdigest()
1742
+ seal = check_seal(paths, raw, manifest, c12, refusals, checks, ev.stdout_check)
1743
+
1744
+ raw_text = raw.decode("utf-8", errors="replace")
1745
+ redacted, n_redacted = redact(raw_text, extra, ev.redactions)
1746
+ n_diff = lines_differing(raw_text, redacted)
1747
+ fields, problems = parse_raw_log(raw_text, redacted)
1748
+ refusals += problems
1749
+ lake_cache_check(repo, commit, raw_text, refusals, checks)
1750
+ mathlib, checker = check_fields(fields, commit=commit, toolchain=toolchain, manifest=manifest,
1751
+ checker_flag=args.checker, check_log_job_id=ev.check_log_job_id,
1752
+ refusals=refusals)
1753
+ log_commit_bound = commit_line_binding(fields, commit, "--stdout" in paths, refusals, checks)
1754
+ container = container_evidence(fields, paths, refusals, checks)
1755
+ claim_axioms = claim_axioms_evidence(repo, commit, raw_text, refusals, checks)
1756
+ hypotheses_evidence(repo, commit, raw_text, redacted, refusals, checks)
1757
+ why = evidence_symlink_problem(repo, commit)
1758
+ if why:
1759
+ refusals.append(why)
1760
+
1761
+ name12 = c12 or "0" * 12
1762
+ out = (pathlib.Path(args.out).expanduser() if args.out
1763
+ else repo / ".lean-receipts" / f"{name12}-{slug}.json")
1764
+ log_out = out.with_name(f"{name12}-{slug}-verify.redacted.log")
1765
+ log_bytes = redacted.encode("utf-8")
1766
+ report_sha = hashlib.sha256(log_bytes).hexdigest()
1767
+ receipt = {
1768
+ "schema": core.LOWER_RECEIPT_SCHEMA, # 0.22.0 (1.0 command tree, section 6): readers accept it absent
1769
+ "commit": commit,
1770
+ "lean_toolchain": toolchain,
1771
+ "mathlib_rev": mathlib,
1772
+ "sorry_count": fields.get("sorry-count"),
1773
+ "axioms": fields.get("axioms", []),
1774
+ "report_sha256": report_sha,
1775
+ "job_id": ev.job_id,
1776
+ "checker": checker,
1777
+ "generated_at": fields.get("generated-at") or core.now_iso(),
1778
+ }
1779
+ if seal:
1780
+ receipt.update(seal) # additive keys: validate_receipt and gate ignore keys beyond RECEIPT_FIELDS
1781
+ # Additive and informational only (field report): whether the verify log's own `commit:` line names --commit.
1782
+ # Gate never reads it: a receipt claiming `true` passes or fails gate exactly as one without the key.
1783
+ receipt["log_commit_bound"] = log_commit_bound
1784
+ if container is not None: # additive (#236): only when the job ran in a container; gate ignores it
1785
+ receipt["container"] = container
1786
+ if claim_axioms is not None: # additive (AX1): per-claim axioms read from the built environment
1787
+ receipt["claim_axioms"] = claim_axioms
1788
+ receipt.update(ev.receipt_extra)
1789
+ files = [] # (path, bytes) of the executor's evidence files
1790
+ sealed_files = [] # {role, path, sha256, receipt_key} of each evidence file, for --json
1791
+ evidence_lines = []
1792
+ for suffix, data, key, line in ev.evidence_files:
1793
+ path = out.with_name(f"{name12}-{slug}-{suffix}")
1794
+ digest = hashlib.sha256(data).hexdigest()
1795
+ receipt[key] = digest # additive, like the seal keys
1796
+ files.append((path, data))
1797
+ sealed_files.append({"role": suffix, "path": str(path), "sha256": digest, "receipt_key": key})
1798
+ evidence_lines.append(line.format(name=path.name, sha=digest))
1799
+ if ev.sacct_seal is not None: # additive (--seal-sacct): the job's sacct record, sealed like a comparator's
1800
+ sacct_path = out.with_name(f"{name12}-{slug}-{SLURM_SACCT_SUFFIX}")
1801
+ if not fields.get("generated-at"):
1802
+ refusals.append("--seal-sacct: the verify log has no `generated-at:` line (stamped inside the job, "
1803
+ "as the --template prints it); the sacct window must contain the run, and a receipt "
1804
+ "stamped at writing time lies after the job")
1805
+ else:
1806
+ try:
1807
+ sblock, sbody = ev.sacct_seal(receipt, f".lean-receipts/{sacct_path.name}")
1808
+ except core.Fail as e:
1809
+ refusals.append(str(e))
1810
+ else:
1811
+ receipt["slurm_sacct"] = sblock
1812
+ files.append((sacct_path, sbody))
1813
+ sealed_files.append({"role": SLURM_SACCT_SUFFIX, "path": str(sacct_path),
1814
+ "sha256": sblock["sha256"], "receipt_key": "slurm_sacct.sha256"})
1815
+ checks.append(f"✓ sacct seal: job {sblock['job']} COMPLETED, exit 0:0, {sblock['start']} .. "
1816
+ f"{sblock['end']} contains generated_at (user {sblock['checks']['user']}, node "
1817
+ f"{sblock['checks']['node']}; {sblock['source']})")
1818
+ evidence_lines.append(
1819
+ f"- Seal: sacct record `{sacct_path.name}`, SHA-256 `{sblock['sha256']}` (= "
1820
+ f"`slurm_sacct.sha256`, {SACCT_SEAL_SCHEMA}): job `{sblock['job']}` COMPLETED, exit `0:0`, "
1821
+ f"{sblock['start']} .. {sblock['end']} (UTC) containing `generated_at`; user "
1822
+ f"{sblock['checks']['user']}, node {sblock['checks']['node']}; from {sblock['source']}.")
1823
+ gz_out = log_out.with_name(log_out.name + gate_mod.REPORT_GZ_SUFFIX)
1824
+ compress = bool(getattr(args, "compress_log", False))
1825
+ gz_bytes = gz_sha = None
1826
+ if compress: # report_sha256 stays the uncompressed log's hash; the .gz is bound by its own additive key
1827
+ gz_bytes = gate_mod.gzip_deterministic(log_bytes)
1828
+ gz_sha = hashlib.sha256(gz_bytes).hexdigest()
1829
+ receipt["report_compressed"] = {"format": "gzip", "sha256": gz_sha, "bytes": len(log_bytes)}
1830
+ evidence_lines.append(f"- Stored compressed: `{gz_out.name}` (deterministic gzip, SHA-256 `{gz_sha}` = "
1831
+ f"`report_compressed.sha256`; {len(log_bytes)} bytes uncompressed). Restore: "
1832
+ f"`gzip -dc {gz_out.name} > {log_out.name}`, then `sha256sum {log_out.name}` "
1833
+ f"prints `report_sha256`.")
1834
+ if not fields.get("generated-at"):
1835
+ kept = _kept_fallback_time(out, receipt)
1836
+ if kept and kept != receipt["generated_at"]:
1837
+ receipt["generated_at"] = kept
1838
+ checks.append(f"· {out.name} already present, identical but for its clock time; kept "
1839
+ f"generated_at {kept}")
1840
+ receipt_bytes = (json.dumps(receipt, indent=2) + "\n").encode("utf-8")
1841
+ rel_r, rel_l = _shown(out, repo), _shown(log_out, repo)
1842
+ tar = f"; tar SHA-256 `{args.tar_sha256}`" if args.tar_sha256 else ""
1843
+ block = readme_block(commit=commit or name12, heading=args.readme_heading or ev.default_heading,
1844
+ executor_lines=ev.executor_lines(out.name, tar), receipt=receipt, log_name=log_out.name,
1845
+ raw_sha=raw_sha, n_diff=n_diff, redaction_note=ev.redaction_note,
1846
+ extra=args.readme_line or [], seal=seal, evidence_lines=evidence_lines,
1847
+ log_commit_bound=log_commit_bound)
1848
+
1849
+ sc = _scanner(repo)
1850
+ scanned = [("redacted verify log", redacted)]
1851
+ scanned += [(path.name, data.decode("utf-8", "replace")) for path, data in files]
1852
+ scanned += [("receipt JSON", receipt_bytes.decode()), ("README block", block)]
1853
+ for what, blob_text in scanned:
1854
+ fams = blocking_families(sc, blob_text)
1855
+ if fams:
1856
+ refusals.append(f"public-safety: a private string remains in the {what} ({', '.join(fams)}); "
1857
+ + (ev.redact_help if what != "README block"
1858
+ else "fix --readme-heading / --readme-line"))
1859
+ log_written = (gz_out, gz_bytes) if compress else (log_out, log_bytes)
1860
+ if not refusals:
1861
+ for path, data in (log_written, *files, (out, receipt_bytes)):
1862
+ why = _same_or_absent(path, data)
1863
+ if why:
1864
+ refusals.append(why)
1865
+ why = _other_form_problem(gz_out if not compress else log_out, log_bytes, report_sha)
1866
+ if why:
1867
+ refusals.append(why)
1868
+ readme = out.parent / "README.md"
1869
+ if not refusals and out.parent.is_symlink():
1870
+ refusals.append(f"{out.parent.name}/ is a symlink; nothing written")
1871
+ readme_old = None
1872
+ if not refusals and args.append_readme:
1873
+ if readme.is_symlink():
1874
+ refusals.append("README.md beside the receipt is a symlink; nothing written")
1875
+ elif readme.exists():
1876
+ try:
1877
+ readme_old = readme.read_bytes().decode("utf-8")
1878
+ except (OSError, UnicodeDecodeError) as e:
1879
+ refusals.append(f"README.md beside the receipt cannot be read as UTF-8 text ({e.__class__.__name__}"
1880
+ f"); fix or move it, or drop --append-readme; nothing written")
1881
+
1882
+ appended = False
1883
+ next_cmd = None
1884
+ if not refusals:
1885
+ checks.append(f"✓ public-safety: no blocking hit after {n_redacted} redaction(s)")
1886
+ out.parent.mkdir(parents=True, exist_ok=True)
1887
+ _write(*log_written)
1888
+ for path, data in files:
1889
+ _write(path, data)
1890
+ _write(out, receipt_bytes)
1891
+ if args.append_readme:
1892
+ old = readme_old if readme_old is not None else "# Receipts\n"
1893
+ if f"`{out.name}`" in old:
1894
+ checks.append(f"· README.md already lists {out.name}; not appended again")
1895
+ else:
1896
+ _write(readme, (old.rstrip() + "\n\n" + block).encode("utf-8"))
1897
+ appended = True
1898
+ next_cmd = f"lean-pkg gate NAME --check --receipt {rel_r}"
1899
+ if "slurm_sacct" in receipt:
1900
+ checks.append(f"· commit {_shown(sacct_path, repo)} with the receipt: gate checks the sealed sacct "
1901
+ f"record committed at HEAD")
1902
+
1903
+ if args.json_out:
1904
+ payload = {"ok": not refusals, "receipt": None if refusals else str(out),
1905
+ "log": None if refusals else str(log_written[0]),
1906
+ "report_sha256": None if refusals else report_sha, "raw_log_sha256": raw_sha,
1907
+ "job_id": ev.job_id, "seal": seal, "log_commit_bound": log_commit_bound,
1908
+ "report_compressed": receipt.get("report_compressed")}
1909
+ payload.update(ev.json_extra)
1910
+ if ev.sacct_seal is not None: # additive, only with --seal-sacct: the block written into the receipt
1911
+ payload["slurm_sacct"] = None if refusals else receipt.get("slurm_sacct")
1912
+ # The exact files this run wrote and bound, so a caller never guesses a sidecar by its name: the
1913
+ # receipt itself, the redacted log (report_sha256) and each evidence file with the receipt key that
1914
+ # holds its SHA-256. Empty on a refusal (nothing written).
1915
+ payload["sealed"] = [] if refusals else (
1916
+ [{"role": "receipt", "path": str(out), "sha256": hashlib.sha256(receipt_bytes).hexdigest(),
1917
+ "receipt_key": None},
1918
+ ({"role": "redacted-log.gz", "path": str(gz_out), "sha256": gz_sha,
1919
+ "receipt_key": "report_compressed.sha256", "uncompressed_sha256": report_sha} if compress else
1920
+ {"role": "redacted-log", "path": str(log_out), "sha256": report_sha, "receipt_key": "report_sha256"})]
1921
+ + sealed_files)
1922
+ payload.update({"redactions": n_redacted, "lines_redacted": n_diff, "checks": checks,
1923
+ "readme_block": None if refusals else block, "readme_appended": appended,
1924
+ "next": next_cmd, "refusals": refusals})
1925
+ core.print_json(payload)
1926
+ if log_commit_bound is False and not refusals:
1927
+ print(f"lean-pkg: WARN {NO_COMMIT_LINE}", file=sys.stderr)
1928
+ if not compress and not refusals and len(log_bytes) > LARGE_LOG_WARN_BYTES:
1929
+ print(f"lean-pkg: WARN the redacted log is {len(log_bytes) / (1 << 20):.1f} MiB, near or over GitHub's "
1930
+ f"100 MiB per-file limit; rerun with --compress-log to write it as deterministic gzip "
1931
+ f"(report_sha256 unchanged)", file=sys.stderr)
1932
+ if refusals:
1933
+ verdict = f"{ev.verb}: refused, {len(refusals)} problem(s); nothing written"
1934
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
1935
+ for r in refusals:
1936
+ print(f" ✗ {r}", file=sys.stderr)
1937
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
1938
+ return 1
1939
+ if not args.json_out:
1940
+ print(f"{ev.verb}: ok, job {ev.job_id} at commit {c12}; {n_redacted} redaction(s)")
1941
+ for c in checks:
1942
+ print(f" {c}")
1943
+ print(f" receipt {rel_r}")
1944
+ if compress:
1945
+ print(f" verify log {_shown(gz_out, repo)} (redacted, gzip SHA-256 {gz_sha}; report_sha256 "
1946
+ f"{report_sha} is the uncompressed log's)")
1947
+ else:
1948
+ print(f" verify log {rel_l} (redacted; report_sha256 {report_sha})")
1949
+ for path, _data in files:
1950
+ print(f" evidence {_shown(path, repo)}")
1951
+ if appended:
1952
+ print(f"README entry appended to {_shown(readme, repo)}:")
1953
+ else:
1954
+ print("README entry to add (or rerun with --append-readme):")
1955
+ print(block.rstrip("\n"))
1956
+ print(f"next: {next_cmd}")
1957
+ allowed = set(core.DEFAULT_AXIOMS)
1958
+ if set(receipt["axioms"]) - allowed:
1959
+ print(f"lean-pkg: WARN axioms outside the default allowed set: "
1960
+ f"{sorted(set(receipt['axioms']) - allowed)}; gate refuses them unless the package's "
1961
+ f"gate.axioms_allowed lists them", file=sys.stderr)
1962
+ if claim_axioms and claim_axioms["nonstandard"]:
1963
+ print(f"lean-pkg: WARN claim(s) use axioms outside the default allowed set: "
1964
+ f"{', '.join(e['decl'] for e in claim_axioms['nonstandard'][:10])}; gate refuses them unless the "
1965
+ f"package's gate.axioms_allowed lists them", file=sys.stderr)
1966
+ return 0
1967
+
1968
+
1969
+ def _job_files(args) -> dict:
1970
+ paths = {}
1971
+ for flag, value in (("--log", args.log), ("--stdout", args.stdout), ("--stderr", args.stderr)):
1972
+ if value is not None:
1973
+ p = pathlib.Path(value).expanduser()
1974
+ if not p.is_file():
1975
+ raise core.UsageError(f"{flag} {value}: no such file")
1976
+ paths[flag] = p
1977
+ return paths
1978
+
1979
+
1980
+ def artifacts_args(args, paths: dict) -> tuple[pathlib.Path, str] | None:
1981
+ """(DIR, manifest name) for --artifacts, or None; the usage errors (exit 2) of the flag pair."""
1982
+ name = getattr(args, "artifacts_manifest", None)
1983
+ root = getattr(args, "artifacts", None)
1984
+ if root is None:
1985
+ if name is not None:
1986
+ raise core.UsageError("--artifacts-manifest is only for --artifacts DIR")
1987
+ return None
1988
+ if "--stdout" not in paths:
1989
+ raise core.UsageError(f"--artifacts needs --stdout (the job's {ARTIFACTS_KEY} line is on its stdout, which "
1990
+ f"the stdout seal binds)")
1991
+ name = ARTIFACTS_MANIFEST if name is None else name
1992
+ if not name or "/" in name or name in (".", "..") or "\0" in name:
1993
+ raise core.UsageError(f"--artifacts-manifest {name!r}: a file name inside the --artifacts directory")
1994
+ path = pathlib.Path(root).expanduser()
1995
+ if not path.exists() and not path.is_symlink():
1996
+ raise core.UsageError(f"--artifacts {root}: no such directory")
1997
+ return path, name
1998
+
1999
+
2000
+ def _artifact_evidence(art, paths: dict, refusals: list[str], checks: list[str]) -> tuple[list, dict | None]:
2001
+ """(Evidence.evidence_files entries, JSON summary) of a --artifacts check (both empty without the flag)."""
2002
+ if art is None:
2003
+ return [], None
2004
+ out_text = paths["--stdout"].read_bytes().decode("utf-8", errors="replace")
2005
+ data, summary = check_artifacts(*art, out_text, refusals, checks)
2006
+ if data is None:
2007
+ return [], {"ok": False, "dir": str(art[0]), "manifest": art[1]}
2008
+ line = (f"- Artifacts: `{{name}}`, SHA-256 `{{sha}}` (= `{ARTIFACTS_RECEIPT_KEY}` = the job stdout's "
2009
+ f"{ARTIFACTS_KEY}); {summary['files']} file(s), {summary['bytes']} bytes rehashed from the collected "
2010
+ f"copy.")
2011
+ return ([(ARTIFACTS_MANIFEST, data, ARTIFACTS_RECEIPT_KEY, line)],
2012
+ {"ok": True, "dir": str(art[0]), **summary})
2013
+
2014
+
2015
+ def preflight(args) -> int:
2016
+ """`receipt slurm --check` (field report): every check on the job's files that needs neither sacct nor a
2017
+ finished long job, on the .log/.out/.err of a trial run; every problem is listed, nothing is written. The
2018
+ commit-side checks run only with --commit, the sacct check only with --sacct-file and --job."""
2019
+ if args.log is None:
2020
+ raise core.UsageError("--check needs --log PATH (the job's raw verify log)")
2021
+ job = (args.job or "").strip().removeprefix("slurm-") or None
2022
+ repo = repo_dir(args)
2023
+ paths = _job_files(args)
2024
+ art = artifacts_args(args, paths)
2025
+ extra = common_usage(args)
2026
+ problems: list[str] = []
2027
+ checks: list[str] = []
2028
+ if args.sacct_file is not None and job:
2029
+ text, _why = sacct_text(job, args.sacct_file)
2030
+ _s, why = check_job(job, text)
2031
+ if why:
2032
+ problems.append(why)
2033
+ else:
2034
+ checks.append(f"✓ sacct: job {job} COMPLETED, exit 0:0 (--sacct-file)")
2035
+ else:
2036
+ checks.append("· sacct: not checked in preflight (the receipt needs the main job line COMPLETED, exit "
2037
+ "0:0; give --sacct-file F --job J to check a saved copy)")
2038
+ commit = toolchain = manifest = None
2039
+ if args.commit_sha is None:
2040
+ checks.append("· commit: not checked (no --commit): the manifest hashes against lake-manifest.json, "
2041
+ "and lean-toolchain:, mathlib-rev:, commit: against the commit")
2042
+ else:
2043
+ commit = resolve_commit(repo, args.commit_sha)
2044
+ if commit is None:
2045
+ problems.append(f"--commit {args.commit_sha}: not a commit in the --repo checkout "
2046
+ f"(default the current directory)")
2047
+ else:
2048
+ toolchain, manifest = commit_package_files(repo, commit, problems)
2049
+ raw = paths["--log"].read_bytes()
2050
+ check_seal(paths, raw, manifest, commit[:12] if commit else None, problems, checks)
2051
+ raw_text = raw.decode("utf-8", errors="replace")
2052
+ redacted, _n = redact(raw_text, extra)
2053
+ fields, found = parse_raw_log(raw_text, redacted)
2054
+ problems += found
2055
+ lake_cache_check(repo, commit, raw_text, problems, checks)
2056
+
2057
+ def log_job_id(value: str) -> str | None:
2058
+ if job and value.removeprefix("slurm-") != job:
2059
+ return f"verify log: `job-id:` {value!r} is not --job {job!r}"
2060
+ return None
2061
+
2062
+ check_fields(fields, commit=commit, toolchain=toolchain, manifest=manifest, checker_flag=args.checker,
2063
+ check_log_job_id=log_job_id, refusals=problems)
2064
+ log_commit_bound = None # null: no resolved --commit to compare the log's `commit:` line with
2065
+ if commit is not None:
2066
+ log_commit_bound = commit_line_binding(fields, commit, "--stdout" in paths, problems, checks)
2067
+ why = evidence_symlink_problem(repo, commit)
2068
+ if why:
2069
+ problems.append(why)
2070
+ elif "commit" not in fields and "--stdout" not in paths:
2071
+ problems.append("verify log: no `commit:` line; with the in-log fallback seal (no --stdout) the receipt "
2072
+ "is refused (print `commit: <sha>` in the log, or pass --stdout)")
2073
+ container_evidence(fields, paths, problems, checks)
2074
+ claim_axioms_evidence(repo, commit, raw_text, problems, checks)
2075
+ hypotheses_evidence(repo, commit, raw_text, redacted, problems, checks)
2076
+ fams = blocking_families(_scanner(repo), redacted)
2077
+ if fams:
2078
+ problems.append(f"public-safety: a private string remains in the redacted verify log ({', '.join(fams)}); "
2079
+ f"add a --redact REGEX for it")
2080
+ _files, art_summary = _artifact_evidence(art, paths, problems, checks)
2081
+ ok = not problems
2082
+ if args.json_out:
2083
+ payload = {"ok": ok, "check": True, "written": [], "raw_log_sha256": hashlib.sha256(raw).hexdigest(),
2084
+ "log_commit_bound": log_commit_bound, "checks": checks, "problems": problems}
2085
+ if art is not None: # additive, only with --artifacts
2086
+ payload["artifacts"] = art_summary
2087
+ core.print_json(payload)
2088
+ else:
2089
+ print(f"receipt slurm --check: {'ok' if ok else f'{len(problems)} problem(s)'}; nothing written")
2090
+ for c in checks:
2091
+ print(f" {c}")
2092
+ for pr in problems:
2093
+ print(f" ✗ {pr}")
2094
+ return 0 if ok else 1
2095
+
2096
+
2097
+ def contracts_preflight(args) -> int:
2098
+ """`receipt slurm --contracts-preflight [--repo DIR]` (#409): before submitting the job, the
2099
+ contracts-only diagnostic of every comparator configuration of the checkout (default the current directory),
2100
+ whose modules must be built here. Writes nothing; exit 0 when every configuration matches, else 1."""
2101
+ from . import comparator_contracts as cc
2102
+ extra = [f for f, v in (("--job", args.job), ("--log", args.log), ("--receipt-commit", args.commit_sha)) if v]
2103
+ if extra:
2104
+ raise core.UsageError(f"{', '.join(extra)}: not with --contracts-preflight (it runs before the job exists)")
2105
+ repo = pathlib.Path(args.repo).resolve() if args.repo else pathlib.Path.cwd()
2106
+ pre = cc.preflight(repo)
2107
+ if getattr(args, "json_out", False):
2108
+ core.print_json({"ok": pre["ok"], "contracts_preflight": True, "written": [], "checks": pre["checks"],
2109
+ "refusals": pre["refusals"], "report": pre["report"]})
2110
+ else:
2111
+ for line in pre["checks"]:
2112
+ print(f"lean-pkg: receipt slurm: {line}")
2113
+ for line in pre["refusals"]:
2114
+ print(f"lean-pkg: receipt slurm: {line}", file=sys.stderr)
2115
+ verdict = "PASS" if pre["ok"] else "REFUSED"
2116
+ print(f"lean-pkg: receipt slurm: contracts preflight {verdict} (never acceptance; nothing written)")
2117
+ return 0 if pre["ok"] else 1
2118
+
2119
+
2120
+ def cmd_receipt_slurm(args) -> int:
2121
+ modes = [f for f, v in (("--template", args.template), ("--check", args.check),
2122
+ ("--preflight-deps", args.preflight_deps),
2123
+ ("--contracts-preflight", getattr(args, "contracts_preflight", False))) if v]
2124
+ if len(modes) > 1:
2125
+ raise core.UsageError(f"{' and '.join(modes)} do not combine")
2126
+ seal = bool(getattr(args, "seal_sacct", False))
2127
+ if seal and modes:
2128
+ raise core.UsageError(f"--seal-sacct seals the receipt this command writes; not with {modes[0]}")
2129
+ if getattr(args, "sacct_user", None) is not None and not seal:
2130
+ raise core.UsageError("--user goes with --seal-sacct (the account the job must have run under)")
2131
+ if not args.preflight_deps:
2132
+ given = [f for f, v in (("--deps-tar", args.deps_tar), ("--deps-dir", args.deps_dir),
2133
+ ("--entries", args.entries), ("--fill-plan", args.fill_plan),
2134
+ ("--plan-out", args.plan_out), ("--base-list", args.base_list)) if v]
2135
+ if given:
2136
+ raise core.UsageError(f"{', '.join(given)}: only with --preflight-deps")
2137
+ if not args.fill_plan:
2138
+ given = [f for f, v in (("--plan-out", args.plan_out), ("--base-list", args.base_list)) if v]
2139
+ if given:
2140
+ raise core.UsageError(f"{', '.join(given)}: only with --fill-plan DONOR")
2141
+ if args.template:
2142
+ if getattr(args, "json_out", False): # --json: the script inside the one JSON document on stdout
2143
+ core.print_json({"ok": True, "template": SBATCH_TEMPLATE})
2144
+ else:
2145
+ sys.stdout.write(SBATCH_TEMPLATE)
2146
+ return 0
2147
+ if args.check:
2148
+ return preflight(args)
2149
+ if args.preflight_deps:
2150
+ from . import deps_closure
2151
+ return deps_closure.cmd(args)
2152
+ if getattr(args, "contracts_preflight", False):
2153
+ return contracts_preflight(args)
2154
+ missing = [f for f, v in (("--job", args.job), ("--log", args.log), ("--receipt-commit", args.commit_sha)) if v is None]
2155
+ if missing:
2156
+ raise core.UsageError(f"receipt slurm needs {', '.join(missing)} (or --template, or --check on a job's files)")
2157
+ job = (args.job or "").strip().removeprefix("slurm-")
2158
+ if not job:
2159
+ raise core.UsageError("--job must not be empty")
2160
+ job_id = f"slurm-{job}"
2161
+ gate_mod.receipt_job_slug(job_id)
2162
+ repo = repo_dir(args)
2163
+ paths = _job_files(args)
2164
+ art = artifacts_args(args, paths)
2165
+ extra = common_usage(args)
2166
+ if seal:
2167
+ seal_usage(args, job, repo)
2168
+
2169
+ refusals: list[str] = []
2170
+ checks: list[str] = []
2171
+ if seal and args.sacct_file is None: # the seal needs zoned Start/End: sacct with its header and time format
2172
+ text, why = sacct_seal_query(job, SLURM_SEAL_QUERY)
2173
+ else:
2174
+ text, why = sacct_text(job, args.sacct_file)
2175
+ sacct = None
2176
+ if why:
2177
+ refusals.append(why)
2178
+ else:
2179
+ sacct, why = check_job(job, text)
2180
+ if why:
2181
+ refusals.append(why)
2182
+ else:
2183
+ checks.append(f"✓ sacct: job {job} COMPLETED, exit 0:0")
2184
+ s = sacct or {}
2185
+
2186
+ def lines(receipt_name: str, tar: str) -> list[str]:
2187
+ return [f"- Receipt: `{receipt_name}`. Slurm job `{job}`: COMPLETED, exit `0:0`,",
2188
+ f" elapsed {s.get('elapsed') or 'unknown'}, TotalCPU {s.get('total_cpu') or 'unknown'}{tar}."]
2189
+
2190
+ def log_job_id(value: str) -> str | None:
2191
+ if value.removeprefix("slurm-") != job:
2192
+ return f"verify log: `job-id:` {value!r} is not --job {job!r}"
2193
+ return None
2194
+
2195
+ evidence_files, art_summary = _artifact_evidence(art, paths, refusals, checks)
2196
+ json_extra = {"sacct": sacct}
2197
+ if seal and sacct is not None: # user and node names are checked, never printed or written
2198
+ json_extra["sacct"] = {k: v for k, v in sacct.items() if k not in ("user", "nodelist")}
2199
+ if art is not None: # additive, only with --artifacts: without it nothing changes
2200
+ json_extra["artifacts"] = art_summary
2201
+ sacct_seal = None
2202
+ if seal and sacct is not None:
2203
+ live = args.sacct_file is None
2204
+
2205
+ def sacct_seal(receipt: dict, rel: str) -> tuple[dict, bytes]:
2206
+ return sacct_seal_record(job, receipt, sacct, live=live, user=args.sacct_user, rel=rel,
2207
+ kind="lower-tier")
2208
+ # The lean-pkg that writes this receipt (the collector, not the one that ran inside the job), with the
2209
+ # shape `receipt systemd --run` seals; additive, gate and receipt check ignore it (producer.py)
2210
+ from . import producer as pr
2211
+ written_by = pr.receipt_producer(pr.fingerprint())
2212
+ json_extra["producer"] = written_by
2213
+ ev = Evidence(verb="receipt slurm", job_id=job_id, refusals=refusals, checks=checks, executor_lines=lines,
2214
+ default_heading=f"lower-tier receipt, Slurm job {job}", check_log_job_id=log_job_id,
2215
+ json_extra=json_extra, evidence_files=evidence_files, sacct_seal=sacct_seal,
2216
+ receipt_extra={"producer": written_by})
2217
+ return produce(args, ev, repo, paths, extra)
2218
+
2219
+
2220
+ def seal_usage(args, job: str, repo: pathlib.Path) -> None:
2221
+ """The usage checks of `receipt slurm --seal-sacct` (exit 2): a job number sacct can be asked about, and the
2222
+ receipt in <repo>/.lean-receipts/, where slurm_sacct.file names the record beside it."""
2223
+ if not re.fullmatch(r"\d+(?:_\d+)?", job):
2224
+ raise core.UsageError(f"--seal-sacct needs a Slurm job number (J or J_T), got --job {args.job!r}")
2225
+ if args.out:
2226
+ want = (repo / ".lean-receipts").resolve()
2227
+ if pathlib.Path(args.out).expanduser().resolve().parent != want:
2228
+ raise core.UsageError("--seal-sacct writes the record beside the receipt under <repo>/.lean-receipts/ "
2229
+ "(slurm_sacct.file names it there); --out must name a file in that directory")
2230
+
2231
+
2232
+ def add_common_flags(s, kind: str, name_hint: str) -> None:
2233
+ """The flags every `receipt` form shares, after its executor's own."""
2234
+ s.add_argument("--checker", default=None, metavar="TEXT",
2235
+ help="the exact checker command or mode (default: the log's `checker:` line)")
2236
+ s.add_argument("--repo", default=None, metavar="DIR", help="the package checkout (default: the current directory)")
2237
+ s.add_argument("--out", default=None, metavar="PATH",
2238
+ help=f"receipt path (default <repo>/.lean-receipts/<commit12>-{name_hint}.json); the redacted log "
2239
+ f"is written beside it as <commit12>-{name_hint}-verify.redacted.log")
2240
+ s.add_argument("--compress-log", action="store_true",
2241
+ help="write the redacted log as deterministic gzip <...>-verify.redacted.log.gz (level 9, mtime 0, "
2242
+ "no file name) instead of the plain .log; report_sha256 stays the SHA-256 of the "
2243
+ "uncompressed log and the receipt gains report_compressed {format: gzip, sha256 of the .gz, "
2244
+ "bytes = decoded length, not the .gz size}; gate decompresses (bounded) and checks report_sha256. Restore: "
2245
+ "gzip -dc X.log.gz > X.log. Without it, a log over 90 MiB prints a WARN naming this flag")
2246
+ s.add_argument("--append-readme", action="store_true",
2247
+ help="append the entry block to README.md beside the receipt (created if absent; an entry "
2248
+ "already naming the receipt is not repeated)")
2249
+ s.add_argument("--readme-heading", default=None, metavar="TEXT",
2250
+ help=f"the entry heading after the short commit (default: lower-tier receipt, {kind})")
2251
+ s.add_argument("--readme-line", action="append", default=[], metavar="TEXT",
2252
+ help="an extra line at the end of the entry block (repeatable)")
2253
+ s.add_argument("--tar-sha256", default=None, metavar="HEX",
2254
+ help="the frozen source tarball's SHA-256, named in the entry block")
2255
+ s.add_argument("--json", dest="json_out", action="store_true", default=argparse.SUPPRESS,
2256
+ help="machine-readable JSON on stdout")
2257
+
2258
+
2259
+ def add_parsers(sub, add_json) -> None:
2260
+ del add_json # its --commit flag (committed mode) would collide with `receipt slurm --commit SHA`
2261
+ from . import receipt_check, receipt_ci, receipt_systemd
2262
+ r = sub.add_parser("receipt", help="produce receipts (slurm, systemd, ci: the lower tier; comparator: the "
2263
+ "comparator run; each writes files in the package checkout, never the "
2264
+ "registry); check a published package's receipts from git alone (check)")
2265
+ rsub = r.add_subparsers(dest="receipt_cmd", metavar="{slurm,systemd,ci,comparator,check}", required=True)
2266
+ s = rsub.add_parser("slurm", help="a lower-tier receipt from a finished Slurm job, its verify log and "
2267
+ "its stdout seal (--template: an sbatch wrapper that meets it; --check: "
2268
+ "preflight the job's files)")
2269
+ s.add_argument("--job", default=None, metavar="J",
2270
+ help="the Slurm job id (job_id becomes slurm-J); required unless --template or --check")
2271
+ s.add_argument("--log", default=None, metavar="PATH",
2272
+ help="the job's raw verify log (required unless --template); when it has no `checker:` line, "
2273
+ "--checker TEXT is required")
2274
+ s.add_argument("--receipt-commit", dest="commit_sha", default=None, metavar="SHA",
2275
+ help="the verified commit; must exist in --repo; required unless --template or --check")
2276
+ s.add_argument("--template", action="store_true",
2277
+ help="print a minimal sbatch wrapper whose .out/.err/log meet every check below (placeholders "
2278
+ "for the package's own commands); needs no other flag")
2279
+ s.add_argument("--check", action="store_true",
2280
+ help="preflight the files of a finished (trial) job: every seal, stderr and log-line check, "
2281
+ "each problem named; no sacct (unless --sacct-file), commit checks only with --receipt-commit; "
2282
+ "writes nothing, exit 0/1")
2283
+ s.add_argument("--contracts-preflight", action="store_true",
2284
+ help="before submitting: run the contracts-only diagnostic (`comparator check --contracts-only`) "
2285
+ "on every comparator configuration of --repo (default the current directory), whose "
2286
+ "modules must be built here; a configuration that differs, one whose modules are not "
2287
+ "built, or a diagnostic that cannot run refuses; writes nothing, exit 0/1 "
2288
+ "(docs/comparator.md, Before receipt work)")
2289
+ s.add_argument("--preflight-deps", action="store_true",
2290
+ help="before submitting: check that the staged dependency cache (--deps-tar or --deps-dir) "
2291
+ "holds, at the lake-manifest.json pins committed at --commit (default HEAD), the built "
2292
+ ".olean and .ilean of every external module in the import closure of the entry files "
2293
+ "the verifier elaborates (--entries); reads the committed tree, builds and writes "
2294
+ "nothing, exit 0/1")
2295
+ s.add_argument("--deps-tar", default=None, metavar="PATH",
2296
+ help="with --preflight-deps: the DEPS_TAR tarball the job will restore (gzip, bzip2, xz or "
2297
+ "plain; read in one pass, never extracted)")
2298
+ s.add_argument("--deps-dir", default=None, metavar="DIR",
2299
+ help="with --preflight-deps: a directory holding .lake/packages, instead of --deps-tar")
2300
+ s.add_argument("--entries", action="append", default=[], metavar="GLOB",
2301
+ help="with --preflight-deps: a glob (relative to the package directory; ** = any directories) "
2302
+ "of the .lean files the verifier elaborates, repeatable; replaces the default "
2303
+ "Verify/**/*.lean, Audit/**/*.lean, OwnedAudit/**/*.lean, **/AxiomCheck*.lean, "
2304
+ "**/TypeCheck*.lean, **/Examples*.lean, **/OwnedAudit*.lean")
2305
+ s.add_argument("--fill-plan", default=None, metavar="DONOR",
2306
+ help="with --preflight-deps: plan filling the missing modules from DONOR, another directory "
2307
+ "holding .lake/packages built from the same pins (docs/receipts.md, \"Filling missing "
2308
+ "dependency artifacts from a pinned donor\", steps 1-4), read-only: every missing module "
2309
+ "(no 500 cap); refuses (exit 1, each refusal with its own code) unless DONOR/lean-toolchain "
2310
+ "is the commit's byte for byte, every manifest package is at its rev, the checkouts have no "
2311
+ "source edits (git status), each candidate .olean's first 80 bytes equal the base's, the "
2312
+ "donor holds every missing module's .olean and .ilean, and no addition is a base member, "
2313
+ "under one, under the package's own .lake/build or in its root namespaces; lists every file "
2314
+ "the donor has under each module's path (all artifact families) with size and sha256. It "
2315
+ "writes no archive: write it yourself, then rerun --preflight-deps on it")
2316
+ s.add_argument("--plan-out", default=None, metavar="FILE",
2317
+ help="with --fill-plan, only when the plan is ok: write FILE (the additions, one path relative "
2318
+ "to the directory holding .lake per line, for tar -T) and FILE.provenance.json (commit, "
2319
+ "toolchain, manifest revs, donor identity, file hashes, created_utc: collector "
2320
+ "provenance, never a job seal); an existing file is never overwritten")
2321
+ s.add_argument("--base-list", default=None, metavar="FILE",
2322
+ help="with --fill-plan: a member listing of the base archive (tar -tf output), added to the "
2323
+ "names no addition may replace")
2324
+ s.add_argument("--stdout", default=None, metavar="PATH",
2325
+ help=f"the job's stdout (.out): {SHA_KEY} = sha256(raw log), {PRE_KEY} = {POST_KEY} = "
2326
+ "sha256(lake-manifest.json at the commit); without it the log must carry its own seal")
2327
+ s.add_argument("--stderr", default=None, metavar="PATH", help="the job's stderr (.err); must be empty")
2328
+ s.add_argument("--redact", action="append", default=[], metavar="REGEX",
2329
+ help=f"also replace matches with {REDACT_TOKEN} (repeatable); the built-in prefixes are always "
2330
+ f"redacted to {USER_TOKEN} instead (/tmp/{USER_TOKEN}-job, /scratch/{USER_TOKEN}/)")
2331
+ s.add_argument("--sacct-file", default=None, metavar="F",
2332
+ help=f"saved output of `sacct -j J --format={SACCT_FORMAT} -P -n` (a host without Slurm); "
2333
+ f"with --seal-sacct: of `SLURM_TIME_FORMAT=%%Y-%%m-%%dT%%H:%%M:%%S%%z sacct -j J "
2334
+ f"--format={SLURM_SEAL_QUERY} -P` (with its header line)")
2335
+ s.add_argument("--seal-sacct", action="store_true",
2336
+ help="seal the job's sacct record into the receipt, as `receipt comparator --seal-sacct` does: "
2337
+ "the main line must also show Start..End (with a zone) containing the log's generated-at: "
2338
+ "line, the account (this one with live sacct, or --user); writes <commit12>-slurm-<J>-"
2339
+ "sacct.txt beside the receipt (JobID|State|ExitCode|Start|End|Elapsed, UTC; no user or "
2340
+ "node names) and the additive slurm_sacct block (slurm-sacct-seal/1) with its sha256; gate "
2341
+ "then refuses the receipt unless that record is committed at HEAD and still hashes and "
2342
+ "parses to the block. Live sacct runs the seal query; on a host without Slurm pass "
2343
+ "--sacct-file")
2344
+ s.add_argument("--user", dest="sacct_user", default=None, metavar="NAME",
2345
+ help="--seal-sacct: the account the job must have run under (default with live sacct: this "
2346
+ "one; with --sacct-file: not checked unless given); compared, never written")
2347
+ s.add_argument("--artifacts", default=None, metavar="DIR",
2348
+ help=f"the collected copy of the job's sealed artifact directory (the template's ARTIFACTS_DIR): "
2349
+ f"the manifest's sha256 must be the --stdout {ARTIFACTS_KEY} line and every file under DIR "
2350
+ f"is rehashed against it (missing, extra, changed files, symlinks, special files, "
2351
+ f"path traversal and duplicate entries refuse); the receipt gains {ARTIFACTS_RECEIPT_KEY} "
2352
+ f"and the manifest is written beside it. Needs --stdout")
2353
+ s.add_argument("--artifacts-manifest", default=None, metavar="NAME",
2354
+ help=f"the manifest's file name inside --artifacts DIR (default {ARTIFACTS_MANIFEST})")
2355
+ add_common_flags(s, "Slurm job J", "slurm-<J>")
2356
+ s.set_defaults(fn=cmd_receipt_slurm)
2357
+ receipt_systemd.add_parser(rsub)
2358
+ receipt_ci.add_parser(rsub)
2359
+ from . import comparator_receipt
2360
+ s = rsub.add_parser("comparator", help="run the comparator on a Lake project and write the comparator receipt "
2361
+ "(the `comparator-receipt` program: the same code and flags)",
2362
+ description="Run comparator-check.sh and write a comparator receipt. The same code and flags "
2363
+ "as the `comparator-receipt` program, which stays.")
2364
+ comparator_receipt.add_arguments(s)
2365
+ s.set_defaults(fn=cmd_receipt_comparator)
2366
+ receipt_check.add_parser(rsub)
2367
+
2368
+
2369
+ def cmd_receipt_comparator(args) -> int:
2370
+ """`receipt comparator ...`: comparator_receipt.run_main on the parsed flags; the resume command it prints
2371
+ repeats this command's own flags (the argv after `receipt comparator`)."""
2372
+ from . import comparator_receipt
2373
+ argv = list(getattr(args, "command_argv", None) or [])
2374
+ at = next((i for i in range(len(argv) - 1) if argv[i:i + 2] == ["receipt", "comparator"]), None)
2375
+ tail = argv[at + 2:] if at is not None else []
2376
+ if getattr(args, "json_out", False) and not args.json:
2377
+ # the global `lean-pkg --json receipt comparator ...` means the runner's own --json: JSON for the modes
2378
+ # that print it, the runner's refusal for the others; never the text output on stdout
2379
+ if not (args.estimate or args.verify_oleans is not None or args.attempts is not None
2380
+ or args.seal_sacct is not None):
2381
+ raise core.UsageError("receipt comparator: --json goes with --estimate, --verify-oleans, --attempts "
2382
+ "or --seal-sacct; a run or --prepare prints text (its JSON record is "
2383
+ "comparator-stages/stages.json and the receipt)")
2384
+ args.json = True
2385
+ return comparator_receipt.run_main(args, tail, prog="lean-pkg receipt comparator")