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,623 @@
1
+ # comparator_stage -- how comparator-receipt's stage 04 runs its judges (#39).
2
+ """Judges stream, never buffer.
3
+
4
+ A judge (`verify-comparator.sh` -> `lake comparator`, or `comparator-check.sh`) runs with stdin
5
+ from /dev/null, stdout and stderr merged into ONE pipe that a reader thread drains line by line
6
+ (so neither side can fill a pipe and stall), every line appended and flushed to the unit's log and
7
+ to the stage log the moment it arrives, and the judge in its own process group so a TERM to the
8
+ runner kills the whole judge tree instead of orphaning it. Lean's `IO.println` is fully buffered
9
+ on a pipe, so the command is wrapped in `stdbuf -oL -eL` when stdbuf exists (it reaches lake and
10
+ every unsandboxed descendant through the environment), and PYTHONUNBUFFERED=1 covers Python
11
+ helpers. While a judge is silent the pool writes a heartbeat line every COMPARATOR_HEARTBEAT_SECONDS
12
+ (default 60) naming its run time, its silence and the bytes in its private TMPDIR (where
13
+ `lake comparator` writes its NDJSON exports, the dominant phase of a long run).
14
+
15
+ Before #39 the toolchain judge ran under `subprocess.run(capture_output=True)` and its output
16
+ reached the log only after it exited: a run killed by an external timeout left an empty log.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import dataclasses
21
+ import datetime as dt
22
+ import hashlib
23
+ import json
24
+ import math
25
+ import os
26
+ import pathlib
27
+ import re
28
+ import shutil
29
+ import signal
30
+ import subprocess
31
+ import threading
32
+ import time
33
+
34
+ HEARTBEAT_ENV = "COMPARATOR_HEARTBEAT_SECONDS"
35
+ DEFAULT_HEARTBEAT = 60.0
36
+ KILL_GRACE = 10.0 # seconds between TERM and KILL for a judge's process group
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Redaction (#41): absolute paths under the checkout, HOME and TMPDIR never reach a stage log, a
41
+ # receipt log or a receipt field; they become <checkout>/..., <home>/..., <tmp>/... . The tools' own install
42
+ # locations become <lean-pkg>/... (this package's directory: its shipped scripts) and <elan>/... (ELAN_HOME, else
43
+ # ~/.elan: the lake that runs), wherever they are, so neither a private directory layout nor a home outside
44
+ # HOME is recorded, and the public-safety scan has no install path to warn about. An evidence
45
+ # directory outside the checkout (--evidence-dir) becomes <evidence>/...: the toolchain judge of a
46
+ # partial unit (--unit-size, --judges > 1, a resumed run) is handed a configuration copy under it.
47
+ # Hashes and bindings cover the tree's bytes, not where it was checked out, so nothing they bind changes.
48
+
49
+ _REDACT: list[tuple[re.Pattern, str]] = []
50
+ _PATH_TAIL = r"(?![A-Za-z0-9_.\-])" # the prefix must end at a path boundary (/home/u, not /home/u2)
51
+
52
+
53
+ def tool_dirs() -> tuple[str, str | None]:
54
+ """(lean-pkg's package directory, elan's home or None when there is none)."""
55
+ elan = os.environ.get("ELAN_HOME") or os.path.join(os.path.expanduser("~"), ".elan")
56
+ return str(pathlib.Path(__file__).resolve().parent), (elan if os.path.isdir(elan) else None)
57
+
58
+
59
+ def set_redactions(checkout: pathlib.Path | None, home: str | None = None, tmp: str | None = None,
60
+ evidence: pathlib.Path | None = None, tools: bool = True) -> None:
61
+ """Configure redaction for this process: longest prefix first, real and as-given spellings.
62
+ An evidence directory inside the checkout is already covered by <checkout>/ and keeps that
63
+ spelling; one outside it becomes <evidence>, whatever else (HOME, TMPDIR) contains it."""
64
+ import tempfile
65
+ if evidence is not None and checkout is not None:
66
+ ev, co = os.path.realpath(evidence), os.path.realpath(checkout)
67
+ if ev == co or ev.startswith(co.rstrip("/") + "/"):
68
+ evidence = None
69
+ pairs: list[tuple[str, str]] = []
70
+ own, elan = tool_dirs() if tools else (None, None)
71
+ for value, tag in ((own, "<lean-pkg>"), (elan, "<elan>"),
72
+ (str(checkout) if checkout else None, "<checkout>"),
73
+ (str(evidence) if evidence else None, "<evidence>"),
74
+ (tmp if tmp is not None else (os.environ.get("TMPDIR") or tempfile.gettempdir()), "<tmp>"),
75
+ (home if home is not None else os.environ.get("HOME"), "<home>")):
76
+ if not value:
77
+ continue
78
+ for v in {value.rstrip("/"), os.path.realpath(value).rstrip("/")}:
79
+ if len(v) > 1:
80
+ pairs.append((v, tag))
81
+ pairs.sort(key=lambda p: -len(p[0]))
82
+ _REDACT[:] = [(re.compile(re.escape(v) + _PATH_TAIL), tag) for v, tag in pairs]
83
+
84
+
85
+ def redact(text: str) -> str:
86
+ for rx, tag in _REDACT:
87
+ text = rx.sub(tag, text)
88
+ return text
89
+
90
+
91
+ def redact_bytes(data: bytes) -> bytes:
92
+ return redact(data.decode("utf-8", "surrogateescape")).encode("utf-8", "surrogateescape") \
93
+ if _REDACT else data
94
+
95
+
96
+ def redact_json(obj):
97
+ if isinstance(obj, str):
98
+ return redact(obj)
99
+ if isinstance(obj, list):
100
+ return [redact_json(x) for x in obj]
101
+ if isinstance(obj, dict):
102
+ return {k: redact_json(v) for k, v in obj.items()}
103
+ return obj
104
+
105
+
106
+ class Interrupted(Exception):
107
+ """The runner received TERM/INT/HUP while judges were running."""
108
+
109
+ def __init__(self, signum: int):
110
+ super().__init__(f"interrupted by {signal.Signals(signum).name}")
111
+ self.signum = signum
112
+
113
+
114
+ def heartbeat_seconds() -> float:
115
+ try:
116
+ v = float(os.environ.get(HEARTBEAT_ENV) or DEFAULT_HEARTBEAT)
117
+ except ValueError:
118
+ v = DEFAULT_HEARTBEAT
119
+ return max(v, 0.05)
120
+
121
+
122
+ def line_buffered(cmd: list[str]) -> list[str]:
123
+ """cmd under `stdbuf -oL -eL` when stdbuf is on PATH (C-stdio and Lean output then flushes per line)."""
124
+ sb = shutil.which("stdbuf")
125
+ return [sb, "-oL", "-eL", *cmd] if sb else list(cmd)
126
+
127
+
128
+ def human_bytes(n: int) -> str:
129
+ for unit in ("B", "KB", "MB", "GB"):
130
+ if n < 1024 or unit == "GB":
131
+ return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
132
+ n /= 1024
133
+ return f"{n} B"
134
+
135
+
136
+ def dir_bytes(d: pathlib.Path | None) -> tuple[int, int]:
137
+ """(total bytes, file count) under d; (0, 0) when absent."""
138
+ total = count = 0
139
+ if d is None or not d.is_dir():
140
+ return 0, 0
141
+ for root, _dirs, files in os.walk(d):
142
+ for f in files:
143
+ try:
144
+ total += os.lstat(os.path.join(root, f)).st_size
145
+ count += 1
146
+ except OSError:
147
+ pass
148
+ return total, count
149
+
150
+
151
+ class StageLog:
152
+ """The stage log, shared by every judge thread: each write is one locked, flushed append."""
153
+
154
+ def __init__(self, path: pathlib.Path, echo=None):
155
+ self.path, self.echo = path, echo
156
+ self.lock = threading.Lock()
157
+ self.fh = open(path, "ab", buffering=0)
158
+
159
+ def write(self, text: str | bytes) -> None:
160
+ data = text.encode("utf-8", "replace") if isinstance(text, str) else text
161
+ data = redact_bytes(data)
162
+ if not data.endswith(b"\n"):
163
+ data += b"\n"
164
+ with self.lock:
165
+ self.fh.write(data)
166
+ if self.echo is not None:
167
+ try:
168
+ self.echo.write(data.decode("utf-8", "replace"))
169
+ self.echo.flush()
170
+ except (OSError, ValueError):
171
+ pass
172
+
173
+ def close(self) -> None:
174
+ self.fh.close()
175
+
176
+
177
+ class Judge:
178
+ """One judge process; see the module docstring for the wiring."""
179
+
180
+ def __init__(self, cmd: list[str], cwd: pathlib.Path, env: dict, log: pathlib.Path | None,
181
+ stage: StageLog, label: str, prefix: str = "", tmpdir: pathlib.Path | None = None,
182
+ preexec=None):
183
+ self.cmd, self.cwd, self.env, self.log = cmd, cwd, dict(env), log
184
+ self.preexec = preexec # run in the child before exec (the stack limit, #52), or None
185
+ self.stage, self.label, self.prefix, self.tmpdir = stage, label, prefix, tmpdir
186
+ self.proc: subprocess.Popen | None = None
187
+ self.reader: threading.Thread | None = None
188
+ self.started = self.last_output = self.last_beat = 0.0
189
+ self.returncode: int | None = None
190
+ self.killed = False
191
+ self.last_line = ""
192
+
193
+ def start(self) -> None:
194
+ self.env["PYTHONUNBUFFERED"] = "1"
195
+ if self.tmpdir is not None:
196
+ self.tmpdir.mkdir(parents=True, exist_ok=True)
197
+ self.env["TMPDIR"] = str(self.tmpdir)
198
+ self.logfh = None # log None: the stage log is the only sink (setup stages)
199
+ if self.log is not None:
200
+ self.log.parent.mkdir(parents=True, exist_ok=True)
201
+ self.logfh = open(self.log, "ab", buffering=0) # copied into .lean-receipts: no paths added
202
+ self.stage.write(self.prefix + "$ " + " ".join(self.cmd))
203
+ self.started = self.last_output = self.last_beat = time.monotonic()
204
+ try:
205
+ self.proc = subprocess.Popen(line_buffered(self.cmd), cwd=self.cwd, env=self.env,
206
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
207
+ stderr=subprocess.STDOUT, start_new_session=True, bufsize=0,
208
+ preexec_fn=self.preexec)
209
+ except OSError as e:
210
+ msg = f"error: cannot run {self.cmd[0]}: {e}"
211
+ if self.logfh is not None:
212
+ self.logfh.write(redact_bytes((msg + "\n").encode()))
213
+ self.logfh.close()
214
+ self.stage.write(self.prefix + msg)
215
+ self.returncode = 127
216
+ return
217
+ self.reader = threading.Thread(target=self._pump, daemon=True)
218
+ self.reader.start()
219
+
220
+ def _pump(self) -> None:
221
+ assert self.proc is not None and self.proc.stdout is not None
222
+ for raw in iter(self.proc.stdout.readline, b""):
223
+ self.last_output = time.monotonic()
224
+ raw = redact_bytes(raw)
225
+ if self.logfh is not None:
226
+ self.logfh.write(raw)
227
+ line = raw.decode("utf-8", "replace").rstrip("\n")
228
+ if line.strip():
229
+ self.last_line = line.strip()[:160]
230
+ self.stage.write(self.prefix + line)
231
+ self.proc.stdout.close()
232
+
233
+ def poll(self) -> int | None:
234
+ if self.returncode is not None:
235
+ return self.returncode
236
+ assert self.proc is not None
237
+ rc = self.proc.poll()
238
+ if rc is None:
239
+ return None
240
+ if self.reader is not None:
241
+ self.reader.join()
242
+ if self.logfh is not None:
243
+ self.logfh.close()
244
+ self.returncode = rc
245
+ return rc
246
+
247
+ def beat(self, every: float) -> None:
248
+ now = time.monotonic()
249
+ if now - self.last_output < every or now - self.last_beat < every:
250
+ return
251
+ self.last_beat = now
252
+ size, n = dir_bytes(self.tmpdir)
253
+ tmp = f"; judge temp files {human_bytes(size)} in {n}" if n else ""
254
+ last = f'; last line: "{self.last_line}"' if self.last_line else ""
255
+ self.stage.write(f"heartbeat: {self.label} running {now - self.started:.0f}s, "
256
+ f"judge silent {now - self.last_output:.0f}s{tmp}{last}")
257
+
258
+ def kill(self) -> None:
259
+ """TERM the judge's process group, KILL it after KILL_GRACE seconds."""
260
+ if self.proc is None or self.returncode is not None:
261
+ return
262
+ self.killed = True
263
+ for sig, grace in ((signal.SIGTERM, KILL_GRACE), (signal.SIGKILL, 5.0)):
264
+ try:
265
+ os.killpg(self.proc.pid, sig)
266
+ except (ProcessLookupError, PermissionError):
267
+ break
268
+ try:
269
+ self.proc.wait(timeout=grace)
270
+ break
271
+ except subprocess.TimeoutExpired:
272
+ continue
273
+ try:
274
+ self.proc.wait(timeout=5)
275
+ except subprocess.TimeoutExpired:
276
+ pass
277
+ self.poll()
278
+
279
+ def elapsed(self) -> float:
280
+ return time.monotonic() - self.started
281
+
282
+
283
+ class SignalGuard:
284
+ """Turns TERM/INT/HUP into Interrupted in the main thread for the duration of a with-block."""
285
+
286
+ SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)
287
+
288
+ def __enter__(self):
289
+ self.old = {}
290
+ for s in self.SIGNALS:
291
+ try:
292
+ self.old[s] = signal.signal(s, self._raise)
293
+ except (ValueError, OSError): # not the main thread: leave the defaults alone
294
+ pass
295
+ return self
296
+
297
+ @staticmethod
298
+ def _raise(signum, _frame):
299
+ raise Interrupted(signum)
300
+
301
+ def __exit__(self, *exc):
302
+ for s, h in self.old.items():
303
+ try:
304
+ signal.signal(s, h)
305
+ except (ValueError, OSError):
306
+ pass
307
+ return False
308
+
309
+
310
+ def run_pool(jobs: list, width: int, start, finish, poll_interval: float = 0.2) -> None:
311
+ """Run jobs, at most `width` at a time. start(job) -> Judge (already started); finish(job, judge)
312
+ -> bool (False stops launching new jobs and kills the running ones). Heartbeats while waiting.
313
+ On Interrupted (or any exception) every running judge's process group is killed, then it re-raises."""
314
+ every = heartbeat_seconds()
315
+ pending = list(jobs)
316
+ running: list[tuple[object, Judge]] = []
317
+ stop = False
318
+ try:
319
+ while pending or running:
320
+ while pending and not stop and len(running) < max(1, width):
321
+ job = pending.pop(0)
322
+ running.append((job, start(job)))
323
+ if stop and not running:
324
+ break
325
+ done = [(j, jd) for j, jd in running if jd.poll() is not None]
326
+ for j, jd in done:
327
+ running.remove((j, jd))
328
+ if not finish(j, jd):
329
+ stop = True
330
+ if stop:
331
+ for _j, jd in running:
332
+ jd.kill()
333
+ for j, jd in running:
334
+ finish(j, jd)
335
+ running = []
336
+ break
337
+ if not done:
338
+ for _j, jd in running:
339
+ jd.beat(every)
340
+ time.sleep(min(poll_interval, every))
341
+ except BaseException:
342
+ for _j, jd in running:
343
+ jd.kill()
344
+ raise
345
+
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # Slots and units. A slot is one theorem_names entry of one configuration, numbered 1..N across
349
+ # the configurations in order. A unit is what one judge invocation judges: a configuration (or a
350
+ # subset of its slots: a --judges shard or a --unit-size chunk). Progress lines name slots; 04-comparator.partial.json names the slots done,
351
+ # pending and failed, rewritten after every unit so even a SIGKILL leaves it current.
352
+
353
+ PARTIAL_FILE = "04-comparator.partial.json"
354
+ PARTIAL_SCHEMA = "comparator-partial/1"
355
+ UNITS_DIR = "04-units"
356
+
357
+
358
+ @dataclasses.dataclass(frozen=True)
359
+ class Slot:
360
+ index: int # 1-based, global over the configurations in order
361
+ config: str
362
+ name: str
363
+
364
+ def row(self) -> dict:
365
+ return {"slot": self.index, "config": self.config, "name": self.name}
366
+
367
+
368
+ @dataclasses.dataclass
369
+ class Unit:
370
+ n: int
371
+ config: str # "" for a judge that takes every configuration at once (legacy)
372
+ slots: list
373
+ whole: bool # judges the configuration file itself, not a partial copy
374
+ id: str = ""
375
+
376
+ def label(self) -> str:
377
+ if len(self.slots) == 1:
378
+ return self.slots[0].name
379
+ return f"{self.config or 'all configs'}[{len(self.slots)} names]"
380
+
381
+
382
+ def list_slots(cfgs: list[tuple[str, dict]]) -> list[Slot]:
383
+ out: list[Slot] = []
384
+ for rel, cfg in cfgs:
385
+ for name in cfg.get("theorem_names") or []:
386
+ out.append(Slot(len(out) + 1, rel, str(name)))
387
+ return out
388
+
389
+
390
+ def ranges(indices) -> str:
391
+ """[1,2,3,7,9,10] -> '1-3,7,9-10'."""
392
+ xs = sorted(set(indices))
393
+ parts, i = [], 0
394
+ while i < len(xs):
395
+ j = i
396
+ while j + 1 < len(xs) and xs[j + 1] == xs[j] + 1:
397
+ j += 1
398
+ parts.append(str(xs[i]) if i == j else f"{xs[i]}-{xs[j]}")
399
+ i = j + 1
400
+ return ",".join(parts)
401
+
402
+
403
+ def unit_id(binding: dict, unit: Unit) -> str:
404
+ key = [binding.get("commit"), binding.get("config_hash"), unit.config, unit.whole,
405
+ [s.name for s in unit.slots]]
406
+ return hashlib.sha256(json.dumps(key).encode()).hexdigest()[:16]
407
+
408
+
409
+ class Progress:
410
+ """Slots done / pending / failed for one stage-04 run, mirrored to the partial report."""
411
+
412
+ def __init__(self, path: pathlib.Path, slots: list[Slot], meta: dict):
413
+ self.path, self.slots, self.meta = path, slots, dict(meta)
414
+ self.done: dict[int, str] = {} # slot index -> how ("judged" | "cached")
415
+ self.failed: set[int] = set()
416
+ self.state = "running"
417
+
418
+ def mark(self, slots, how: str) -> None:
419
+ for s in slots:
420
+ if how == "failed":
421
+ self.failed.add(s.index)
422
+ else:
423
+ self.done[s.index] = how
424
+ self.failed.discard(s.index)
425
+
426
+ def counts(self) -> dict:
427
+ return {"done": len(self.done), "total": len(self.slots), "failed": len(self.failed)}
428
+
429
+ def write(self) -> None:
430
+ pend = [s.row() for s in self.slots if s.index not in self.done and s.index not in self.failed]
431
+ data = {"schema": PARTIAL_SCHEMA, **self.meta, "state": self.state, **self.counts(),
432
+ "slots_done": [{**s.row(), "how": self.done[s.index]} for s in self.slots
433
+ if s.index in self.done],
434
+ "slots_pending": pend,
435
+ "slots_failed": [s.row() for s in self.slots if s.index in self.failed],
436
+ "updated_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")}
437
+ tmp = self.path.with_name(self.path.name + ".tmp")
438
+ tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
439
+ os.replace(tmp, self.path)
440
+
441
+ def summary(self) -> str:
442
+ c = self.counts()
443
+ return f"partial: {c['done']}/{c['total']} done" + (f", {c['failed']} failed" if c["failed"] else "")
444
+
445
+
446
+ # ---------------------------------------------------------------------------
447
+ # Resume (#39): a slot judged and accepted is cached under 04-slots/<slot-hash>.json, keyed by
448
+ # everything that decides its verdict: commit, config hash (every configuration's path and bytes),
449
+ # lean-toolchain, mechanism, the judge script's digest, the configuration path and the slot name, and
450
+ # the olean manifest's digest when the setup recorded one (the compiled modules the judge read).
451
+ # The unit log that accepted it is kept content-addressed in 04-slots/logs/ and re-checked (digest
452
+ # and PASS line) before a cached slot is trusted; anything missing or different is judged again.
453
+
454
+ SLOTS_DIR = "04-slots"
455
+ SLOT_SCHEMA = "comparator-slot/1"
456
+
457
+
458
+ def slot_key(binding: dict, mechanism: str, judge_sha256: str, slot: Slot) -> dict:
459
+ key = {"commit": binding.get("commit"), "config_hash": binding.get("config_hash"),
460
+ "lean_toolchain": binding.get("lean_toolchain"), "mechanism": mechanism,
461
+ "judge_sha256": judge_sha256, "config": slot.config, "name": slot.name}
462
+ if binding.get("olean_manifest_sha256"): # the oleans the slot was judged against (olean manifest)
463
+ key["olean_manifest_sha256"] = binding["olean_manifest_sha256"]
464
+ return key
465
+
466
+
467
+ def slot_hash(key: dict) -> str:
468
+ return hashlib.sha256(json.dumps(key, sort_keys=True).encode()).hexdigest()[:24]
469
+
470
+
471
+ class SlotCache:
472
+ def __init__(self, root: pathlib.Path, binding: dict, mechanism: str, judge_sha256: str, accept):
473
+ self.root, self.binding, self.mechanism, self.judge = root, binding, mechanism, judge_sha256
474
+ self.accept = accept # accept(log_text) -> bool: the PASS predicate
475
+
476
+ def path(self, slot: Slot) -> pathlib.Path:
477
+ return self.root / f"{slot_hash(slot_key(self.binding, self.mechanism, self.judge, slot))}.json"
478
+
479
+ def get(self, slot: Slot) -> dict | None:
480
+ """The cache entry for slot when it is valid for this run, else None."""
481
+ try:
482
+ e = json.loads(self.path(slot).read_text(encoding="utf-8"))
483
+ except (OSError, ValueError):
484
+ return None
485
+ if not isinstance(e, dict) or e.get("schema") != SLOT_SCHEMA or e.get("result") != "pass" \
486
+ or e.get("key") != slot_key(self.binding, self.mechanism, self.judge, slot):
487
+ return None
488
+ log = self.root / str(e.get("log") or "")
489
+ try:
490
+ data = log.read_bytes()
491
+ except OSError:
492
+ return None
493
+ if hashlib.sha256(data).hexdigest() != e.get("log_sha256") \
494
+ or not self.accept(data.decode("utf-8", "replace")):
495
+ return None
496
+ e["log_path"] = log
497
+ return e
498
+
499
+ def put(self, slots: list[Slot], log: pathlib.Path, whole: bool, wall: float) -> None:
500
+ data = log.read_bytes()
501
+ digest = hashlib.sha256(data).hexdigest()
502
+ logs = self.root / "logs"
503
+ logs.mkdir(parents=True, exist_ok=True)
504
+ dst = logs / f"{digest}.log"
505
+ if not dst.exists():
506
+ tmp = dst.with_name(dst.name + ".tmp")
507
+ tmp.write_bytes(data)
508
+ os.replace(tmp, dst)
509
+ now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
510
+ for s in slots:
511
+ entry = {"schema": SLOT_SCHEMA, "key": slot_key(self.binding, self.mechanism, self.judge, s),
512
+ "result": "pass", "slot": s.index, "unit_slots": [x.name for x in slots],
513
+ "whole": whole, "log": f"logs/{digest}.log", "log_sha256": digest,
514
+ "wall_s": round(wall, 3), "judged_at": now}
515
+ p = self.path(s)
516
+ tmp = p.with_name(p.name + ".tmp")
517
+ tmp.write_text(json.dumps(entry, indent=2) + "\n", encoding="utf-8")
518
+ os.replace(tmp, p)
519
+
520
+
521
+ JOBS_ENV = "LEAN_PKG_COMPARATOR_JOBS"
522
+
523
+
524
+ def shards(slots: list, n: int) -> list[list]:
525
+ """slots in min(n, len) contiguous chunks whose sizes differ by at most one (neighbouring
526
+ theorems usually share most of their export closure, so contiguity keeps shards cheaper)."""
527
+ k = max(1, min(n, len(slots)))
528
+ q, r = divmod(len(slots), k)
529
+ out, i = [], 0
530
+ for c in range(k):
531
+ size = q + (1 if c < r else 0)
532
+ out.append(slots[i:i + size])
533
+ i += size
534
+ return out
535
+
536
+
537
+ UNIT_SIZE_ENV = "LEAN_PKG_COMPARATOR_UNIT_SIZE"
538
+
539
+
540
+ def chunks(slots: list, k: int) -> list[list]:
541
+ """slots in contiguous units of at most k names, in order (--unit-size K, #60): every unit but
542
+ the last has exactly k. Independent of the pool width, so `--unit-size 1` judges each name alone
543
+ and every accepted slot is cached as soon as its unit ends."""
544
+ k = max(1, k)
545
+ return [slots[i:i + k] for i in range(0, len(slots), k)]
546
+
547
+
548
+ # ---------------------------------------------------------------------------
549
+ # Slot subsets (--slots SPEC) and the stratified sample that --estimate and `sample:K` share.
550
+
551
+ def namespace(name: str) -> str:
552
+ return name.rsplit(".", 1)[0] if "." in name else ""
553
+
554
+
555
+ def stratified_sample(slots: list[Slot], k: int) -> list[Slot]:
556
+ """k slots spread across strata (configuration, namespace of the name: the closest proxy for the
557
+ module that the configuration itself carries): round-robin over the strata in order of first
558
+ appearance, each stratum yielding its slots in order. Deterministic; returned in slot order."""
559
+ strata: dict[tuple[str, str], list[Slot]] = {}
560
+ for s in slots:
561
+ strata.setdefault((s.config, namespace(s.name)), []).append(s)
562
+ queues = [list(v) for v in strata.values()]
563
+ out: list[Slot] = []
564
+ while len(out) < min(k, len(slots)):
565
+ for q in queues:
566
+ if q and len(out) < k:
567
+ out.append(q.pop(0))
568
+ return sorted(out, key=lambda s: s.index)
569
+
570
+
571
+ def weighted_sample(slots: list[Slot], k: int, weights: dict[int, int]) -> tuple[list[Slot], set[int]]:
572
+ """k slots for --estimate (#59): first the k_heavy = max(1, ceil(0.2 * k)) heaviest slots by weight
573
+ (weights: slot index -> bytes; only slots of positive weight count, ties to the lower index), then
574
+ the rest by stratified_sample over the remaining slots. Deterministic; returns (the sample in slot
575
+ order, the indices picked as heavy)."""
576
+ k = min(k, len(slots))
577
+ k_heavy = min(k, max(1, math.ceil(0.2 * k)))
578
+ ranked = sorted((s for s in slots if weights.get(s.index, 0) > 0),
579
+ key=lambda s: (-weights[s.index], s.index))
580
+ heavy = ranked[:k_heavy]
581
+ taken = {s.index for s in heavy}
582
+ rest = stratified_sample([s for s in slots if s.index not in taken], k - len(heavy))
583
+ return sorted(heavy + rest, key=lambda s: s.index), taken
584
+
585
+
586
+ def parse_slot_spec(spec: str, slots: list[Slot]) -> list[Slot]:
587
+ """SPEC: comma-separated tokens, each `sample:K`, an index `i` or range `i-j` (1-based, over all
588
+ configurations in order), a slot name, or `<config>:<name>`. Raises ValueError naming the token."""
589
+ picked: dict[int, Slot] = {}
590
+ by_name: dict[str, list[Slot]] = {}
591
+ for s in slots:
592
+ by_name.setdefault(s.name, []).append(s)
593
+ for tok in [t.strip() for t in spec.split(",")]:
594
+ if not tok:
595
+ continue
596
+ if tok.startswith("sample:"):
597
+ try:
598
+ k = int(tok[7:])
599
+ except ValueError:
600
+ k = 0
601
+ if k < 1:
602
+ raise ValueError(f"{tok!r}: sample:K needs a positive integer K")
603
+ for s in stratified_sample(slots, k):
604
+ picked[s.index] = s
605
+ elif tok.replace("-", "").isdigit() and tok.count("-") <= 1 and not tok.startswith("-"):
606
+ a, _, b = tok.partition("-")
607
+ lo, hi = int(a), int(b or a)
608
+ if not (1 <= lo <= hi <= len(slots)):
609
+ raise ValueError(f"{tok!r}: slot indices run 1..{len(slots)}")
610
+ for s in slots[lo - 1:hi]:
611
+ picked[s.index] = s
612
+ else:
613
+ cfg, sep, name = tok.rpartition(":") if ":" in tok else ("", "", tok)
614
+ hits = [s for s in by_name.get(name, []) if not sep or s.config == cfg]
615
+ if not hits:
616
+ raise ValueError(f"{tok!r}: no such slot (theorem_names entry)")
617
+ if len(hits) > 1:
618
+ raise ValueError(f"{tok!r} names a slot in several configurations "
619
+ f"({', '.join(s.config for s in hits)}); write <config>:{name}")
620
+ picked[hits[0].index] = hits[0]
621
+ if not picked:
622
+ raise ValueError("selects no slot")
623
+ return [picked[i] for i in sorted(picked)]