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
@@ -0,0 +1,890 @@
1
+ # lean-pkg receipt systemd -- a lower-tier receipt from a finished systemd --user service unit
2
+ """`lean-pkg receipt systemd --unit U --log PATH --commit SHA [--properties-file F | --run [caps] -- CMD ...]
3
+ [--stdout PATH] [--stderr PATH] [--checker TEXT] [--repo DIR] [--redact REGEX ...] [--out PATH]
4
+ [--append-readme ...] [--json]` (alias `receipt local`): the local-executor counterpart of `receipt slurm`. A
5
+ verify script run in a capped `systemd-run --user` service unit becomes a lower-tier receipt in exactly the shape
6
+ `gate --receipt` validates, through the same seal, field, redaction and public-safety pipeline
7
+ (`receipt.produce`). It never reads or writes a registry.
8
+
9
+ Where the unit's terminal state comes from (one of three, like sacct / --sacct-file):
10
+
11
+ - `--run -- CMD ...`: lean-pkg starts CMD itself as the transient unit U with
12
+ `systemd-run --user --unit=U -p RemainAfterExit=yes -p WorkingDirectory=<repo> -p OOMPolicy=stop
13
+ -p MemoryMax=.. -p MemorySwapMax=.. -p CPUQuota=.. -p RuntimeMaxSec=..` (bounded by default), the unit's
14
+ stdout/stderr going to --stdout/--stderr (truncate:). RemainAfterExit keeps the finished unit loaded, so
15
+ nothing is collected before lean-pkg has read it: it polls `systemctl --user show U` until the unit is
16
+ terminal, captures UNIT_PROPS (plus `Hostname=` of this system) to --properties-out (default
17
+ `<log>.unit.properties`, written even when the receipt is later refused), and only then stops and
18
+ resets the unit. `--wait --collect` is not used: with --collect the unit and its properties vanish the moment
19
+ it finishes. The checkout must be at --commit with no tracked change and no untracked file under the
20
+ package directory before the run, and still be after it (untracked: what `git ls-files --others
21
+ --exclude-standard` lists, less .lean-receipts/, .lake/ and the run's own output files; files git ignores
22
+ are not checked, so they are not bound). Lake's local artifact cache is isolated for the unit: unless
23
+ --setenv names them, it gets LAKE_CACHE_DIR=<a fresh empty temporary directory, removed afterwards> and
24
+ LAKE_ARTIFACT_CACHE=false, so no module is restored (`Reused`) without its sorry warning (lake_hygiene).
25
+ An explicit --setenv LAKE_CACHE_DIR=DIR is used as given (it should be empty); LAKE_CACHE_DIR= (empty, which
26
+ does not disable the cache) and a LAKE_ARTIFACT_CACHE other than false/0 are usage errors. Interrupted while
27
+ waiting (SIGINT, SIGTERM, SIGHUP), the unit is left running and its temporary cache is kept while the unit may
28
+ still run; the recovery command (the same without --run) is printed, exit 128 + the signal (report_interrupt). A log showing a
29
+ root-package module Reused, Replayed or Unpacked is refused, so run from a clean build (`lake clean`).
30
+ The running lean-pkg itself is fingerprinted before the start (producer.py: its package files, dist-info,
31
+ interpreter and entry point), checked about every PRODUCER_CHECK_SECONDS while waiting (a WARN, once) and
32
+ again at collection: a change refuses, naming the files; an unchanged one is sealed as the additive receipt
33
+ key `producer` (gate ignores it) and a `- Producer:` README line.
34
+ `--require-tools A,B,...` (repeatable): before the unit is created, each project-declared executable must
35
+ resolve like bash `type -P` in the unit's PATH (this process's, or the last --setenv PATH=); the resolved
36
+ path, its real path and SHA-256 are printed to stderr and returned as --json `run_tools`; a missing one
37
+ refuses and nothing is run. It checks only the names given, not their libraries, modules or what they call.
38
+ - `--properties-file F`: the output of `systemctl --user show U -p <UNIT_PROPS>` saved before the unit was
39
+ collected, plus a `Hostname=` line naming the host it ran on (the host is part of job_id).
40
+ - neither: `systemctl --user show U` now, on this host (the unit must still be loaded, i.e. not --collect).
41
+
42
+ The exported property set is exactly UNIT_PROPS plus Hostname: Id, LoadState, ActiveState, SubState, Result,
43
+ InvocationID, ExecMainCode, ExecMainStatus, ExecMainStartTimestamp, ExecMainExitTimestamp,
44
+ ExecMainStartTimestampMonotonic, ExecMainExitTimestampMonotonic, NRestarts, MemoryPeak, CPUUsageNSec, MemoryMax,
45
+ MemorySwapMax, CPUQuotaPerSecUSec, RuntimeMaxUSec, OOMPolicy, RemainAfterExit. Only these keys are read and
46
+ copied into the evidence (any other line is ignored); REQUIRED must be present, the others are recorded when
47
+ present and never required. MainPID is not exported (0 once the main process has exited).
48
+
49
+ Unit checks (every failure listed; any one refuses, exit 1, nothing written): LoadState=loaded and Id = U; a
50
+ 32-hex InvocationID; terminal (ActiveState failed or inactive, or active with SubState exited); Result=success
51
+ (oom-kill, timeout, signal, exit-code ... are named); ExecMainCode exited (1) with ExecMainStatus 0 (killed or
52
+ dumped: the signal is named); NRestarts 0. Then everything `receipt slurm` checks: the stdout seal
53
+ (verify-log-sha256, pre = post manifest = committed lake-manifest.json; or the in-log fallback seal), an
54
+ optional stdout `invocation-id` line equal to InvocationID, empty --stderr, toolchain / mathlib / sorry /
55
+ axioms / checker / commit: lines, redaction and the public-safety scan.
56
+
57
+ Output: job_id `systemd-user:<U>:<InvocationID>@<host label>`, the host label being `h-` and the first 12 hex
58
+ digits of the SHA-256 of the lower-cased host name (`host_label`; the name itself is never written, and the
59
+ public-safety scan blocks this host's name); beside the receipt `<c12>-<slug>.json` and redacted log, the
60
+ normalised properties `<c12>-<slug>-unit.properties` (Hostname as its label; its SHA-256 in the additive receipt
61
+ key `unit_properties_sha256`, gate ignores it) and a README entry with Result, exit, runtime, CPU, memory peak and
62
+ the caps. Built-in redactions: the checkout's absolute path -> `<repo>`, $HOME -> `<HOME>`, `/run/user/N/` ->
63
+ `/run/user/<UID>/`, then every --redact.
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ import hashlib
69
+ import os
70
+ import pathlib
71
+ import re
72
+ import shlex
73
+ import shutil
74
+ import signal
75
+ import socket
76
+ import subprocess
77
+ import sys
78
+ import tempfile
79
+ import threading
80
+ import time
81
+
82
+ from . import gate as gate_mod
83
+ from . import core
84
+ from . import producer as pr
85
+ from . import receipt as rc
86
+
87
+ UNIT_PROPS = ("Id", "LoadState", "ActiveState", "SubState", "Result", "InvocationID", "ExecMainCode",
88
+ "ExecMainStatus", "ExecMainStartTimestamp", "ExecMainExitTimestamp",
89
+ "ExecMainStartTimestampMonotonic", "ExecMainExitTimestampMonotonic", "NRestarts", "MemoryPeak",
90
+ "CPUUsageNSec", "MemoryMax", "MemorySwapMax", "CPUQuotaPerSecUSec", "RuntimeMaxUSec", "OOMPolicy",
91
+ "RemainAfterExit")
92
+ # The exported set is exactly UNIT_PROPS (plus Hostname). REQUIRED must be present; the rest are recorded when
93
+ # present and never required, so a capture made with an older, shorter list (RemainAfterExit was added in
94
+ # 0.13.0) stays valid. MainPID is deliberately not exported: at terminal capture the main process is gone and
95
+ # systemd reports MainPID=0, and a PID is host-local and recycled; InvocationID identifies the run.
96
+ REQUIRED = ("Id", "LoadState", "ActiveState", "SubState", "Result", "InvocationID", "ExecMainCode",
97
+ "ExecMainStatus", "ExecMainExitTimestampMonotonic")
98
+ HOST_KEY = "Hostname"
99
+ STATE_PROPS = "LoadState,ActiveState,SubState,ExecMainExitTimestampMonotonic"
100
+ INVOCATION_KEY = "invocation-id"
101
+ # siginfo si_code values systemd reports as ExecMainCode (CLD_EXITED, CLD_KILLED, CLD_DUMPED)
102
+ CODES = {"1": "exited", "2": "killed", "3": "dumped", "exited": "exited", "killed": "killed", "dumped": "dumped"}
103
+ DEFAULT_CAPS = {"memory_max": "8G", "memory_swap_max": "0", "cpu_quota": "400%", "runtime_max": "4h"}
104
+ POLL_SECONDS = 2.0
105
+ # --run re-fingerprints the running lean-pkg this often while it waits (producer.py); and always at collection
106
+ PRODUCER_CHECK_SECONDS = 60.0
107
+ SYSTEMCTL_TIMEOUT = 60
108
+ _CAP_RE = re.compile(r"[0-9][0-9.]*[A-Za-z%]*")
109
+ _UNIT_RE = re.compile(r"[A-Za-z0-9:_.@\\-]+")
110
+ _HOST_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
111
+ _TOOL_RE = re.compile(r"[A-Za-z0-9_.+][A-Za-z0-9_.+-]*")
112
+ _OTHER_TYPE_RE = re.compile(r"\.(scope|socket|timer|target|mount|automount|path|slice|swap|device)$")
113
+
114
+
115
+ # --------------------------------------------------------------------------
116
+ # talking to the user manager
117
+
118
+ def user_env() -> dict:
119
+ """os.environ, plus the user bus when the caller's session lacks it (over ssh `systemctl --user` otherwise
120
+ fails with "Access denied" / "Failed to connect to bus")."""
121
+ env = dict(os.environ)
122
+ rt = env.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
123
+ if "XDG_RUNTIME_DIR" not in env and os.path.isdir(rt):
124
+ env["XDG_RUNTIME_DIR"] = rt
125
+ if "DBUS_SESSION_BUS_ADDRESS" not in env and os.path.exists(os.path.join(rt, "bus")):
126
+ env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={rt}/bus"
127
+ return env
128
+
129
+
130
+ def systemctl_show(exe: str, unit: str, props: str) -> tuple[str | None, str | None]:
131
+ """(`systemctl --user show UNIT -p PROPS` output, refusal)."""
132
+ try:
133
+ p = subprocess.run([exe, "--user", "show", unit, "-p", props], capture_output=True, text=True,
134
+ timeout=SYSTEMCTL_TIMEOUT, env=user_env())
135
+ except (OSError, subprocess.TimeoutExpired) as e:
136
+ return None, f"systemctl could not run: {e}"
137
+ if p.returncode != 0:
138
+ return None, (f"systemctl --user show exited {p.returncode}: {(p.stderr or p.stdout).strip() or 'no output'}"
139
+ " (over ssh the user bus needs XDG_RUNTIME_DIR=/run/user/$UID)")
140
+ return p.stdout, None
141
+
142
+
143
+ def _quiet(argv: list[str]) -> None:
144
+ try:
145
+ subprocess.run(argv, capture_output=True, text=True, timeout=SYSTEMCTL_TIMEOUT, env=user_env())
146
+ except (OSError, subprocess.TimeoutExpired):
147
+ pass
148
+
149
+
150
+ # --------------------------------------------------------------------------
151
+ # properties
152
+
153
+ def parse_properties(text: str) -> tuple[dict, list[str]]:
154
+ """(KEY -> value for the recognised UNIT_PROPS and Hostname lines, refusals). Other keys are ignored and
155
+ never copied into the evidence; a recognised key given twice refuses."""
156
+ seen: dict[str, list[str]] = {}
157
+ for line in text.splitlines():
158
+ key, eq, value = line.rstrip("\r").partition("=")
159
+ if eq and key in UNIT_PROPS + (HOST_KEY,):
160
+ seen.setdefault(key, []).append(value.strip())
161
+ props, refusals = {}, []
162
+ for key, values in seen.items():
163
+ if len(values) > 1:
164
+ refusals.append(f"unit properties: `{key}=` appears {len(values)} times; exactly one is allowed")
165
+ else:
166
+ props[key] = values[0]
167
+ return props, refusals
168
+
169
+
170
+ def host_label(name: str) -> str:
171
+ """The host as published (job_id, README, the properties evidence): `h-` and the first 12 hex digits of
172
+ the SHA-256 of the lower-cased host name. Distinct hosts stay distinct and anyone holding the name can
173
+ recompute the label, but the name itself (often a user or site identifier) is never written; the
174
+ receipt's public-safety scan blocks this host's name."""
175
+ return "h-" + hashlib.sha256(name.strip().lower().encode("utf-8")).hexdigest()[:12]
176
+
177
+
178
+ def normalised(props: dict) -> bytes:
179
+ """The evidence file: the recognised properties in UNIT_PROPS order, then Hostname as its label."""
180
+ keys = [k for k in UNIT_PROPS + (HOST_KEY,) if k in props]
181
+ return "".join(f"{k}={host_label(props[k]) if k == HOST_KEY else props[k]}\n" for k in keys).encode("utf-8")
182
+
183
+
184
+ def _int(value) -> int | None:
185
+ try:
186
+ return int(str(value).strip())
187
+ except (TypeError, ValueError):
188
+ return None
189
+
190
+
191
+ def check_unit(props: dict, unit: str) -> tuple[dict | None, list[str], list[str]]:
192
+ """(summary, refusals, checks): the unit is this one, terminal, and finished Result=success, exit 0."""
193
+ refusals: list[str] = []
194
+ ls = props.get("LoadState")
195
+ if ls is not None and ls != "loaded":
196
+ return None, [f"unit {unit}: not found (LoadState={ls}); a unit started with --collect is gone once it "
197
+ f"finishes: capture `systemctl --user show` before it is collected, or use --run"], []
198
+ missing = [k for k in REQUIRED if k not in props]
199
+ if missing:
200
+ return None, [f"unit properties: no {', '.join(k + '=' for k in missing)} line(s) (capture them with "
201
+ f"`systemctl --user show {unit} -p {','.join(UNIT_PROPS)}`)"], []
202
+ if props["Id"] != unit:
203
+ refusals.append(f"unit properties are for {props['Id']!r}, not --unit {unit}")
204
+ inv = props["InvocationID"].lower()
205
+ if not re.fullmatch(r"[0-9a-f]{32}", inv):
206
+ refusals.append(f"unit {unit}: InvocationID {props['InvocationID']!r} is not 32 hex characters")
207
+ host = props.get(HOST_KEY, "")
208
+ if not host:
209
+ refusals.append(f"unit properties: no `{HOST_KEY}=` line; append `{HOST_KEY}=$(hostname)` on the host "
210
+ f"the unit ran on (the host is part of job_id)")
211
+ elif not _HOST_RE.fullmatch(host):
212
+ refusals.append(f"unit properties: `{HOST_KEY}=` {host!r} is not a host name")
213
+ active, subst = props["ActiveState"], props["SubState"]
214
+ terminal = active in ("failed", "inactive") or (active == "active" and subst == "exited")
215
+ code = CODES.get(props["ExecMainCode"])
216
+ status = _int(props["ExecMainStatus"])
217
+ exited_at = _int(props["ExecMainExitTimestampMonotonic"]) or 0
218
+ if not terminal:
219
+ refusals.append(f"unit {unit} is not terminal (ActiveState={active}, SubState={subst}); a receipt needs "
220
+ f"the finished unit")
221
+ elif not exited_at or code is None:
222
+ refusals.append(f"unit {unit}: its main process never exited (ExecMainCode={props['ExecMainCode']}, "
223
+ f"ExecMainExitTimestampMonotonic={props['ExecMainExitTimestampMonotonic']})")
224
+ result = props["Result"]
225
+ if result != "success":
226
+ why = {"oom-kill": f"the OOM killer stopped it (MemoryMax={props.get('MemoryMax', 'unknown')})",
227
+ "timeout": f"the runtime cap stopped it (RuntimeMaxUSec={props.get('RuntimeMaxUSec', 'unknown')})",
228
+ "signal": "it was killed by a signal", "core-dump": "it dumped core",
229
+ "exit-code": "its main process exited non-zero"}.get(result, "not a clean finish")
230
+ refusals.append(f"unit {unit}: Result={result}: {why}; a receipt needs Result=success")
231
+ if code in ("killed", "dumped"):
232
+ refusals.append(f"unit {unit}: main process {code} by signal {props['ExecMainStatus']} "
233
+ f"(ExecMainCode={props['ExecMainCode']}); a receipt needs a clean exit 0")
234
+ elif code == "exited" and status != 0:
235
+ refusals.append(f"unit {unit}: main process exited {props['ExecMainStatus']}; a receipt needs exit 0")
236
+ restarts = _int(props.get("NRestarts", "0"))
237
+ if restarts:
238
+ refusals.append(f"unit {unit}: NRestarts={restarts}; a receipt binds one run of the unit")
239
+ start = _int(props.get("ExecMainStartTimestampMonotonic"))
240
+ summary = {"id": props["Id"], "invocation_id": inv, "host": None, "active_state": active,
241
+ "sub_state": subst, "result": result, "exec_main_code": code or props["ExecMainCode"],
242
+ "exec_main_status": props["ExecMainStatus"],
243
+ "runtime_usec": exited_at - start if start and exited_at >= start else None,
244
+ "cpu_usage_nsec": _int(props.get("CPUUsageNSec")), "memory_peak": _int(props.get("MemoryPeak")),
245
+ "memory_max": props.get("MemoryMax"), "memory_swap_max": props.get("MemorySwapMax"),
246
+ "cpu_quota_per_sec": props.get("CPUQuotaPerSecUSec"), "runtime_max": props.get("RuntimeMaxUSec"),
247
+ "remain_after_exit": props.get("RemainAfterExit")}
248
+ if host and _HOST_RE.fullmatch(host):
249
+ summary["host"] = host_label(host) # the name itself is never published
250
+ checks = []
251
+ if not refusals:
252
+ checks.append(f"✓ unit: {unit} invocation {inv[:12]}… on {summary['host']}: Result=success, exited 0")
253
+ checks.append(f"· resources: {resources(summary)}")
254
+ return summary, refusals, checks
255
+
256
+
257
+ def _bytes(v) -> str:
258
+ n = _int(v)
259
+ if n is None:
260
+ return "none" if str(v) == "infinity" else "unknown"
261
+ for unit, size in (("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)):
262
+ if n >= size:
263
+ return f"{n / size:.1f} {unit}"
264
+ return f"{n} B"
265
+
266
+
267
+ def _clock(seconds: float | None) -> str:
268
+ if seconds is None:
269
+ return "unknown"
270
+ h, rem = divmod(seconds, 3600)
271
+ m, s = divmod(rem, 60)
272
+ return f"{int(h):02d}:{int(m):02d}:{s:05.2f}"
273
+
274
+
275
+ def _quota(v) -> str:
276
+ """CPUQuotaPerSecUSec (`4s`, `500ms`, `1s 500ms`, `infinity`) as the CPUQuota percentage."""
277
+ if v is None:
278
+ return "unknown"
279
+ if v == "infinity":
280
+ return "none"
281
+ parts = re.findall(r"(\d+(?:\.\d+)?)(us|ms|s)\b", v)
282
+ if not parts or "".join(a + b for a, b in parts) != v.replace(" ", ""):
283
+ return v
284
+ total = sum(float(a) * {"us": 1e-6, "ms": 1e-3, "s": 1.0}[b] for a, b in parts)
285
+ return f"{total * 100:g}%"
286
+
287
+
288
+ def resources(s: dict) -> str:
289
+ rt = s["runtime_usec"] / 1e6 if s["runtime_usec"] is not None else None
290
+ cpu = s["cpu_usage_nsec"] / 1e9 if s["cpu_usage_nsec"] is not None else None
291
+ runtime_max = s["runtime_max"] or "unknown"
292
+ return (f"runtime {_clock(rt)}, CPU {_clock(cpu)}, memory peak {_bytes(s['memory_peak'])}; caps MemoryMax "
293
+ f"{_bytes(s['memory_max'])}, MemorySwapMax {_bytes(s['memory_swap_max'])}, CPUQuota "
294
+ f"{_quota(s['cpu_quota_per_sec'])}, RuntimeMax {'none' if runtime_max == 'infinity' else runtime_max}")
295
+
296
+
297
+ def redactions(repo: pathlib.Path) -> list[tuple[str, str]]:
298
+ """The checkout's absolute path (as given and resolved) -> <repo>, $HOME -> <HOME>, the runtime dir's uid:
299
+ a local run prints these, and a committed evidence file must not carry them."""
300
+ out, seen = [], set()
301
+ pairs = [(os.path.abspath(repo), "<repo>"), (str(repo.resolve()), "<repo>")]
302
+ home = os.environ.get("HOME")
303
+ if home:
304
+ pairs += [(os.path.abspath(home), "<HOME>"), (os.path.realpath(home), "<HOME>")]
305
+ for path, token in sorted(pairs, key=lambda x: -len(x[0])):
306
+ path = path.rstrip("/")
307
+ if len(path) > 1 and path not in seen:
308
+ seen.add(path)
309
+ out.append((re.escape(path) + r"(?![A-Za-z0-9._-])", token))
310
+ out.append((r"/run/user/\d+/", "/run/user/<UID>/"))
311
+ return out
312
+
313
+
314
+ # --------------------------------------------------------------------------
315
+ # --run
316
+
317
+ # Untracked paths under the package directory that a local run may leave without changing the source: the
318
+ # evidence directory and Lake's build state. Ignored files (.gitignore) are not listed and not bound.
319
+ UNTRACKED_OK = (".lean-receipts/", ".lake/")
320
+
321
+
322
+ def tree_state(repo: pathlib.Path, exclude=()) -> tuple[str | None, str, list[str]]:
323
+ """(HEAD, porcelain status of tracked files, untracked files) of the package directory `repo`. The
324
+ pathspec `.` scopes both to it: a package incubated in a subdirectory of a manuscript repository is not
325
+ made dirty by an edit outside it, as the evidence-only rule ignores those paths too. Untracked files are
326
+ the ones git does not ignore (`git ls-files --others --exclude-standard`, package-relative), less
327
+ UNTRACKED_OK and the package-relative paths in `exclude` (the run's own log, stdout, stderr and
328
+ properties files)."""
329
+ head = core.git_head(repo)
330
+ p = core.git(repo, "status", "--porcelain", "--untracked-files=no", "--", ".")
331
+ dirty = p.stdout if p.returncode == 0 else f"git status failed: {p.stderr.strip()}"
332
+ u = core.git(repo, "ls-files", "-z", "--others", "--exclude-standard", "--", ".")
333
+ if u.returncode != 0:
334
+ return head, dirty or f"git ls-files failed: {u.stderr.strip()}", []
335
+ skip = set(exclude)
336
+ untracked = [x for x in u.stdout.split("\0") if x and x not in skip and not x.startswith(UNTRACKED_OK)]
337
+ return head, dirty, untracked
338
+
339
+
340
+ def run_outputs(repo: pathlib.Path, files) -> list[str]:
341
+ """The package-relative paths of the files a run writes that lie inside the package directory."""
342
+ out = []
343
+ root = repo.resolve()
344
+ for f in files:
345
+ try:
346
+ out.append(pathlib.Path(os.path.abspath(f)).resolve().relative_to(root).as_posix())
347
+ except (ValueError, OSError):
348
+ pass
349
+ return out
350
+
351
+
352
+ def source_problem(repo: pathlib.Path, commit: str | None, when: str, exclude=()) -> str | None:
353
+ if commit is None:
354
+ return None # produce() refuses the unknown commit
355
+ head, dirty, untracked = tree_state(repo, exclude)
356
+ if head != commit:
357
+ return (f"source changed {when}: the checkout's HEAD is {(head or 'unknown')[:12]}, not --commit "
358
+ f"{commit[:12]}; a local run verifies the working tree, so it must be the commit")
359
+ if dirty.strip():
360
+ n = len(dirty.strip().splitlines())
361
+ return f"source changed {when}: {n} tracked file(s) differ from --commit {commit[:12]}"
362
+ if untracked:
363
+ shown = ", ".join(untracked[:5]) + (f" (+{len(untracked) - 5} more)" if len(untracked) > 5 else "")
364
+ return (f"source changed {when}: {len(untracked)} untracked file(s) under the package directory, "
365
+ f"which the build can read but --commit {commit[:12]} does not hold: {shown}; commit, remove "
366
+ f"or .gitignore them (ignored files are not bound)")
367
+ return None
368
+
369
+
370
+ class RunInterrupted(Exception):
371
+ """`receipt systemd --run` stopped by a signal (SIGINT, SIGTERM, SIGHUP) while the unit was started or
372
+ polled; cmd_receipt_systemd exits 128 + signum."""
373
+
374
+ def __init__(self, signum: int):
375
+ super().__init__(f"interrupted by {signal.Signals(signum).name}")
376
+ self.signum = signum
377
+
378
+
379
+ INTERRUPT_SIGNALS = (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)
380
+
381
+
382
+ def _set_handlers(handler) -> dict:
383
+ """Install `handler` for INTERRUPT_SIGNALS (main thread only); the previous handlers, for _restore."""
384
+ if threading.current_thread() is not threading.main_thread():
385
+ return {}
386
+ return {s: signal.signal(s, handler) for s in INTERRUPT_SIGNALS}
387
+
388
+
389
+ def _restore(old: dict) -> None:
390
+ for s, h in old.items():
391
+ signal.signal(s, h)
392
+
393
+
394
+ def _raise_interrupt(signum, _frame):
395
+ raise RunInterrupted(signum)
396
+
397
+
398
+ def unit_running(ctl: str, unit: str) -> bool | None:
399
+ """True while the unit (and so its main process) may still run, False when it is gone (not loaded) or
400
+ terminal (failed, inactive, active+exited), None when its state cannot be read."""
401
+ text, why = systemctl_show(ctl, unit, "LoadState,ActiveState,SubState")
402
+ if why:
403
+ return None
404
+ state, _ = parse_properties(text)
405
+ load = state.get("LoadState")
406
+ if load is None:
407
+ return None
408
+ if load != "loaded" or state.get("ActiveState") in ("failed", "inactive") or state.get("SubState") == "exited":
409
+ return False
410
+ return True
411
+
412
+
413
+ def recovery_command(args, unit: str, repo: pathlib.Path, paths: dict, commit: str | None) -> str:
414
+ """The `receipt systemd --unit U ...` (no --run) that writes the receipt from the unit once it finished."""
415
+ argv = ["lean-pkg", "receipt", "systemd", "--unit", unit, "--log", str(paths["--log"]),
416
+ "--receipt-commit", commit or args.commit_sha, "--repo", str(repo)]
417
+ for flag in ("--stdout", "--stderr"):
418
+ if flag in paths:
419
+ argv += [flag, str(paths[flag])]
420
+ if args.checker:
421
+ argv += ["--checker", args.checker]
422
+ for rx in args.redact or []:
423
+ argv += ["--redact", rx]
424
+ return " ".join(shlex.quote(a) for a in argv)
425
+
426
+
427
+ def report_interrupt(args, signum: int, unit: str, running: bool | None, cache_dir: str | None, repo, paths,
428
+ commit) -> None:
429
+ """What an interrupted --run leaves and how to finish it (stderr): the unit is not stopped; its temporary
430
+ Lake cache is kept while the unit may still run; the recovery command, which skips the "source tree
431
+ unchanged during the run" check."""
432
+ name = signal.Signals(signum).name
433
+ state = {True: "is still running", False: "is no longer running", None: "is in an unknown state"}[running]
434
+ err = sys.stderr
435
+ print(f"lean-pkg: receipt systemd: interrupted by {name} while waiting for {unit}; the unit {state} and was "
436
+ f"not stopped; nothing was written to .lean-receipts", file=err)
437
+ if cache_dir is not None:
438
+ if running is False:
439
+ print("lean-pkg: its temporary LAKE_CACHE_DIR was removed (the unit no longer runs)", file=err)
440
+ else:
441
+ print(f"lean-pkg: its temporary LAKE_CACHE_DIR is kept at {cache_dir} (the unit may still use it); "
442
+ f"remove it once the unit has finished: rm -rf {shlex.quote(cache_dir)}", file=err)
443
+ print("lean-pkg: to write the receipt once the unit has finished (it stays loaded: RemainAfterExit), run "
444
+ "without --run, adding any other flags of this run (--out, --append-readme, ...):", file=err)
445
+ print(f" {recovery_command(args, unit, repo, paths, commit)}", file=err)
446
+ print("lean-pkg: WARN recovery via --unit skips the --run check that the source tree was unchanged during the "
447
+ "run (HEAD at --commit, no tracked change, no untracked file); confirm `git status` is clean yourself. "
448
+ f"Then: systemctl --user stop {unit}; systemctl --user reset-failed {unit}", file=err)
449
+
450
+
451
+ def tool_names(values) -> list[str]:
452
+ """The --require-tools names (comma-separated, repeatable), in order, each once."""
453
+ names: list[str] = []
454
+ for value in values or []:
455
+ for name in (w.strip() for w in value.split(",")):
456
+ if not name:
457
+ continue
458
+ if not _TOOL_RE.fullmatch(name):
459
+ raise core.UsageError(f"--require-tools {name!r}: a command name (as `type -P` takes it, no '/')")
460
+ if name not in names:
461
+ names.append(name)
462
+ return names
463
+
464
+
465
+ def unit_path(setenv) -> str:
466
+ """The PATH the unit gets: this process's, unless a --setenv PATH=... replaces it (the last one wins, as in
467
+ systemd's Environment=)."""
468
+ path = os.environ.get("PATH", "")
469
+ for kv in setenv or []:
470
+ if kv.startswith("PATH="):
471
+ path = kv[len("PATH="):]
472
+ return path
473
+
474
+
475
+ def _file_sha256(path: str) -> str | None:
476
+ h = hashlib.sha256()
477
+ try:
478
+ with open(path, "rb") as f:
479
+ for chunk in iter(lambda: f.read(1 << 20), b""):
480
+ h.update(chunk)
481
+ except OSError:
482
+ return None
483
+ return h.hexdigest()
484
+
485
+
486
+ def require_tools(names: list[str], path: str) -> tuple[list[dict], list[str]]:
487
+ """(resolved, missing): each name resolved like bash `type -P` in the unit's PATH (an executable file;
488
+ never a keyword, builtin or function: `time` needs a binary), with its real path and SHA-256."""
489
+ from .host_routes import type_p
490
+ resolved, missing = [], []
491
+ for name in names:
492
+ hit = type_p(name, path)
493
+ if hit is None:
494
+ missing.append(name)
495
+ continue
496
+ real = os.path.realpath(hit)
497
+ resolved.append({"name": name, "path": hit, "realpath": real, "sha256": _file_sha256(real)})
498
+ return resolved, missing
499
+
500
+
501
+ def run_unit(args, unit: str, repo: pathlib.Path, paths: dict, props_out: pathlib.Path,
502
+ refusals: list[str], checks: list[str], producer: dict | None = None) -> str | None:
503
+ """Start the command as the bounded transient unit, wait for it to finish, capture its properties before
504
+ the unit is stopped and reset; returns the captured text (None when it never ran). `producer` (a dict)
505
+ receives the fingerprint of the running lean-pkg taken before the start ("start", producer.py), its
506
+ receipt key as of the start ("receipt") and, when it changed by collection, the changed entries
507
+ ("changed"; also a refusal)."""
508
+ run_exe, ctl = shutil.which("systemd-run"), shutil.which("systemctl")
509
+ if run_exe is None or ctl is None:
510
+ refusals.append("systemd-run / systemctl are not on PATH; on a host without systemd run the unit "
511
+ "elsewhere and pass its saved properties with --properties-file")
512
+ return None
513
+ commit = rc.resolve_commit(repo, args.commit_sha)
514
+ outputs = run_outputs(repo, [*paths.values(), props_out])
515
+ why = source_problem(repo, commit, "before the run", outputs)
516
+ if why:
517
+ refusals.append(why + "; nothing was run")
518
+ return None
519
+ producer = {} if producer is None else producer
520
+ producer["start"] = pr.fingerprint()
521
+ producer["receipt"] = pr.receipt_producer(producer["start"]) # commit and dirtiness as of the start
522
+ argv = [run_exe, "--user", f"--unit={unit}", "--quiet", "-p", "RemainAfterExit=yes",
523
+ "-p", f"WorkingDirectory={repo.resolve()}", "-p", "OOMPolicy=stop",
524
+ "-p", f"MemoryMax={args.memory_max}", "-p", f"MemorySwapMax={args.memory_swap_max}",
525
+ "-p", f"CPUQuota={args.cpu_quota}", "-p", f"RuntimeMaxSec={args.runtime_max}"]
526
+ for flag, prop in (("--stdout", "StandardOutput"), ("--stderr", "StandardError")):
527
+ if flag in paths:
528
+ argv += ["-p", f"{prop}=truncate:{paths[flag].resolve()}"]
529
+ argv += [f"--setenv=PATH={os.environ.get('PATH', '')}"]
530
+ argv += [f"--setenv={kv}" for kv in args.setenv or []]
531
+ given = {kv.split("=", 1)[0] for kv in args.setenv or []}
532
+ cache_dir = None
533
+ if "LAKE_CACHE_DIR" not in given: # a fresh, empty Lake cache of the unit's own (lake_hygiene)
534
+ cache_dir = tempfile.mkdtemp(prefix="lean-pkg-lake-cache.")
535
+ argv += [f"--setenv=LAKE_CACHE_DIR={cache_dir}"]
536
+ if "LAKE_ARTIFACT_CACHE" not in given:
537
+ argv += ["--setenv=LAKE_ARTIFACT_CACHE=false"]
538
+ checks.append("✓ lake cache: " + ("a fresh empty LAKE_CACHE_DIR" if cache_dir else "LAKE_CACHE_DIR as --setenv")
539
+ + ", LAKE_ARTIFACT_CACHE=false" + (" (--setenv)" if "LAKE_ARTIFACT_CACHE" in given else ""))
540
+ argv += ["--", *args.command]
541
+ # Interrupted while the unit may still run (Ctrl-C or a SIGTERM while polling), its temporary Lake cache is
542
+ # never deleted under it: the unit's state decides, and the recovery command is printed (report_interrupt).
543
+ keep_cache = False
544
+ old = _set_handlers(_raise_interrupt)
545
+ try:
546
+ return _run_started(argv, unit, ctl, repo, commit, outputs, props_out, refusals, checks, producer)
547
+ except (KeyboardInterrupt, RunInterrupted) as e:
548
+ _set_handlers(signal.SIG_IGN) # no second interruption while the state is read and reported
549
+ signum = e.signum if isinstance(e, RunInterrupted) else signal.SIGINT
550
+ running = unit_running(ctl, unit)
551
+ keep_cache = running is not False
552
+ if cache_dir is not None and not keep_cache:
553
+ shutil.rmtree(cache_dir, ignore_errors=True)
554
+ report_interrupt(args, signum, unit, running, cache_dir, repo, paths, commit)
555
+ raise RunInterrupted(signum) from None
556
+ finally:
557
+ _restore(old)
558
+ if cache_dir is not None and not keep_cache:
559
+ shutil.rmtree(cache_dir, ignore_errors=True)
560
+
561
+
562
+ def _producer_changes(producer: dict) -> list[str]:
563
+ return pr.changes(producer["start"], pr.fingerprint(pathlib.Path(producer["start"]["pkg"])))
564
+
565
+
566
+ def _run_started(argv, unit, ctl, repo, commit, outputs, props_out, refusals, checks, producer) -> str | None:
567
+ try:
568
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=SYSTEMCTL_TIMEOUT, env=user_env())
569
+ except (OSError, subprocess.TimeoutExpired) as e:
570
+ refusals.append(f"systemd-run could not run: {e}")
571
+ return None
572
+ if p.returncode != 0:
573
+ refusals.append(f"systemd-run exited {p.returncode}: {(p.stderr or p.stdout).strip() or 'no output'} "
574
+ f"(a unit named {unit} may already be loaded: `systemctl --user status {unit}`)")
575
+ return None
576
+ print(f"lean-pkg: receipt systemd: started {unit}; waiting for it to finish", file=sys.stderr)
577
+ next_check, warned = time.monotonic() + PRODUCER_CHECK_SECONDS, False
578
+ while True:
579
+ text, why = systemctl_show(ctl, unit, STATE_PROPS)
580
+ if why:
581
+ refusals.append(why)
582
+ return None
583
+ state, _ = parse_properties(text)
584
+ if (state.get("LoadState") != "loaded" or state.get("ActiveState") in ("failed", "inactive")
585
+ or state.get("SubState") == "exited"):
586
+ break
587
+ if not warned and time.monotonic() >= next_check:
588
+ # Early, not only at the end: the receipt of this run will be refused, say so while it runs.
589
+ names = _producer_changes(producer)
590
+ next_check = time.monotonic() + PRODUCER_CHECK_SECONDS
591
+ if names:
592
+ warned = True
593
+ print(f"lean-pkg: receipt systemd: WARN {pr.changed_message(names, 'while ' + unit + ' runs')}; "
594
+ f"this run's receipt will be refused at collection (the unit keeps running; stop it with "
595
+ f"systemctl --user stop {unit})", file=sys.stderr)
596
+ time.sleep(POLL_SECONDS)
597
+ text, why = systemctl_show(ctl, unit, ",".join(UNIT_PROPS))
598
+ if why is None:
599
+ text = text.rstrip("\n") + f"\n{HOST_KEY}={socket.gethostname()}\n"
600
+ props_out.write_text(text, encoding="utf-8")
601
+ checks.append(f"✓ ran {unit}; properties captured before cleanup to {rc._shown(props_out, repo)}")
602
+ else:
603
+ refusals.append(why)
604
+ text = None
605
+ _quiet([ctl, "--user", "stop", unit]) # RemainAfterExit kept it loaded until now
606
+ _quiet([ctl, "--user", "reset-failed", unit])
607
+ why = source_problem(repo, commit, "during the run", outputs)
608
+ if why:
609
+ refusals.append(why)
610
+ names = _producer_changes(producer)
611
+ if names:
612
+ producer["changed"] = names
613
+ refusals.append(pr.changed_message(names, "during the run"))
614
+ else:
615
+ start = producer["start"]
616
+ what = "; ".join([f"{len(start['sources'])} source files", *start["environment"]])
617
+ checks.append(f"✓ producer: lean-pkg {start['version']} unchanged from run start to collection ({what})")
618
+ return text
619
+
620
+
621
+ # --------------------------------------------------------------------------
622
+ # the command
623
+
624
+ def unit_name(value: str) -> str:
625
+ unit = (value or "").strip()
626
+ if not unit or unit.startswith("-") or not _UNIT_RE.fullmatch(unit):
627
+ raise core.UsageError(f"--unit must name a systemd service unit, got {value!r}")
628
+ if _OTHER_TYPE_RE.search(unit):
629
+ raise core.UsageError(f"--unit {unit}: only service units carry a main process exit status")
630
+ return unit if unit.endswith(".service") else unit + ".service"
631
+
632
+
633
+ def _refuse_early(args, job_id: str | None, refusals: list[str], checks: list[str], json_extra: dict) -> int:
634
+ """Refuse before the shared pipeline can run (the unit never ran, or left no log)."""
635
+ if args.json_out:
636
+ payload = {"ok": False, "receipt": None, "log": None, "report_sha256": None, "raw_log_sha256": None,
637
+ "sealed": [],
638
+ "job_id": job_id, "seal": None, "log_commit_bound": None}
639
+ payload.update(json_extra)
640
+ payload.update({"redactions": 0, "lines_redacted": 0, "checks": checks, "readme_block": None,
641
+ "readme_appended": False, "next": None, "refusals": refusals})
642
+ core.print_json(payload)
643
+ verdict = f"receipt systemd: refused, {len(refusals)} problem(s); nothing written"
644
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
645
+ for r in refusals:
646
+ print(f" ✗ {r}", file=sys.stderr)
647
+ print(f"lean-pkg: {verdict}", file=sys.stderr)
648
+ return 1
649
+
650
+
651
+ def cmd_receipt_systemd(args) -> int:
652
+ unit = unit_name(args.unit)
653
+ repo = rc.repo_dir(args)
654
+ run = bool(args.run)
655
+ if run and not args.command:
656
+ raise core.UsageError("--run needs the command after `--` (e.g. --run -- bash verify.sh)")
657
+ if args.command and not run:
658
+ raise core.UsageError(f"a command ({args.command[0]!r} ...) is only run with --run")
659
+ if run and args.properties_file:
660
+ raise core.UsageError("--run and --properties-file are exclusive: --run captures the properties itself")
661
+ if not run and args.properties_out:
662
+ raise core.UsageError("--properties-out is only for --run")
663
+ if run:
664
+ for flag in ("memory_max", "memory_swap_max", "cpu_quota", "runtime_max"):
665
+ v = getattr(args, flag)
666
+ if not _CAP_RE.fullmatch(v or ""):
667
+ raise core.UsageError(f"--{flag.replace('_', '-')} {v!r}: a finite systemd value (e.g. "
668
+ f"{DEFAULT_CAPS[flag]}) is required; the unit is bounded")
669
+ for kv in args.setenv or []:
670
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", kv):
671
+ raise core.UsageError(f"--setenv {kv!r}: expected NAME=VALUE")
672
+ name, value = kv.split("=", 1)
673
+ if name == "LAKE_CACHE_DIR" and not value.strip():
674
+ raise core.UsageError("--setenv LAKE_CACHE_DIR= (empty) does not disable Lake's artifact cache "
675
+ "(Lake then uses .lake/cache); leave it out and --run gives the unit a "
676
+ "fresh empty one")
677
+ if name == "LAKE_ARTIFACT_CACHE" and value.strip().lower() not in ("false", "0"):
678
+ raise core.UsageError(f"--setenv {kv!r}: a receipt run needs LAKE_ARTIFACT_CACHE=false (a "
679
+ f"restored module's sorry warning need not be printed)")
680
+ elif args.setenv:
681
+ raise core.UsageError("--setenv is only for --run")
682
+ tools = tool_names(args.require_tools)
683
+ if tools and not run:
684
+ raise core.UsageError("--require-tools is only for --run (it is checked before the unit is created)")
685
+ if getattr(args, "contracts_preflight", False) and not run:
686
+ raise core.UsageError("--contracts-preflight is only for --run (it compares before the unit is created)")
687
+ paths = {}
688
+ for flag, value in (("--log", args.log), ("--stdout", args.stdout), ("--stderr", args.stderr)):
689
+ if value is None:
690
+ continue
691
+ p = pathlib.Path(value).expanduser()
692
+ if run:
693
+ if p.exists() or p.is_symlink():
694
+ raise core.UsageError(f"{flag} {value}: already exists; --run writes it fresh (remove it first)")
695
+ if not p.parent.is_dir():
696
+ raise core.UsageError(f"{flag} {value}: no such directory")
697
+ elif not p.is_file():
698
+ raise core.UsageError(f"{flag} {value}: no such file")
699
+ paths[flag] = p
700
+ props_out = None
701
+ if run:
702
+ props_out = pathlib.Path(args.properties_out or f"{paths['--log']}.unit.properties").expanduser()
703
+ if props_out.exists() or props_out.is_symlink():
704
+ raise core.UsageError(f"--properties-out {props_out.name}: already exists (remove it first)")
705
+ if args.properties_file is not None and not pathlib.Path(args.properties_file).expanduser().is_file():
706
+ raise core.UsageError(f"--properties-file {args.properties_file}: no such file")
707
+ extra = rc.common_usage(args)
708
+
709
+ refusals: list[str] = []
710
+ checks: list[str] = []
711
+ json_extra = {"unit": None, "properties": None, "ran": run, "producer": None}
712
+ producer: dict = {}
713
+ missing_tools: list[str] = []
714
+ if run and tools:
715
+ # Before the unit exists: every project-declared tool must resolve in the unit's own PATH.
716
+ resolved, missing_tools = require_tools(tools, unit_path(args.setenv))
717
+ json_extra["run_tools"] = {"required": tools, "resolved": resolved, "missing": missing_tools}
718
+ for t in resolved:
719
+ print(f"lean-pkg: receipt systemd: run tool {t['name']}: {t['path']}"
720
+ + (f" -> {t['realpath']}" if t["realpath"] != t["path"] else "")
721
+ + f" sha256 {t['sha256'] or 'unreadable'}", file=sys.stderr)
722
+ if missing_tools:
723
+ refusals.append(f"--require-tools: not found in the unit's PATH (type -P): {', '.join(missing_tools)}; "
724
+ f"nothing was run")
725
+ else:
726
+ checks.append(f"✓ run tools: {len(resolved)} resolved in the unit's PATH (type -P) before the unit "
727
+ f"was created: {', '.join(tools)}")
728
+ contracts_refused = False
729
+ if run and getattr(args, "contracts_preflight", False):
730
+ # Before the unit exists: every comparator configuration must match (#409)
731
+ from . import comparator_contracts as cc
732
+ pre = cc.preflight(repo)
733
+ json_extra["contracts_preflight"] = {"ok": pre["ok"], "report": pre["report"]}
734
+ refusals += pre["refusals"]
735
+ checks += pre["checks"]
736
+ contracts_refused = not pre["ok"]
737
+ if run and (missing_tools or contracts_refused):
738
+ text = None
739
+ elif run:
740
+ try:
741
+ text = run_unit(args, unit, repo, paths, props_out, refusals, checks, producer)
742
+ except RunInterrupted as e:
743
+ return 128 + e.signum
744
+ if text is not None:
745
+ json_extra["properties"] = str(props_out)
746
+ if "receipt" in producer:
747
+ json_extra["producer"] = {**producer["receipt"],
748
+ "changed": producer.get("changed", [])}
749
+ elif args.properties_file is not None:
750
+ text = pathlib.Path(args.properties_file).expanduser().read_text(encoding="utf-8", errors="replace")
751
+ json_extra["properties"] = str(args.properties_file)
752
+ else:
753
+ ctl = shutil.which("systemctl")
754
+ if ctl is None:
755
+ text = None
756
+ refusals.append("systemctl is not on PATH; save `systemctl --user show U -p "
757
+ f"{','.join(UNIT_PROPS)}` plus a `{HOST_KEY}=` line where the unit ran and pass "
758
+ "--properties-file")
759
+ else:
760
+ text, why = systemctl_show(ctl, unit, ",".join(UNIT_PROPS))
761
+ if why:
762
+ refusals.append(why)
763
+ else:
764
+ text = text.rstrip("\n") + f"\n{HOST_KEY}={socket.gethostname()}\n"
765
+
766
+ summary = None
767
+ props: dict = {}
768
+ if text is not None:
769
+ props, problems = parse_properties(text)
770
+ refusals += problems
771
+ summary, problems, unit_checks = check_unit(props, unit)
772
+ refusals += problems
773
+ checks += unit_checks
774
+ json_extra["unit"] = summary
775
+ s = summary or {}
776
+ host = s.get("host") or "unknown-host"
777
+ inv = s.get("invocation_id") or "unknown"
778
+ job_id = f"systemd-user:{unit}:{inv}@{host}"
779
+ gate_mod.receipt_job_slug(job_id)
780
+ if summary is None or not paths["--log"].is_file():
781
+ if "--log" in paths and not paths["--log"].is_file():
782
+ refusals.append(f"--log {paths['--log'].name}: the unit wrote no verify log there")
783
+ return _refuse_early(args, job_id if summary else None, refusals, checks, json_extra)
784
+ for flag in ("--stdout", "--stderr"):
785
+ if flag in paths and not paths[flag].is_file():
786
+ refusals.append(f"{flag} {paths[flag].name}: the unit's stream was not written")
787
+ return _refuse_early(args, job_id, refusals, checks, json_extra)
788
+
789
+ sealed_producer = None
790
+ if json_extra["producer"] is not None and not json_extra["producer"]["changed"]:
791
+ sealed_producer = {k: v for k, v in json_extra["producer"].items() if k != "changed"}
792
+
793
+ def lines(receipt_name: str, tar: str) -> list[str]:
794
+ out = [f"- Receipt: `{receipt_name}`. systemd --user unit `{unit}`, invocation `{inv}` on `{host}`:",
795
+ f" Result success, exit `0`; {resources(s)}{tar}."]
796
+ if sealed_producer:
797
+ p = sealed_producer
798
+ build = f"editable {p['commit'][:12]}{'+dirty' if p['dirty'] else ''}" if p["commit"] else p["install"]
799
+ code = (f", own bytecode ({p['bytecode_tag']}, {p['bytecode_files']} file(s)) SHA-256 "
800
+ f"`{p['bytecode_sha256']}`" if p.get("bytecode_sha256") else "")
801
+ other = (f", {p['other_bytecode_files']} other bytecode file(s)"
802
+ if p.get("other_bytecode_files") else "")
803
+ out.append(f"- Producer: lean-pkg {p['lean_pkg']} ({build}), sources SHA-256 `{p['sources_sha256']}`"
804
+ f"{code}{other}; sources unchanged from run start to collection.")
805
+ return out
806
+
807
+ def log_job_id(value: str) -> str | None:
808
+ if value not in (job_id, inv):
809
+ return f"verify log: `job-id:` {value!r} is neither the job_id {job_id!r} nor the InvocationID"
810
+ return None
811
+
812
+ def stdout_check(out_text: str, refs: list[str], chks: list[str]) -> None:
813
+ vals = rc.stdout_values(out_text, INVOCATION_KEY)
814
+ if len(vals) > 1:
815
+ refs.append(f"job stdout: {len(vals)} `{INVOCATION_KEY}` lines; at most one is allowed")
816
+ elif vals and vals[0].lower() != inv:
817
+ refs.append(f"job stdout: {INVOCATION_KEY} {vals[0][:12]}… is not the unit's InvocationID "
818
+ f"{inv[:12]}…; the stdout is from another run")
819
+ elif vals:
820
+ chks.append(f"✓ stdout: {INVOCATION_KEY} = the unit's InvocationID")
821
+
822
+ ev = rc.Evidence(verb="receipt systemd", job_id=job_id, refusals=refusals, checks=checks,
823
+ executor_lines=lines, default_heading=f"lower-tier receipt, systemd unit {unit}",
824
+ check_log_job_id=log_job_id, json_extra=json_extra, redactions=redactions(repo),
825
+ redaction_note="local paths redacted", stdout_check=stdout_check,
826
+ evidence_files=[("unit.properties", normalised(props), "unit_properties_sha256",
827
+ "- Unit properties: `{name}`, SHA-256 `{sha}` (captured before the unit "
828
+ "was collected).")],
829
+ receipt_extra={"producer": sealed_producer} if sealed_producer else None)
830
+ return rc.produce(args, ev, repo, paths, extra)
831
+
832
+
833
+ def add_parser(rsub) -> None:
834
+ s = rsub.add_parser("systemd", # `receipt local` is an alias (command_tree.COMMAND_ALIASES)
835
+ help="a lower-tier receipt from a finished systemd --user service unit (run bounded with "
836
+ "--run, or its saved properties), its verify log and its stdout seal")
837
+ s.add_argument("--unit", required=True, metavar="U",
838
+ help="the service unit (`.service` added when absent); job_id becomes "
839
+ "systemd-user:<U>:<InvocationID>@<host label> (h- + 12 hex of the host name's SHA-256)")
840
+ s.add_argument("--log", required=True, metavar="PATH",
841
+ help="the raw verify log the unit writes; when it has no `checker:` line, --checker TEXT is "
842
+ "required")
843
+ s.add_argument("--receipt-commit", dest="commit_sha", required=True, metavar="SHA",
844
+ help="the verified commit; must exist in --repo (with --run: the checkout's clean HEAD)")
845
+ s.add_argument("--stdout", default=None, metavar="PATH",
846
+ help=f"the unit's stdout file: {rc.SHA_KEY} = sha256(raw log), {rc.PRE_KEY} = {rc.POST_KEY} = "
847
+ f"sha256(lake-manifest.json at the commit), optional {INVOCATION_KEY} = InvocationID; "
848
+ "without it the log must carry its own seal. With --run the unit writes it")
849
+ s.add_argument("--stderr", default=None, metavar="PATH",
850
+ help="the unit's stderr file; must be empty. With --run the unit writes it")
851
+ src = s.add_argument_group("where the unit's terminal state comes from (default: `systemctl --user show U` "
852
+ "now, on this host)")
853
+ src.add_argument("--properties-file", default=None, metavar="F",
854
+ help=f"saved `systemctl --user show U -p {','.join(UNIT_PROPS)}` output, captured before the "
855
+ f"unit was collected, plus a `{HOST_KEY}=` line for the host it ran on")
856
+ src.add_argument("--run", action="store_true",
857
+ help="start `-- CMD ...` as the bounded unit U (systemd-run --user, RemainAfterExit, "
858
+ "WorkingDirectory=--repo), wait for it, capture its properties before stopping it; "
859
+ "--log, --stdout, --stderr must not exist yet. The running lean-pkg's own files must "
860
+ "not change during the run (sealed as the receipt key `producer`)")
861
+ src.add_argument("--memory-max", default=DEFAULT_CAPS["memory_max"], metavar="BYTES",
862
+ help=f"--run: MemoryMax (default {DEFAULT_CAPS['memory_max']})")
863
+ src.add_argument("--memory-swap-max", default=DEFAULT_CAPS["memory_swap_max"], metavar="BYTES",
864
+ help=f"--run: MemorySwapMax (default {DEFAULT_CAPS['memory_swap_max']}, so the memory cap "
865
+ "is an OOM kill, not swapping)")
866
+ src.add_argument("--cpu-quota", default=DEFAULT_CAPS["cpu_quota"], metavar="PCT",
867
+ help=f"--run: CPUQuota (default {DEFAULT_CAPS['cpu_quota'].replace('%', '%%')})")
868
+ src.add_argument("--runtime-max", default=DEFAULT_CAPS["runtime_max"], metavar="SPAN",
869
+ help=f"--run: RuntimeMaxSec (default {DEFAULT_CAPS['runtime_max']})")
870
+ src.add_argument("--setenv", action="append", default=[], metavar="NAME=VALUE",
871
+ help="--run: an extra environment variable for the unit (repeatable; PATH is passed; "
872
+ "LAKE_CACHE_DIR=<fresh empty dir> and LAKE_ARTIFACT_CACHE=false unless named here)")
873
+ src.add_argument("--require-tools", action="append", default=[], metavar="A,B,...",
874
+ help="--run: executables the command needs (comma-separated, repeatable), each resolved "
875
+ "with `type -P` in the unit's PATH before the unit is created; a missing one refuses "
876
+ "and nothing is run. The resolved paths and SHA-256 are printed (stderr) and in --json "
877
+ "run_tools")
878
+ src.add_argument("--contracts-preflight", action="store_true",
879
+ help="--run: before the unit is created, run the contracts-only diagnostic (`comparator check "
880
+ "--contracts-only`) on every comparator configuration of the checkout; a configuration "
881
+ "that differs, one whose modules are not built, or a diagnostic that cannot run refuses, "
882
+ "and nothing is run or written (docs/comparator.md, Before receipt work)")
883
+ src.add_argument("--properties-out", default=None, metavar="PATH",
884
+ help="--run: where the captured properties go (default <log>.unit.properties)")
885
+ s.add_argument("--redact", action="append", default=[], metavar="REGEX",
886
+ help=f"also replace matches with {rc.REDACT_TOKEN} (repeatable); the checkout's path, $HOME "
887
+ "and /run/user/N/ are always redacted to <repo>, <HOME>, /run/user/<UID>/ instead")
888
+ rc.add_common_flags(s, "systemd unit U", "systemd-user-<U>-<InvocationID>-<host label>")
889
+ s.add_argument("command", nargs="*", metavar="-- CMD", help="with --run: the command the unit runs")
890
+ s.set_defaults(fn=cmd_receipt_systemd)