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.
- lean_pkg/__init__.py +3 -0
- lean_pkg/adapters/__init__.py +148 -0
- lean_pkg/adapters/github.py +65 -0
- lean_pkg/adapters/leansearch.py +68 -0
- lean_pkg/adapters/loogle.py +45 -0
- lean_pkg/adapters/palomar.py +170 -0
- lean_pkg/adapters/reservoir.py +127 -0
- lean_pkg/anchor.py +678 -0
- lean_pkg/audit.py +716 -0
- lean_pkg/binding_file.py +446 -0
- lean_pkg/blueprint.py +213 -0
- lean_pkg/build_scope.py +282 -0
- lean_pkg/ci_github.py +917 -0
- lean_pkg/claim_axioms.py +421 -0
- lean_pkg/claims.py +1155 -0
- lean_pkg/claims_mark.py +197 -0
- lean_pkg/cli.py +5208 -0
- lean_pkg/cli_parser.py +768 -0
- lean_pkg/command_tree.py +615 -0
- lean_pkg/comparator_config.py +990 -0
- lean_pkg/comparator_contracts.py +382 -0
- lean_pkg/comparator_receipt.py +2854 -0
- lean_pkg/comparator_stage.py +623 -0
- lean_pkg/comparator_types.py +830 -0
- lean_pkg/container.py +172 -0
- lean_pkg/core.py +1570 -0
- lean_pkg/coverage.py +1278 -0
- lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
- lean_pkg/data/toolchain-advisories.yaml +77 -0
- lean_pkg/data/upgrade-breaking.yaml +20 -0
- lean_pkg/data/verify-workflow-pins.yaml +14 -0
- lean_pkg/deps_closure.py +512 -0
- lean_pkg/deps_fill.py +445 -0
- lean_pkg/dup_constants.py +448 -0
- lean_pkg/exercise.py +828 -0
- lean_pkg/exercise_forbid.py +288 -0
- lean_pkg/export_paths.py +77 -0
- lean_pkg/extract.py +1172 -0
- lean_pkg/extract_decls.py +501 -0
- lean_pkg/extract_ledger.py +1408 -0
- lean_pkg/extract_summary.py +132 -0
- lean_pkg/extract_types.py +502 -0
- lean_pkg/extract_write.py +138 -0
- lean_pkg/formalization.py +1078 -0
- lean_pkg/formalization_kept.py +182 -0
- lean_pkg/fresh_repo.py +709 -0
- lean_pkg/gate.py +2141 -0
- lean_pkg/headline.py +211 -0
- lean_pkg/help_topics.py +442 -0
- lean_pkg/holes.py +289 -0
- lean_pkg/host_routes.py +376 -0
- lean_pkg/hypotheses.py +788 -0
- lean_pkg/index.py +1749 -0
- lean_pkg/json_stdout.py +48 -0
- lean_pkg/lake_hygiene.py +289 -0
- lean_pkg/lean_diag.py +280 -0
- lean_pkg/lean_scan.py +1300 -0
- lean_pkg/ledger.py +582 -0
- lean_pkg/next_step.py +510 -0
- lean_pkg/page.py +1831 -0
- lean_pkg/page_html.py +153 -0
- lean_pkg/palomar.py +316 -0
- lean_pkg/palomar_check.py +1027 -0
- lean_pkg/port_modules.py +677 -0
- lean_pkg/prior_art.py +286 -0
- lean_pkg/producer.py +212 -0
- lean_pkg/producer_skew.py +208 -0
- lean_pkg/public_safety.py +1487 -0
- lean_pkg/publish.py +402 -0
- lean_pkg/rebase.py +984 -0
- lean_pkg/receipt.py +2385 -0
- lean_pkg/receipt_check.py +1064 -0
- lean_pkg/receipt_ci.py +660 -0
- lean_pkg/receipt_systemd.py +890 -0
- lean_pkg/recommended.py +232 -0
- lean_pkg/report.py +727 -0
- lean_pkg/reservoir.py +203 -0
- lean_pkg/scaffold.py +588 -0
- lean_pkg/schemas/formalization-0.4.schema.json +344 -0
- lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
- lean_pkg/scripts/ClaimAxioms.lean +47 -0
- lean_pkg/scripts/ContractsOnly.lean +300 -0
- lean_pkg/scripts/DupConstants.lean +149 -0
- lean_pkg/scripts/HypProbe.lean +257 -0
- lean_pkg/scripts/comparator-check.sh +396 -0
- lean_pkg/scripts/verify-comparator.sh +135 -0
- lean_pkg/seal_bundle.py +647 -0
- lean_pkg/search.py +865 -0
- lean_pkg/site_profiles/easley.yaml +10 -0
- lean_pkg/site_profiles/github-actions.yaml +12 -0
- lean_pkg/sites.py +225 -0
- lean_pkg/stacks.py +373 -0
- lean_pkg/statements_module.py +217 -0
- lean_pkg/templates/Apache-2.0.txt +202 -0
- lean_pkg/toolchain_advisories.py +225 -0
- lean_pkg/upgrade.py +706 -0
- lean_pkg/verify.py +495 -0
- lean_pkg-0.25.0.dist-info/METADATA +93 -0
- lean_pkg-0.25.0.dist-info/RECORD +103 -0
- lean_pkg-0.25.0.dist-info/WHEEL +5 -0
- lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
- lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
- lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
lean_pkg/holes.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
# holes -- the definition-hole sign-off rule shared by the comparator receipt
|
|
2
|
+
# runner (before a run) and the receipt validators (against the config bytes
|
|
3
|
+
# at the bound commit), and the sign-off sidecar that holds lean-pkg's own
|
|
4
|
+
# comparator metadata. Mirrors lint_config in scripts/comparator-check.sh.
|
|
5
|
+
"""Why this exists.
|
|
6
|
+
|
|
7
|
+
leanprover/comparator compares a name listed in a configuration's
|
|
8
|
+
``definition_names`` by name, universes, type and safety only
|
|
9
|
+
(``Comparator/Compare.lean``), never by body, and its README says such holes
|
|
10
|
+
must be checked by an additional, potentially human, verifier. A
|
|
11
|
+
configuration with non-empty ``definition_names`` is therefore refused
|
|
12
|
+
unless that verifier is recorded.
|
|
13
|
+
|
|
14
|
+
Where (#signoff-sidecar). Palomar's verifier refuses any configuration key
|
|
15
|
+
outside its six (challenge_module, solution_module, theorem_names,
|
|
16
|
+
definition_names, permitted_axioms, enable_nanoda), so lean-pkg keeps its own
|
|
17
|
+
metadata out of the configuration, in one sidecar file at the package root,
|
|
18
|
+
``lean-pkg-signoff.json`` (deliberately not ``comparator*.json``: the runner
|
|
19
|
+
and Palomar would read that as a configuration)::
|
|
20
|
+
|
|
21
|
+
{"schema": "lean-pkg-signoff/1",
|
|
22
|
+
"configs": {
|
|
23
|
+
"comparator.json": {
|
|
24
|
+
"config_sha256": "<sha256 of the configuration's bytes>",
|
|
25
|
+
"definitions": {
|
|
26
|
+
"Foo.bar": {"reviewer": "<human name>", "date": "YYYY-MM-DD",
|
|
27
|
+
"judged_as": "<what the body was judged to be, and how>"}},
|
|
28
|
+
"scaffold": {"todo": [{"theorem_name": "...", ...}], ...},
|
|
29
|
+
"smoke": {"reason": "<why this configuration is a sanity check>"}}}}
|
|
30
|
+
|
|
31
|
+
Strict: exact key sets, duplicate JSON keys refused, every configuration key
|
|
32
|
+
a comparator configuration path. ``config_sha256`` binds the sign-off to the
|
|
33
|
+
configuration's bytes: a changed configuration invalidates it until a human
|
|
34
|
+
re-judges and re-binds. ``scaffold`` holds the TODO markers `comparator config
|
|
35
|
+
--from-claims` writes (formerly the ``lean_pkg_scaffold`` key). ``smoke`` (optional) declares the
|
|
36
|
+
configuration a smoke check: a sanity theorem that tests the comparator set-up and states no result of
|
|
37
|
+
the package. Its theorems must still pass (they are in the receipt), but they verify no claim, need no
|
|
38
|
+
claim in coverage.yaml, and pages show them as smoke checks, never as results (`smoke_paths`).
|
|
39
|
+
|
|
40
|
+
Deprecated: the inline ``judged_as`` object ({reviewer, date, definitions[],
|
|
41
|
+
basis?}) and ``lean_pkg_scaffold`` keys inside the configuration still work
|
|
42
|
+
for lean-pkg's own checks, with a deprecation warning naming
|
|
43
|
+
``lean-pkg comparator config --migrate-signoff PATH --write``; ``palomar
|
|
44
|
+
check`` still refuses them. When the sidecar has an entry for a configuration,
|
|
45
|
+
the entry wins.
|
|
46
|
+
|
|
47
|
+
``reviewer`` must not be a model or agent token. This is a declaration, not a
|
|
48
|
+
verification: the tool records who signed, it cannot check the bodies.
|
|
49
|
+
"""
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import hashlib
|
|
53
|
+
import json
|
|
54
|
+
import re
|
|
55
|
+
|
|
56
|
+
REVIEWER_DENY = frozenset({
|
|
57
|
+
"claude", "codex", "gpt", "opus", "sonnet", "fable", "agent", "bot",
|
|
58
|
+
"opencode", "assistant", "llm", "ai",
|
|
59
|
+
})
|
|
60
|
+
SIDECAR = "lean-pkg-signoff.json"
|
|
61
|
+
SIDECAR_SCHEMA = "lean-pkg-signoff/1"
|
|
62
|
+
INLINE_KEYS = ("judged_as", "lean_pkg_scaffold") # deprecated in a configuration (Palomar refuses them)
|
|
63
|
+
ENTRY_KEYS = frozenset({"config_sha256", "definitions", "scaffold", "smoke"})
|
|
64
|
+
SIGNOFF_KEYS = frozenset({"reviewer", "date", "judged_as"})
|
|
65
|
+
SCAFFOLD_KEYS = frozenset({"generated_by", "note", "types_note", "todo"})
|
|
66
|
+
SMOKE_KEYS = frozenset({"reason"})
|
|
67
|
+
# Same rule as gate.COMPARATOR_CONFIG_RE (a test pins the two equal); holes.py imports nothing of lean-pkg.
|
|
68
|
+
CONFIG_RE = re.compile(r"^(comparator[^/]*\.json|comparator/config[^/]*\.json)$")
|
|
69
|
+
_DATE_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
|
|
70
|
+
_HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
|
71
|
+
_TAIL = (" (comparator checks definition holes by name and type only, never by "
|
|
72
|
+
f"body; a human must sign off in {SIDECAR})")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def migrate_command(cfg_rel: str) -> str:
|
|
76
|
+
return f"lean-pkg comparator config --migrate-signoff {cfg_rel} --write"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def deprecation(cfg_rel: str, keys) -> str:
|
|
80
|
+
keys = [k for k in INLINE_KEYS if k in set(keys)]
|
|
81
|
+
return (f"{cfg_rel}: inline {' and '.join(keys)} in the comparator configuration is deprecated "
|
|
82
|
+
f"(Palomar refuses keys outside its six); move {'them' if len(keys) > 1 else 'it'} to {SIDECAR}: "
|
|
83
|
+
f"{migrate_command(cfg_rel)} (the config's bytes change: a gated package then needs a new "
|
|
84
|
+
f"comparator receipt)")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def sha256_bytes(b: bytes) -> str:
|
|
88
|
+
return hashlib.sha256(b).hexdigest()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _strict_pairs(pairs):
|
|
92
|
+
out = {}
|
|
93
|
+
for k, v in pairs:
|
|
94
|
+
if k in out:
|
|
95
|
+
raise ValueError(f"duplicate key {k!r}")
|
|
96
|
+
out[k] = v
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def check_reviewer(reviewer, where: str) -> None:
|
|
101
|
+
if not isinstance(reviewer, str) or not reviewer.strip():
|
|
102
|
+
raise ValueError(f"{where}.reviewer must be a non-empty human name{_TAIL}")
|
|
103
|
+
tokens = [t for t in re.split(r"[^a-z0-9]+", reviewer.lower()) if t]
|
|
104
|
+
if any(t in REVIEWER_DENY for t in tokens):
|
|
105
|
+
raise ValueError(f"{where}.reviewer {reviewer!r} names an agent/model token, not a human reviewer{_TAIL}")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def parse_sidecar(raw: bytes | None, label: str = SIDECAR) -> dict:
|
|
109
|
+
"""The sidecar document, validated strictly; {"schema": ..., "configs": {}} when `raw` is None (no file).
|
|
110
|
+
Raises ValueError naming the first problem."""
|
|
111
|
+
if raw is None:
|
|
112
|
+
return {"schema": SIDECAR_SCHEMA, "configs": {}}
|
|
113
|
+
try:
|
|
114
|
+
doc = json.loads(raw.decode("utf-8"), object_pairs_hook=_strict_pairs)
|
|
115
|
+
except (UnicodeDecodeError, ValueError) as e:
|
|
116
|
+
raise ValueError(f"{label}: not valid strict JSON ({e})") from e
|
|
117
|
+
if not isinstance(doc, dict) or set(doc) != {"schema", "configs"}:
|
|
118
|
+
raise ValueError(f"{label}: must be an object with exactly the keys schema and configs")
|
|
119
|
+
if doc["schema"] != SIDECAR_SCHEMA:
|
|
120
|
+
raise ValueError(f"{label}: schema must be {SIDECAR_SCHEMA!r}, got {doc['schema']!r}")
|
|
121
|
+
if not isinstance(doc["configs"], dict):
|
|
122
|
+
raise ValueError(f"{label}: configs must be an object keyed by comparator configuration path")
|
|
123
|
+
for rel, ent in doc["configs"].items():
|
|
124
|
+
where = f"{label}: configs[{rel!r}]"
|
|
125
|
+
if not CONFIG_RE.match(rel):
|
|
126
|
+
raise ValueError(f"{where}: not a comparator configuration path (comparator*.json at the package "
|
|
127
|
+
f"root or comparator/config*.json)")
|
|
128
|
+
if not isinstance(ent, dict) or not ent or set(ent) - ENTRY_KEYS:
|
|
129
|
+
raise ValueError(f"{where}: must be a non-empty object with keys among "
|
|
130
|
+
f"{', '.join(sorted(ENTRY_KEYS))}")
|
|
131
|
+
defs = ent.get("definitions")
|
|
132
|
+
if defs is not None:
|
|
133
|
+
if not isinstance(defs, dict) or not defs:
|
|
134
|
+
raise ValueError(f"{where}.definitions: must be a non-empty object keyed by definition name")
|
|
135
|
+
if not isinstance(ent.get("config_sha256"), str) or not _HEX64.match(ent["config_sha256"]):
|
|
136
|
+
raise ValueError(f"{where}.config_sha256: must be the 64-hex sha256 of the configuration's "
|
|
137
|
+
f"bytes (it binds the sign-off to them)")
|
|
138
|
+
for dname, s in defs.items():
|
|
139
|
+
w = f"{where}.definitions[{dname!r}]"
|
|
140
|
+
if not dname.strip():
|
|
141
|
+
raise ValueError(f"{w}: empty definition name")
|
|
142
|
+
if not isinstance(s, dict) or set(s) != SIGNOFF_KEYS:
|
|
143
|
+
raise ValueError(f"{w}: must have exactly the keys {', '.join(sorted(SIGNOFF_KEYS))}")
|
|
144
|
+
check_reviewer(s["reviewer"], w)
|
|
145
|
+
if not isinstance(s["date"], str) or not _DATE_RE.match(s["date"]):
|
|
146
|
+
raise ValueError(f"{w}.date must be an ISO date YYYY-MM-DD")
|
|
147
|
+
if not isinstance(s["judged_as"], str) or not s["judged_as"].strip():
|
|
148
|
+
raise ValueError(f"{w}.judged_as must be a non-empty text: what the body was judged to "
|
|
149
|
+
f"be, and how")
|
|
150
|
+
elif "config_sha256" in ent:
|
|
151
|
+
raise ValueError(f"{where}: config_sha256 binds a sign-off; it needs definitions")
|
|
152
|
+
sc = ent.get("scaffold")
|
|
153
|
+
if sc is not None:
|
|
154
|
+
if not isinstance(sc, dict) or set(sc) - SCAFFOLD_KEYS or not isinstance(sc.get("todo"), list):
|
|
155
|
+
raise ValueError(f"{where}.scaffold: must be an object with a todo list (keys among "
|
|
156
|
+
f"{', '.join(sorted(SCAFFOLD_KEYS))})")
|
|
157
|
+
for i, t in enumerate(sc["todo"]):
|
|
158
|
+
if not isinstance(t, dict) or not isinstance(t.get("theorem_name"), str) or not t["theorem_name"]:
|
|
159
|
+
raise ValueError(f"{where}.scaffold.todo[{i}]: must be an object with a theorem_name")
|
|
160
|
+
for k in ("generated_by", "note", "types_note"):
|
|
161
|
+
if k in sc and not isinstance(sc[k], str):
|
|
162
|
+
raise ValueError(f"{where}.scaffold.{k}: must be a string")
|
|
163
|
+
sm = ent.get("smoke")
|
|
164
|
+
if sm is not None and (not isinstance(sm, dict) or set(sm) != SMOKE_KEYS
|
|
165
|
+
or not isinstance(sm["reason"], str) or not sm["reason"].strip()):
|
|
166
|
+
raise ValueError(f"{where}.smoke: must be an object with exactly the key reason, a non-empty text "
|
|
167
|
+
f"saying why the configuration is a sanity check and states no result")
|
|
168
|
+
return doc
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def smoke_paths(sidecar: dict | None) -> dict[str, str]:
|
|
172
|
+
"""{configuration path: reason} of the configurations the sidecar marks as smoke checks."""
|
|
173
|
+
out = {}
|
|
174
|
+
for rel, ent in ((sidecar or {}).get("configs") or {}).items():
|
|
175
|
+
sm = ent.get("smoke") if isinstance(ent, dict) else None
|
|
176
|
+
if isinstance(sm, dict) and isinstance(sm.get("reason"), str) and sm["reason"].strip():
|
|
177
|
+
out[rel] = sm["reason"].strip()
|
|
178
|
+
return out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def dump_sidecar(doc: dict) -> str:
|
|
182
|
+
configs = {k: doc["configs"][k] for k in sorted(doc["configs"]) if doc["configs"][k]}
|
|
183
|
+
return json.dumps({"schema": SIDECAR_SCHEMA, "configs": configs}, indent=2, ensure_ascii=False) + "\n"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _inline_check(cfg: dict, holes: list[str], label: str) -> dict:
|
|
187
|
+
judged = cfg.get("judged_as")
|
|
188
|
+
if not isinstance(judged, dict):
|
|
189
|
+
raise ValueError(f"{label}: definition_names is non-empty ({len(holes)} hole(s)) but there is no "
|
|
190
|
+
f"sign-off: no entry in {SIDECAR} and no (deprecated) inline judged_as object{_TAIL}")
|
|
191
|
+
check_reviewer(judged.get("reviewer"), f"{label}: judged_as")
|
|
192
|
+
date = judged.get("date")
|
|
193
|
+
if not isinstance(date, str) or not _DATE_RE.match(date):
|
|
194
|
+
raise ValueError(f"{label}: judged_as.date must be an ISO date YYYY-MM-DD{_TAIL}")
|
|
195
|
+
defs = judged.get("definitions")
|
|
196
|
+
if not isinstance(defs, list):
|
|
197
|
+
raise ValueError(f"{label}: judged_as.definitions must be an array covering "
|
|
198
|
+
f"every definition_names entry{_TAIL}")
|
|
199
|
+
missing = [h for h in holes if h not in defs]
|
|
200
|
+
if missing:
|
|
201
|
+
raise ValueError(f"{label}: judged_as.definitions does not cover definition "
|
|
202
|
+
f"hole(s): {', '.join(missing)}{_TAIL}")
|
|
203
|
+
basis = judged.get("basis")
|
|
204
|
+
text = basis.strip() if isinstance(basis, str) and basis.strip() else \
|
|
205
|
+
"signed off in the inline judged_as object (no basis recorded)"
|
|
206
|
+
return {h: {"reviewer": judged["reviewer"], "date": date, "judged_as": text} for h in holes}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def check_definition_holes(cfg: dict, label: str, *, cfg_rel: str | None = None,
|
|
210
|
+
cfg_bytes: bytes | None = None, sidecar: dict | None = None,
|
|
211
|
+
warn=None) -> dict | None:
|
|
212
|
+
"""Raise ValueError unless cfg's definition holes carry a human sign-off.
|
|
213
|
+
|
|
214
|
+
Returns None when the configuration has no holes, else {"source": "sidecar"|"inline", "definitions":
|
|
215
|
+
{hole: {reviewer, date, judged_as}}}. With `sidecar` (a parse_sidecar document) and `cfg_rel`, an entry
|
|
216
|
+
for the configuration is used first; its config_sha256 must equal sha256(`cfg_bytes`). Without an
|
|
217
|
+
entry, the deprecated inline judged_as is read, and `warn(msg)` (when given) is told to migrate."""
|
|
218
|
+
holes = cfg.get("definition_names") or []
|
|
219
|
+
if not isinstance(holes, list) or not all(isinstance(h, str) for h in holes):
|
|
220
|
+
raise ValueError(f"{label}: definition_names must be a list of strings")
|
|
221
|
+
inline = [k for k in INLINE_KEYS if k in cfg]
|
|
222
|
+
ent = ((sidecar or {}).get("configs") or {}).get(cfg_rel) if cfg_rel else None
|
|
223
|
+
defs = (ent or {}).get("definitions")
|
|
224
|
+
if not holes:
|
|
225
|
+
if inline and warn:
|
|
226
|
+
warn(deprecation(cfg_rel or label, inline))
|
|
227
|
+
return None
|
|
228
|
+
if defs:
|
|
229
|
+
if cfg_bytes is None:
|
|
230
|
+
raise ValueError(f"{label}: the sign-off in {SIDECAR} is bound to the configuration's bytes, "
|
|
231
|
+
f"which were not read")
|
|
232
|
+
have = sha256_bytes(cfg_bytes)
|
|
233
|
+
if have != ent["config_sha256"]:
|
|
234
|
+
raise ValueError(f"{label}: the sign-off in {SIDECAR} is bound to config_sha256 "
|
|
235
|
+
f"{ent['config_sha256'][:12]}, but the configuration's bytes hash to {have[:12]}: a "
|
|
236
|
+
f"changed configuration invalidates its sign-off; a human re-judges the definition "
|
|
237
|
+
f"bodies, then sets config_sha256 to {have}{_TAIL}")
|
|
238
|
+
missing = [h for h in holes if h not in defs]
|
|
239
|
+
if missing:
|
|
240
|
+
raise ValueError(f"{label}: {SIDECAR} definitions do not cover definition hole(s): "
|
|
241
|
+
f"{', '.join(missing)}{_TAIL}")
|
|
242
|
+
extra = sorted(set(defs) - set(holes))
|
|
243
|
+
if extra:
|
|
244
|
+
raise ValueError(f"{label}: {SIDECAR} signs off {', '.join(extra)}, not a definition_names entry of "
|
|
245
|
+
f"the configuration (remove the stale sign-off)")
|
|
246
|
+
if inline and warn:
|
|
247
|
+
warn(deprecation(cfg_rel or label, inline) + f"; the {SIDECAR} entry is the one read")
|
|
248
|
+
return {"source": "sidecar", "definitions": {h: dict(defs[h]) for h in holes}}
|
|
249
|
+
out = _inline_check(cfg, holes, label)
|
|
250
|
+
if warn:
|
|
251
|
+
warn(deprecation(cfg_rel or label, inline))
|
|
252
|
+
return {"source": "inline", "definitions": out}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def scaffold_block(cfg: dict, cfg_rel: str | None = None, sidecar: dict | None = None) -> dict | None:
|
|
256
|
+
"""The scaffold TODO block of a configuration: the sidecar's entry, else the deprecated inline
|
|
257
|
+
lean_pkg_scaffold key."""
|
|
258
|
+
ent = ((sidecar or {}).get("configs") or {}).get(cfg_rel) if cfg_rel else None
|
|
259
|
+
if isinstance(ent, dict) and isinstance(ent.get("scaffold"), dict):
|
|
260
|
+
return ent["scaffold"]
|
|
261
|
+
block = cfg.get("lean_pkg_scaffold") if isinstance(cfg, dict) else None
|
|
262
|
+
return block if isinstance(block, dict) else None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def summary(signoff: dict | None) -> dict | None:
|
|
266
|
+
"""One {reviewer, date, definitions, basis} object for a sign-off (the shape the deprecated inline
|
|
267
|
+
judged_as had, which formalization.yaml main_results and the page render): reviewers joined, the
|
|
268
|
+
latest date, the judgements joined."""
|
|
269
|
+
if not signoff:
|
|
270
|
+
return None
|
|
271
|
+
defs = signoff["definitions"]
|
|
272
|
+
uniq = lambda xs: list(dict.fromkeys(xs)) # noqa: E731
|
|
273
|
+
return {"reviewer": "; ".join(uniq(d["reviewer"] for d in defs.values())),
|
|
274
|
+
"date": max(d["date"] for d in defs.values()),
|
|
275
|
+
"definitions": list(defs),
|
|
276
|
+
"basis": "; ".join(uniq(d["judged_as"] for d in defs.values()))}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def receipt_judged(entry: dict) -> dict:
|
|
280
|
+
"""{reviewer, date} a comparator receipt's config entry records for its holes: the `signoff` copy
|
|
281
|
+
(from the sidecar) first, else the deprecated `judged_as` copy; {} when neither."""
|
|
282
|
+
so = entry.get("signoff")
|
|
283
|
+
if isinstance(so, dict) and isinstance(so.get("definitions"), dict) and so["definitions"]:
|
|
284
|
+
try:
|
|
285
|
+
return summary({"definitions": so["definitions"]}) or {}
|
|
286
|
+
except (KeyError, TypeError, ValueError):
|
|
287
|
+
return {}
|
|
288
|
+
j = entry.get("judged_as")
|
|
289
|
+
return j if isinstance(j, dict) else {}
|
lean_pkg/host_routes.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""`lean-pkg comparator host-check --routes [--json]` (field report #5): host and cluster planning before sbatch.
|
|
3
|
+
|
|
4
|
+
Per route, whether this host (run it inside the job's image, with the job's binds and PATH) supports it and
|
|
5
|
+
exactly why:
|
|
6
|
+
|
|
7
|
+
- judge: the official `lake comparator` judge, sandboxed in bwrap; needs an unprivileged user namespace.
|
|
8
|
+
The same requirement set as `mechanism toolchain` of `comparator host-check` (one source: host_checks()).
|
|
9
|
+
- prepare: the setup stages only (`comparator-receipt --prepare`: dependency checkout, Mathlib cache, build);
|
|
10
|
+
no sandbox, so it may run in a cluster job.
|
|
11
|
+
- transfer: build here, judge on another host that passes the judge route: prepare here, pack and hash the
|
|
12
|
+
build and its evidence directory, copy them to a checkout of the same commit there, and check the copied
|
|
13
|
+
oleans with `comparator-receipt --verify-oleans` (#173) before judging.
|
|
14
|
+
|
|
15
|
+
Plus the facts a job needs: executables resolved like `type -P` (the Slurm template's required-tool list is
|
|
16
|
+
read from SBATCH_TEMPLATE itself, so there is one list), locale (the inherited-locale warning that broke a
|
|
17
|
+
strict empty stderr), open-file limits with the LEAN_NUM_THREADS advice, the CPU affinity count and the
|
|
18
|
+
cgroup memory limit. Read-only: no network, no writes, no registry. It never offers an unsandboxed judge:
|
|
19
|
+
a host without a working bwrap has no judge route, only prepare and transfer.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import pathlib
|
|
26
|
+
import re
|
|
27
|
+
import stat
|
|
28
|
+
import sys
|
|
29
|
+
|
|
30
|
+
ROUTES_SCHEMA = "host-routes/1"
|
|
31
|
+
ROUTES = ("judge", "prepare", "transfer")
|
|
32
|
+
# comparator-receipt is a Python program; its setup stages run lake, lean and git.
|
|
33
|
+
PREPARE_TOOLS = ("lake", "lean", "git", "python3")
|
|
34
|
+
# The transfer packs and hashes .lake/build for the copy to the judging host.
|
|
35
|
+
TRANSFER_TOOLS = ("tar", "sha256sum")
|
|
36
|
+
# Always reported, in this order; then the Slurm template's own required tools not already listed.
|
|
37
|
+
CORE_EXECUTABLES = ("lake", "lean", "git", "python3", "bwrap", "sha256sum", "tar", "time")
|
|
38
|
+
TIME_NOTE = ("`time` is a bash keyword, which `type -P` never reports: only a time binary resolves. The "
|
|
39
|
+
"keyword works in a bash script; `$RUN time ...`, `env time`, `xargs time` or `srun time` need "
|
|
40
|
+
"the binary, which many images lack")
|
|
41
|
+
|
|
42
|
+
NOFILE_LOW = 4096 # a soft `ulimit -n` below this is tight for a Mathlib-heavy Lean build
|
|
43
|
+
FILE_TABLE_FREE_LOW = 262144 # free entries in the system file table (file-nr max - allocated)
|
|
44
|
+
MATHLIB_THREADS = 3 # the Slurm template's LEAN_NUM_THREADS default
|
|
45
|
+
CGROUP_UNLIMITED = 1 << 62 # cgroup v1 reports "no limit" as a page-rounded 2**63-1
|
|
46
|
+
CGROUP_ROOT = pathlib.Path("/sys/fs/cgroup")
|
|
47
|
+
PROC_CGROUP = pathlib.Path("/proc/self/cgroup")
|
|
48
|
+
FILE_NR = pathlib.Path("/proc/sys/fs/file-nr")
|
|
49
|
+
MEMINFO = pathlib.Path("/proc/meminfo")
|
|
50
|
+
SLURM_ENV = ("SLURM_JOB_ID", "SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE", "SLURM_MEM_PER_NODE",
|
|
51
|
+
"SLURM_MEM_PER_CPU")
|
|
52
|
+
LOCALE_VARS = ("LC_ALL", "LC_CTYPE", "LANG")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
# One source of truth with `receipt slurm --template` (#172): its required host tools and its locale line.
|
|
57
|
+
|
|
58
|
+
def template_host_tools() -> tuple[str, ...]:
|
|
59
|
+
"""The HOST_TOOLS list of the Slurm template (`receipt slurm --template`), without EXTRA_TOOLS."""
|
|
60
|
+
from .receipt import SBATCH_TEMPLATE
|
|
61
|
+
m = re.search(r'^HOST_TOOLS="([^"]*)"', SBATCH_TEMPLATE, re.MULTILINE)
|
|
62
|
+
if m is None: # the template changed shape: tests/test_host_routes.py fails on this
|
|
63
|
+
return ()
|
|
64
|
+
return tuple(w for w in m.group(1).split() if not w.startswith("$"))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def template_locale() -> str:
|
|
68
|
+
"""The template's locale export, e.g. 'LC_ALL=C LANG=C PYTHONUTF8=1'."""
|
|
69
|
+
from .receipt import SBATCH_TEMPLATE
|
|
70
|
+
m = re.search(r"^export (LC_ALL=\S+ LANG=\S+ PYTHONUTF8=\S+)\s*$", SBATCH_TEMPLATE, re.MULTILINE)
|
|
71
|
+
return m.group(1) if m else "LC_ALL=C LANG=C PYTHONUTF8=1"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------------------------------------------------------------------------
|
|
75
|
+
# Probes. Each is a module-level function so the tests monkeypatch it; none writes anything.
|
|
76
|
+
|
|
77
|
+
def type_p(name: str, path: str | None = None) -> str | None:
|
|
78
|
+
"""Like bash `type -P NAME`: the first PATH entry holding an executable regular file NAME (an empty
|
|
79
|
+
entry is the current directory). Keywords, builtins, aliases and functions are never reported."""
|
|
80
|
+
path = os.environ.get("PATH", "") if path is None else path
|
|
81
|
+
for d in path.split(os.pathsep):
|
|
82
|
+
p = os.path.join(d or ".", name)
|
|
83
|
+
try:
|
|
84
|
+
st = os.stat(p)
|
|
85
|
+
except OSError:
|
|
86
|
+
continue
|
|
87
|
+
if stat.S_ISREG(st.st_mode) and os.access(p, os.X_OK):
|
|
88
|
+
return p
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def locale_available(name: str) -> bool:
|
|
93
|
+
"""Whether the C library can load locale NAME (what bash's setlocale warning is about). The process's
|
|
94
|
+
LC_CTYPE is restored before returning."""
|
|
95
|
+
import locale
|
|
96
|
+
old = locale.setlocale(locale.LC_CTYPE)
|
|
97
|
+
try:
|
|
98
|
+
locale.setlocale(locale.LC_CTYPE, name)
|
|
99
|
+
return True
|
|
100
|
+
except locale.Error:
|
|
101
|
+
return False
|
|
102
|
+
finally:
|
|
103
|
+
locale.setlocale(locale.LC_CTYPE, old)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def nofile_limits() -> tuple[int | None, int | None]:
|
|
107
|
+
"""(soft, hard) of RLIMIT_NOFILE; None means unlimited or unknown."""
|
|
108
|
+
try:
|
|
109
|
+
import resource
|
|
110
|
+
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
|
|
111
|
+
except (ImportError, OSError, ValueError):
|
|
112
|
+
return None, None
|
|
113
|
+
inf = getattr(__import__("resource"), "RLIM_INFINITY", -1)
|
|
114
|
+
return (None if soft == inf else int(soft)), (None if hard == inf else int(hard))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_text(path: pathlib.Path) -> str | None:
|
|
118
|
+
try:
|
|
119
|
+
return path.read_text()
|
|
120
|
+
except (OSError, UnicodeDecodeError):
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cpus_allowed() -> int | None:
|
|
125
|
+
try:
|
|
126
|
+
return len(os.sched_getaffinity(0))
|
|
127
|
+
except (AttributeError, OSError):
|
|
128
|
+
return os.cpu_count()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def env_get(name: str) -> str | None:
|
|
132
|
+
return os.environ.get(name)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------------------
|
|
136
|
+
# Parsers (pure; tested on fixed text)
|
|
137
|
+
|
|
138
|
+
def parse_file_nr(text: str | None) -> dict | None:
|
|
139
|
+
"""/proc/sys/fs/file-nr 'allocated unused max' -> {allocated, unused, max, free}."""
|
|
140
|
+
if not text:
|
|
141
|
+
return None
|
|
142
|
+
parts = text.split()
|
|
143
|
+
if len(parts) < 3 or not all(p.isdigit() for p in parts[:3]):
|
|
144
|
+
return None
|
|
145
|
+
alloc, unused, mx = (int(p) for p in parts[:3])
|
|
146
|
+
return {"allocated": alloc, "unused": unused, "max": mx, "free": max(mx - alloc, 0)}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _limit_walk(base: pathlib.Path, rel: str, filename: str, unlimited) -> int | None:
|
|
150
|
+
"""The tightest FILENAME limit from base/rel up to base (a parent's limit binds its children)."""
|
|
151
|
+
rel = rel.strip().lstrip("/")
|
|
152
|
+
p = base / rel if rel else base
|
|
153
|
+
found: list[int] = []
|
|
154
|
+
while True:
|
|
155
|
+
v = read_text(p / filename)
|
|
156
|
+
if v is not None:
|
|
157
|
+
v = v.strip()
|
|
158
|
+
if v.isdigit() and not unlimited(int(v)):
|
|
159
|
+
found.append(int(v))
|
|
160
|
+
if p == base or base not in p.parents:
|
|
161
|
+
break
|
|
162
|
+
p = p.parent
|
|
163
|
+
return min(found) if found else None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def cgroup_memory(proc_cgroup: str | None, root: pathlib.Path = CGROUP_ROOT) -> dict:
|
|
167
|
+
"""{version: 2|1|None, path, limit_bytes (None = no limit found)} from /proc/self/cgroup text.
|
|
168
|
+
v2: the unified line `0::/path`, memory.max ('max' = none). v1: the line whose controllers include
|
|
169
|
+
`memory`, memory.limit_in_bytes under <root>/memory (2**62 or more = none)."""
|
|
170
|
+
if not proc_cgroup:
|
|
171
|
+
return {"version": None, "path": None, "limit_bytes": None}
|
|
172
|
+
v1 = v2 = None
|
|
173
|
+
for line in proc_cgroup.splitlines():
|
|
174
|
+
parts = line.split(":", 2)
|
|
175
|
+
if len(parts) != 3:
|
|
176
|
+
continue
|
|
177
|
+
hid, ctrls, path = parts
|
|
178
|
+
if hid == "0" and ctrls == "":
|
|
179
|
+
v2 = path
|
|
180
|
+
elif "memory" in ctrls.split(","):
|
|
181
|
+
v1 = path
|
|
182
|
+
if v1 is not None:
|
|
183
|
+
return {"version": 1, "path": v1,
|
|
184
|
+
"limit_bytes": _limit_walk(root / "memory", v1, "memory.limit_in_bytes",
|
|
185
|
+
lambda n: n >= CGROUP_UNLIMITED)}
|
|
186
|
+
if v2 is not None:
|
|
187
|
+
return {"version": 2, "path": v2,
|
|
188
|
+
"limit_bytes": _limit_walk(root, v2, "memory.max", lambda n: False)}
|
|
189
|
+
return {"version": None, "path": None, "limit_bytes": None}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def mem_available(meminfo: str | None) -> int | None:
|
|
193
|
+
m = re.search(r"^MemAvailable:\s+(\d+)\s*kB", meminfo or "", re.MULTILINE)
|
|
194
|
+
return int(m.group(1)) * 1024 if m else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _gib(n: int | None) -> str:
|
|
198
|
+
return "none" if n is None else f"{n / (1 << 30):.1f} GiB"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
def locale_report() -> dict:
|
|
204
|
+
vals = {v: env_get(v) for v in LOCALE_VARS}
|
|
205
|
+
c_utf8 = locale_available("C.UTF-8")
|
|
206
|
+
missing = sorted({x for x in vals.values() if x and x not in ("C", "POSIX") and not locale_available(x)})
|
|
207
|
+
fix = template_locale()
|
|
208
|
+
if missing:
|
|
209
|
+
level = "warn"
|
|
210
|
+
detail = (f"{', '.join(missing)} is set but not installed here: bash and other tools print a setlocale "
|
|
211
|
+
f"warning on stderr, and a lean-pkg receipt refuses a non-empty stderr (it is never "
|
|
212
|
+
f"filtered). Export {fix} in the job before any tool runs (the `receipt slurm --template` "
|
|
213
|
+
f"wrapper does)")
|
|
214
|
+
else:
|
|
215
|
+
level = "ok"
|
|
216
|
+
detail = "every set locale variable names an installed locale"
|
|
217
|
+
return {"LANG": vals["LANG"], "LC_ALL": vals["LC_ALL"], "LC_CTYPE": vals["LC_CTYPE"], "c_utf8": c_utf8,
|
|
218
|
+
"unavailable": missing, "level": level, "detail": detail, "job_export": fix}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def limits_report() -> dict:
|
|
222
|
+
soft, hard = nofile_limits()
|
|
223
|
+
fnr = parse_file_nr(read_text(FILE_NR))
|
|
224
|
+
reasons = []
|
|
225
|
+
if soft is not None and soft < NOFILE_LOW:
|
|
226
|
+
reasons.append(f"ulimit -n soft {soft} < {NOFILE_LOW}")
|
|
227
|
+
if fnr is not None and fnr["free"] < FILE_TABLE_FREE_LOW:
|
|
228
|
+
reasons.append(f"system file table: {fnr['free']} free of {fnr['max']} (/proc/sys/fs/file-nr)")
|
|
229
|
+
return {"nofile_soft": soft, "nofile_hard": hard, "file_nr": fnr, "tight": bool(reasons),
|
|
230
|
+
"reasons": reasons, "level": "warn" if reasons else "ok"}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def resources_report() -> dict:
|
|
234
|
+
cg = cgroup_memory(read_text(PROC_CGROUP))
|
|
235
|
+
slurm = {k: env_get(k) for k in SLURM_ENV if env_get(k) is not None}
|
|
236
|
+
return {"cpus_allowed": cpus_allowed(), "cgroup_version": cg["version"],
|
|
237
|
+
"cgroup_memory_max": cg["limit_bytes"], "mem_available": mem_available(read_text(MEMINFO)),
|
|
238
|
+
"slurm": slurm}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def advice_list(limits: dict, resources: dict, loc: dict) -> list[str]:
|
|
242
|
+
out = []
|
|
243
|
+
cpus = resources["cpus_allowed"]
|
|
244
|
+
if limits["tight"]:
|
|
245
|
+
line = (f"file limits are tight ({'; '.join(limits['reasons'])}): Mathlib-heavy packages: "
|
|
246
|
+
f"LEAN_NUM_THREADS={MATHLIB_THREADS}")
|
|
247
|
+
if limits["nofile_soft"] is not None and (limits["nofile_hard"] is None
|
|
248
|
+
or limits["nofile_hard"] > limits["nofile_soft"]):
|
|
249
|
+
line += f"; raise the soft limit first: ulimit -n {limits['nofile_hard'] or 'unlimited'}"
|
|
250
|
+
out.append(line + ". \"Too many open files in system\" means fewer threads, never excluding the node")
|
|
251
|
+
else:
|
|
252
|
+
out.append(f"LEAN_NUM_THREADS at most {cpus or 'the allowed CPUs'}; Mathlib-heavy packages: "
|
|
253
|
+
f"{MATHLIB_THREADS} if a build reports \"Too many open files\"")
|
|
254
|
+
if cpus is not None:
|
|
255
|
+
out.append(f"size the job to measured use: {cpus} CPU(s) allowed here (sched_getaffinity); about "
|
|
256
|
+
f"--cpus-per-task=4 for a serial checker; read TotalCPU/Elapsed of a pilot in sacct")
|
|
257
|
+
if resources["cgroup_memory_max"] is not None:
|
|
258
|
+
out.append(f"cgroup memory limit {_gib(resources['cgroup_memory_max'])}: size the judge's memory cap "
|
|
259
|
+
f"(`comparator-receipt --estimate`) below it")
|
|
260
|
+
if loc["level"] != "ok":
|
|
261
|
+
out.append(f"export {loc['job_export']} before any tool runs")
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _route(name, ok, needs, failing, reason, commands, notes=()):
|
|
266
|
+
return {"route": name, "supported": ok, "needs": list(needs), "failing": list(failing),
|
|
267
|
+
"reason": reason, "commands": list(commands) if ok else [], "notes": list(notes)}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def routes_report(hc: dict) -> dict:
|
|
271
|
+
"""The additive `--routes` keys for a host_checks() result."""
|
|
272
|
+
from .comparator_receipt import ALLOWED_HOSTS_ENV, BUILD_SOURCE_ENV, DEFAULT_EVIDENCE, TOOLCHAIN_FLOOR
|
|
273
|
+
tmpl = template_host_tools()
|
|
274
|
+
names = list(CORE_EXECUTABLES) + [t for t in tmpl if t not in CORE_EXECUTABLES]
|
|
275
|
+
exes = {n: type_p(n) for n in names}
|
|
276
|
+
loc, lim, res = locale_report(), limits_report(), resources_report()
|
|
277
|
+
threads = f"LEAN_NUM_THREADS={MATHLIB_THREADS} " if lim["tight"] else ""
|
|
278
|
+
kernel = next((c for c in hc["checks"] if c["item"] == "kernel"), {"level": "ok", "detail": ""})
|
|
279
|
+
common_notes = [f"locale: {loc['detail']}"] if loc["level"] != "ok" else []
|
|
280
|
+
|
|
281
|
+
jd = hc["mechanism_detail"]["toolchain"]
|
|
282
|
+
policy_note = (f"host policy: inside a Slurm job comparator-receipt runs as is; on a workstation without Slurm "
|
|
283
|
+
f"and with {ALLOWED_HOSTS_ENV} unset it runs as is too (the workstation default); on a Slurm "
|
|
284
|
+
f"login node list this host in {ALLOWED_HOSTS_ENV}")
|
|
285
|
+
if jd["ok"]:
|
|
286
|
+
judge = _route("judge", True, jd["needs"], [], (
|
|
287
|
+
f"bwrap creates a user namespace and {', '.join(n for n in jd['needs'] if n not in ('kernel', 'bwrap'))} "
|
|
288
|
+
f"resolve; the project's toolchain must be Lean {TOOLCHAIN_FLOOR}+ (comparator-receipt checks it "
|
|
289
|
+
f"per project)"),
|
|
290
|
+
[f"cd CHECKOUT && {threads}comparator-receipt --prepare",
|
|
291
|
+
"comparator-receipt --estimate --json # read recommended_cap",
|
|
292
|
+
f"timeout \"$CAP\" comparator-receipt --from-prepared {DEFAULT_EVIDENCE.as_posix()}"],
|
|
293
|
+
common_notes + [policy_note])
|
|
294
|
+
else:
|
|
295
|
+
judge = _route("judge", False, jd["needs"], jd["failing"], (
|
|
296
|
+
"; ".join(jd["failing"]) + ". The judge runs only inside bwrap; there is no unsandboxed route. "
|
|
297
|
+
"Build here and judge on a host whose `host-check --routes` says judge: yes (route transfer)"),
|
|
298
|
+
[])
|
|
299
|
+
|
|
300
|
+
def missing(tools):
|
|
301
|
+
return [f"{t}: not found (type -P)" for t in tools if exes[t] is None]
|
|
302
|
+
|
|
303
|
+
pf = ([f"kernel: {kernel['detail']}"] if kernel["level"] == "fail" else []) + missing(PREPARE_TOOLS)
|
|
304
|
+
prepare = _route("prepare", not pf, ("kernel",) + PREPARE_TOOLS, pf,
|
|
305
|
+
("; ".join(pf) if pf else
|
|
306
|
+
f"{', '.join(PREPARE_TOOLS)} resolve; the setup stages (dependency checkout, Mathlib cache, "
|
|
307
|
+
f"build) need no sandbox, so they may run in a cluster job"),
|
|
308
|
+
[f"cd CHECKOUT && {threads}comparator-receipt --prepare"], common_notes)
|
|
309
|
+
tf = pf + missing(TRANSFER_TOOLS)
|
|
310
|
+
t_notes = list(common_notes)
|
|
311
|
+
if judge["supported"]:
|
|
312
|
+
t_notes.append("this host can judge itself; the transfer is needed only to judge elsewhere")
|
|
313
|
+
transfer = _route("transfer", not tf, ("kernel",) + PREPARE_TOOLS + TRANSFER_TOOLS, tf,
|
|
314
|
+
("; ".join(tf) if tf else
|
|
315
|
+
"this host can be the build side: prepare here, pack .lake/build and the evidence "
|
|
316
|
+
"directory with their sha256, copy them to a checkout of the same commit (same "
|
|
317
|
+
"lean-toolchain and lake-manifest.json) on a host whose `host-check --routes` says "
|
|
318
|
+
"judge: yes, check the copied oleans there with `comparator-receipt --verify-oleans`, "
|
|
319
|
+
"and judge there"),
|
|
320
|
+
[f"cd CHECKOUT && {threads}comparator-receipt --prepare",
|
|
321
|
+
f"tar -cf build.tar .lake/build && tar -cf evidence.tar -C {DEFAULT_EVIDENCE.parent.as_posix()} "
|
|
322
|
+
f"{DEFAULT_EVIDENCE.name} && sha256sum build.tar evidence.tar > transfer.sha256",
|
|
323
|
+
"# judging host, a checkout of the same commit, after copying the three files:",
|
|
324
|
+
"sha256sum -c transfer.sha256 && tar -xf build.tar && mkdir -p \"$CLUSTER_EVIDENCE\" "
|
|
325
|
+
"&& tar -xf evidence.tar -C \"$CLUSTER_EVIDENCE\"",
|
|
326
|
+
"lean-pkg comparator host-check --routes # judge: yes required there",
|
|
327
|
+
f"export {BUILD_SOURCE_ENV}=\"cluster job $JOB\"",
|
|
328
|
+
f"comparator-receipt --verify-oleans \"$CLUSTER_EVIDENCE/{DEFAULT_EVIDENCE.name}\" "
|
|
329
|
+
f"# the copied oleans are the job's",
|
|
330
|
+
"comparator-receipt --prepare # compiles nothing: build: prebuilt",
|
|
331
|
+
"comparator-receipt --estimate --json # read recommended_cap",
|
|
332
|
+
"timeout \"$CAP\" comparator-receipt"],
|
|
333
|
+
t_notes)
|
|
334
|
+
exe_rows = {n: {"path": p, "level": "ok" if p else ("warn" if n in ("time", "bwrap") else "fail"),
|
|
335
|
+
**({"note": TIME_NOTE} if n == "time" else {}),
|
|
336
|
+
"required_by": sorted(
|
|
337
|
+
({"judge"} if n in jd["needs"] else set())
|
|
338
|
+
| ({"prepare", "transfer"} if n in PREPARE_TOOLS else set())
|
|
339
|
+
| ({"transfer"} if n in TRANSFER_TOOLS else set())
|
|
340
|
+
| ({"slurm-template"} if n in tmpl else set()))}
|
|
341
|
+
for n, p in exes.items()}
|
|
342
|
+
return {"routes_schema": ROUTES_SCHEMA, "routes": [judge, prepare, transfer], "executables": exe_rows,
|
|
343
|
+
"locale": loc, "limits": lim, "resources": res, "advice": advice_list(lim, res, loc)}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def render_text(rep: dict) -> list[str]:
|
|
347
|
+
out = []
|
|
348
|
+
for r in rep["routes"]:
|
|
349
|
+
out.append(f"route {r['route']}: {'yes' if r['supported'] else 'no'} ({r['reason']})")
|
|
350
|
+
for c in r["commands"]:
|
|
351
|
+
out.append(f" run: {c}")
|
|
352
|
+
for n in r["notes"]:
|
|
353
|
+
out.append(f" note: {n}")
|
|
354
|
+
for n, e in rep["executables"].items():
|
|
355
|
+
out.append(f"{e['level']} exe {n}: {e['path'] or 'not found (type -P)'}"
|
|
356
|
+
+ (f" [{', '.join(e['required_by'])}]" if e["required_by"] else "")
|
|
357
|
+
+ (f"; {e['note']}" if e.get("note") and not e["path"] else ""))
|
|
358
|
+
loc = rep["locale"]
|
|
359
|
+
out.append(f"{loc['level']} locale: LANG={loc['LANG'] or '(unset)'} LC_ALL={loc['LC_ALL'] or '(unset)'}; "
|
|
360
|
+
f"C.UTF-8 installed: {'yes' if loc['c_utf8'] else 'no'}; {loc['detail']}")
|
|
361
|
+
lim = rep["limits"]
|
|
362
|
+
fnr = lim["file_nr"]
|
|
363
|
+
out.append(f"{lim['level']} limits: ulimit -n soft {lim['nofile_soft'] or 'unlimited'} hard "
|
|
364
|
+
f"{lim['nofile_hard'] or 'unlimited'}; file-nr "
|
|
365
|
+
+ (f"{fnr['allocated']} allocated of {fnr['max']}" if fnr else "unreadable"))
|
|
366
|
+
res = rep["resources"]
|
|
367
|
+
out.append(f"ok resources: {res['cpus_allowed']} CPU(s) allowed; cgroup v{res['cgroup_version'] or '?'} "
|
|
368
|
+
f"memory limit {_gib(res['cgroup_memory_max'])}; MemAvailable {_gib(res['mem_available'])}"
|
|
369
|
+
+ (f"; {' '.join(f'{k}={v}' for k, v in res['slurm'].items())}" if res["slurm"] else ""))
|
|
370
|
+
for a in rep["advice"]:
|
|
371
|
+
out.append(f"advice: {a}")
|
|
372
|
+
return out
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
if __name__ == "__main__": # pragma: no cover
|
|
376
|
+
sys.exit("use: lean-pkg comparator host-check --routes")
|