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,830 @@
1
+ # lean-pkg comparator config --challenge-from-type -- pre-fill Challenge/Solution from elaborated types
2
+ """Elaborated types for `comparator config --from-claims NAME --challenge-from-type` (#25).
3
+
4
+ Three modes share one code path:
5
+
6
+ - `--emit-script F` writes a self-contained driver (bash + python3) that, run from the package
7
+ checkout at the bound commit (`cd <checkout> && bash F out.json`), elaborates each declaration
8
+ with `lake env lean` and writes the JSON output contract below. Nothing runs here, so a
9
+ workstation never elaborates a large package; the script can go to a Slurm job.
10
+ - `--from-output F` reads that JSON (schema and commit checked) and fills the scaffold.
11
+ - `--challenge-from-type` alone is emit to a temp dir, run, then ingest.
12
+
13
+ Output contract (schema comparator-types/1), written by the driver to its first argument:
14
+
15
+ {"schema": "comparator-types/1", "package": NAME, "commit": "<40-hex HEAD>",
16
+ "toolchain": "<lean-toolchain contents or null>",
17
+ "results": [{"decl": D, "type": T|null, "status": "ok"|"error", "error": E|null,
18
+ "levels": [..], "modules": [..]}]}
19
+
20
+ `levels` (the declaration's universe parameters) and `modules` (modules of the constants its type
21
+ mentions) are additive; an ingested result without `modules` is marked `needs_restatement`.
22
+ Also additive: `summary` {ok, total, filled, errors, round_trip_failed, declaration_errors, jobs,
23
+ backoff} and per result `rc`, `failure` (declaration | resource | extraction | round_trip),
24
+ `output_tail`, `round_trip` ("ok" | "failed") and `round_trip_rc` (#30, #31). A result is `ok` only
25
+ when its printed type passed the round-trip check (ROUNDTRIP_SNIPPET). Also additive (field report
26
+ #5): per result `round_trip_exact` (true when the re-elaborated type is syntactically the
27
+ declaration's, `#guard_expr ... =ₛ ...`; false when it is only definitionally equal, with
28
+ `round_trip_exact_error`), and `summary.round_trip_inexact` / `summary.resumed`. Also additive
29
+ (#160): `round_trip_variant` / `round_trip_open` when the text that passed is the
30
+ fallback (printed with pp.coercions.types, or checked under `open scoped Classical`), and
31
+ `summary.round_trip_variant`.
32
+
33
+ The driver prints `[k/N] DECL ok|fail` progress lines to stderr and appends every finished result
34
+ to `OUT.json.checkpoint.jsonl`; a rerun with the same OUT.json (same package, commit and snippets)
35
+ reuses the settled results there and runs only the rest (LEAN_PKG_TYPES_RESUME=0 starts afresh). The
36
+ checkpoint is removed once a run ends with no extraction failure.
37
+
38
+ The driver writes only to a temp dir (its Lean scratch files), the output path and its checkpoint
39
+ beside it; it never writes into the checkout.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import json
45
+ import os
46
+ import pathlib
47
+ import re
48
+ import shutil
49
+ import subprocess
50
+ import tempfile
51
+
52
+ from . import cli, gate as gate_mod
53
+ from . import core
54
+ from . import statements_module as stm
55
+
56
+ SCHEMA = "comparator-types/1"
57
+ DEFAULT_JOBS = 2
58
+ DEFAULT_TIMEOUT = 120
59
+ # Module roots a Challenge may use: it imports Mathlib, which brings these in (one list, statements_module's).
60
+ VOCAB_ROOTS = stm.VOCAB_ROOTS
61
+ UNPARSEABLE = ("✝", "⋯") # inaccessible-name dagger, elided-proof ellipsis
62
+ DECL_RE = re.compile(r"^[^\s«».]+(\.[^\s«».]+)*$")
63
+ LAKEFILES = ("lakefile.lean", "lakefile.toml")
64
+
65
+ # The Lean the driver writes for each declaration; it fills in __IMPORTS__ and __NAME__.
66
+ LEAN_SNIPPET = """\
67
+ __IMPORTS__
68
+ import Lean
69
+ set_option pp.fullNames true
70
+ set_option pp.proofs true
71
+ set_option pp.analyze true
72
+ set_option pp.numericTypes true
73
+ set_option pp.funBinderTypes true
74
+ open Lean Elab Command in
75
+ #eval show CommandElabM Unit from do
76
+ let env ← getEnv
77
+ let n : Name := __NAME__
78
+ match env.find? n with
79
+ | none => IO.println s!"LEANPKG-ERROR unknown constant {n}"
80
+ | some ci =>
81
+ let fmt ← liftTermElabM (Meta.ppExpr ci.type)
82
+ let alt ← liftTermElabM (withOptions (·.setBool `pp.coercions.types true) (Meta.ppExpr ci.type))
83
+ let mods := ci.type.getUsedConstants.toList.filterMap fun c =>
84
+ (env.getModuleIdxFor? c).map fun i => (env.header.moduleNames[i.toNat]!).toString
85
+ IO.println s!"LEANPKG-LEVELS {String.intercalate "," (ci.levelParams.map toString)}"
86
+ IO.println s!"LEANPKG-MODULES {String.intercalate "," mods.eraseDups}"
87
+ IO.println "LEANPKG-TYPE-BEGIN"
88
+ IO.println (fmt.pretty 100)
89
+ IO.println "LEANPKG-TYPE-END"
90
+ IO.println "LEANPKG-ALT-BEGIN"
91
+ IO.println (alt.pretty 100)
92
+ IO.println "LEANPKG-ALT-END"
93
+ """
94
+
95
+ # The round-trip check (#31): the printed type must elaborate, in the declaration's own module context
96
+ # with no auto-bound implicits, to a type the declaration itself inhabits (defeq). Exit status decides.
97
+ # The `#guard_expr` after it (field report #5) asks more: the re-elaborated type is syntactically the
98
+ # declaration's (`=ₛ`, Expr equality after instantiating metavariables). An error only at or after the
99
+ # LEANPKG-EXACT line means defeq but not syntactically equal (round_trip_exact false).
100
+ ROUNDTRIP_SNIPPET = """\
101
+ __IMPORTS__
102
+ set_option autoImplicit false
103
+ -- LEANPKG-ROUNDTRIP __DECL__
104
+ __UNIVERSES__
105
+ example :
106
+ (__TYPE__) :=
107
+ @_root_.__IDENT__
108
+ -- LEANPKG-EXACT
109
+ #guard_expr
110
+ (__TYPE__) =ₛ type_of% @_root_.__IDENT____LEVELS__
111
+ """
112
+
113
+ DRIVER_PY = r'''
114
+ import concurrent.futures, errno, hashlib, json, os, pathlib, re, shutil, subprocess, sys, tempfile, time
115
+
116
+ CONFIG = json.loads(__CONFIG__)
117
+ DEFAULT_JOBS = CONFIG["default_jobs"]
118
+ SNIPPET = CONFIG["snippet"]
119
+ ROUNDTRIP = CONFIG["roundtrip_snippet"]
120
+ SIMPLE = re.compile(r"^[A-Za-z_][A-Za-z0-9_']*$")
121
+ DIAG = re.compile(r"^.*?:\d+:\d+: (error|warning|info)(\([^)]*\))?: ?")
122
+ ERRLINE = re.compile(r"^.*?:(\d+):\d+: error")
123
+ CHECKPOINT = "comparator-types-checkpoint/1"
124
+ SETTLED = (None, "declaration", "round_trip") # failures a rerun would only repeat
125
+ # File-table exhaustion (ENFILE 23 / EMFILE 24), common with many Lean processes on Lustre/NFS (#30).
126
+ RESOURCE = re.compile(r"too many open files|\bENFILE\b|\bEMFILE\b", re.I)
127
+ RESOURCE_ERRNOS = (errno.ENFILE, errno.EMFILE)
128
+ # A proposition Lean could not decide in the round trip: the declaration was stated under `open Classical`.
129
+ DECIDABLE = re.compile(r"failed to synthesize[^\n]*\n?[^\n]*\bDecidable\b")
130
+ CLASSICAL = "open scoped Classical\n"
131
+
132
+
133
+ def refuse(msg):
134
+ sys.stderr.write("lean-pkg types: " + msg + "\n")
135
+ sys.exit(2)
136
+
137
+
138
+ def lean_ident(dotted):
139
+ return ".".join(p if SIMPLE.match(p) else "«" + p + "»" for p in dotted.split("."))
140
+
141
+
142
+ def lean_name(dotted):
143
+ expr = "Name.anonymous"
144
+ for p in dotted.split("."):
145
+ expr = "(" + expr + ").str " + json.dumps(p, ensure_ascii=True)
146
+ return "(" + expr + ")"
147
+
148
+
149
+ def elan_bin():
150
+ home = os.environ.get("ELAN_HOME", "").strip()
151
+ return pathlib.Path(home) if home else pathlib.Path.home() / ".elan"
152
+
153
+
154
+ def is_elan(tool):
155
+ where = shutil.which(tool)
156
+ if where is None:
157
+ return None
158
+ p, proxy = pathlib.Path(where), elan_bin() / "bin" / tool
159
+ if p.parent.resolve() == proxy.parent.resolve():
160
+ return True
161
+ return proxy.exists() and p.resolve() == proxy.resolve()
162
+
163
+
164
+ def parse(out):
165
+ """(type, levels, modules, error) from the driver snippet's stdout+stderr."""
166
+ lines = [DIAG.sub("", l) if DIAG.match(l) and "LEANPKG-" in l else l for l in out.splitlines()]
167
+ levels = modules = None
168
+ body, inside, err = [], False, None
169
+ for l in lines:
170
+ s = l.strip()
171
+ if inside:
172
+ if s == "LEANPKG-TYPE-END":
173
+ inside = False
174
+ continue
175
+ body.append(l.rstrip())
176
+ elif s.startswith("LEANPKG-ERROR"):
177
+ err = s[len("LEANPKG-ERROR"):].strip() or "unknown constant"
178
+ elif s.startswith("LEANPKG-LEVELS"):
179
+ levels = [x for x in s[len("LEANPKG-LEVELS"):].strip().split(",") if x]
180
+ elif s.startswith("LEANPKG-MODULES"):
181
+ modules = [x for x in s[len("LEANPKG-MODULES"):].strip().split(",") if x]
182
+ elif s == "LEANPKG-TYPE-BEGIN":
183
+ inside = True
184
+ text = "\n".join(body).strip()
185
+ if text and not inside and err is None:
186
+ return text, levels or [], modules, None
187
+ if err is None:
188
+ for l in out.splitlines():
189
+ m = DIAG.match(l)
190
+ if m and m.group(1) == "error":
191
+ err = l[m.end():].strip() or l.strip()
192
+ break
193
+ if err is None:
194
+ first = [l.strip() for l in out.splitlines() if l.strip()]
195
+ err = first[0] if first else "no output"
196
+ return None, None, None, err
197
+
198
+
199
+ def tail(out, n=5, cap=800):
200
+ """The last `n` non-blank lines of `out`, at most `cap` characters."""
201
+ t = "\n".join([l.rstrip() for l in out.splitlines() if l.strip()][-n:])
202
+ return t[-cap:]
203
+
204
+
205
+ def one(entry, work, lake_dir, timeout):
206
+ """One declaration -> result. `failure` says why a result is not ok: `declaration` (Lean ran and
207
+ reported the declaration missing, or the claim names no module: not retried, not an extraction
208
+ error), `resource` (the file table was exhausted: retried with fewer workers, an extraction error
209
+ if it persists) or `extraction` (Lean did not run to completion: exit status, timeout, OS error)."""
210
+ decl, module = entry["decl"], entry.get("module")
211
+ res = {"decl": decl, "type": None, "status": "error", "error": None, "levels": [], "modules": [],
212
+ "rc": None, "failure": "extraction"}
213
+ if not module:
214
+ res.update(error="no Lean module for the claim's file " + str(entry.get("file")), failure="declaration")
215
+ return res
216
+ src = SNIPPET.replace("__IMPORTS__", "import " + lean_ident(module)).replace("__NAME__", lean_name(decl))
217
+ f = pathlib.Path(work) / ("d%05d.lean" % entry["index"])
218
+ try:
219
+ f.write_text(src, encoding="utf-8")
220
+ p = subprocess.run(["lake", "env", "lean", str(f)], cwd=lake_dir, stdin=subprocess.DEVNULL,
221
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
222
+ except subprocess.TimeoutExpired:
223
+ res["error"] = "timed out after %ss" % timeout
224
+ return res
225
+ except OSError as e:
226
+ res["error"] = "cannot run lake: %s" % e
227
+ if e.errno in RESOURCE_ERRNOS:
228
+ res["failure"] = "resource"
229
+ return res
230
+ out = p.stdout.decode("utf-8", "replace")
231
+ res["rc"] = p.returncode
232
+ typ, levels, modules, err = parse(out)
233
+ if p.returncode != 0 or typ is None:
234
+ res["error"] = err
235
+ res["output_tail"] = tail(out)
236
+ if p.returncode == 0 and any(l.strip().startswith("LEANPKG-ERROR") for l in out.splitlines()):
237
+ res["failure"] = "declaration"
238
+ elif p.returncode != 0 and typ is not None:
239
+ res["error"] = "lake env lean exited %d after printing the type: %s" % (
240
+ p.returncode, tail(out, 1) or "no output")
241
+ if res["failure"] == "extraction" and RESOURCE.search(out):
242
+ res["failure"] = "resource"
243
+ return res
244
+ res.update(type=typ, levels=levels)
245
+ if modules is None:
246
+ res.pop("modules")
247
+ else:
248
+ res["modules"] = modules
249
+ alt = alt_text(out)
250
+ if alt:
251
+ res["alt_type"] = alt
252
+ return round_trip(res, entry, module, work, lake_dir, timeout)
253
+
254
+
255
+ def alt_text(out):
256
+ """The LEANPKG-ALT block (the type printed with pp.coercions.types as well), or None."""
257
+ body, inside = [], False
258
+ for l in out.splitlines():
259
+ s = l.strip()
260
+ if s == "LEANPKG-ALT-BEGIN":
261
+ body, inside = [], True
262
+ elif s == "LEANPKG-ALT-END" and inside:
263
+ text = "\n".join(body).strip()
264
+ return text or None
265
+ elif inside:
266
+ body.append(l.rstrip())
267
+ return None
268
+
269
+
270
+ def rt_attempt(res, typ, entry, module, work, lake_dir, timeout, n, classical):
271
+ """One round-trip run of the printed text `typ` -> (outcome, fields, output); outcome is exact,
272
+ defeq, failed or abort (timed out, OS error, file table exhausted: not a verdict on the text)."""
273
+ src = (ROUNDTRIP.replace("__IMPORTS__", "import " + lean_ident(module))
274
+ .replace("__DECL__", res["decl"])
275
+ .replace("__UNIVERSES__", ("universe " + " ".join(res["levels"])) if res["levels"] else "")
276
+ .replace("__LEVELS__", (".{" + ", ".join(res["levels"]) + "}") if res["levels"] else "")
277
+ .replace("__IDENT__", lean_ident(res["decl"]))
278
+ .replace("__TYPE__", typ.replace("\n", "\n ")))
279
+ if classical:
280
+ src = src.replace("set_option autoImplicit false\n", "set_option autoImplicit false\n" + CLASSICAL)
281
+ marks = [i for i, l in enumerate(src.splitlines(), 1) if l.strip() == "-- LEANPKG-EXACT"]
282
+ exact_from = marks[0] if marks else None
283
+ f = pathlib.Path(work) / ("r%05d%s.lean" % (entry["index"], "" if n == 0 else "-%d" % n))
284
+ try:
285
+ f.write_text(src, encoding="utf-8")
286
+ p = subprocess.run(["lake", "env", "lean", str(f)], cwd=lake_dir, stdin=subprocess.DEVNULL,
287
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
288
+ except subprocess.TimeoutExpired:
289
+ return "abort", {"error": "round-trip check timed out after %ss" % timeout}, ""
290
+ except OSError as e:
291
+ fields = {"error": "cannot run lake for the round-trip check: %s" % e}
292
+ if e.errno in RESOURCE_ERRNOS:
293
+ fields["failure"] = "resource"
294
+ return "abort", fields, ""
295
+ out = p.stdout.decode("utf-8", "replace")
296
+ if p.returncode == 0:
297
+ fields = {"round_trip_rc": 0, "status": "ok", "failure": None, "round_trip": "ok"}
298
+ if exact_from is not None:
299
+ fields["round_trip_exact"] = True
300
+ return "exact", fields, out
301
+ errs = [int(m.group(1)) for m in (ERRLINE.match(l) for l in out.splitlines()) if m]
302
+ if exact_from is not None and errs and min(errs) > exact_from and not RESOURCE.search(out):
303
+ # The `example` elaborated (defeq), only the syntactic `#guard_expr` failed.
304
+ lines = [l.rstrip() for l in out.splitlines() if l.strip()]
305
+ first = next(i for i, l in enumerate(lines) if ERRLINE.match(l))
306
+ msg = " | ".join([DIAG.sub("", lines[first])] + lines[first + 1:first + 4])
307
+ return "defeq", {"round_trip_rc": p.returncode, "status": "ok", "failure": None, "round_trip": "ok",
308
+ "round_trip_exact": False, "round_trip_exact_error": msg[:800]}, out
309
+ if RESOURCE.search(out):
310
+ return "abort", {"round_trip_rc": p.returncode, "output_tail": tail(out),
311
+ "error": "round-trip check: " + tail(out, 1), "failure": "resource"}, out
312
+ lines = [l.rstrip() for l in out.splitlines() if l.strip()]
313
+ first = next((i for i, l in enumerate(lines) if DIAG.match(l) and DIAG.match(l).group(1) == "error"), 0)
314
+ msg = [DIAG.sub("", lines[first])] + lines[first + 1:first + 8] if lines else ["no output"]
315
+ return "failed", {"round_trip_rc": p.returncode, "output_tail": tail(out), "round_trip": "failed",
316
+ "failure": "round_trip",
317
+ "error": ("round-trip check failed (exit %d): %s" % (p.returncode, " | ".join(msg)))[:800]}, out
318
+
319
+
320
+ RANK = {"exact": 2, "defeq": 1, "failed": 0}
321
+
322
+
323
+ def round_trip(res, entry, module, work, lake_dir, timeout):
324
+ """Re-elaborate the printed type against the declaration (#31); only a pass makes the result ok.
325
+ When the first text is not syntactically exact, the fallbacks run in order (field report #5): the
326
+ text printed with pp.coercions.types, then, if Lean could not decide a proposition, both texts again
327
+ under `open scoped Classical`. The first exact attempt wins, else the best (defeq over failed, an
328
+ earlier one on a tie); `type` is the text that passed and `round_trip_variant` names what was added."""
329
+ primary = res["type"]
330
+ alt = res.pop("alt_type", None)
331
+ tries = [(primary, False)] + ([(alt, False)] if alt and alt != primary else [])
332
+ best, i, classical_added = None, 0, False
333
+ while i < len(tries):
334
+ typ, classical = tries[i]
335
+ outcome, fields, out = rt_attempt(res, typ, entry, module, work, lake_dir, timeout, i, classical)
336
+ if outcome == "abort":
337
+ if best is None or best[0] == "failed": # not a verdict: report it, so a rerun repeats it
338
+ res.update(fields)
339
+ return res
340
+ break
341
+ if best is None or RANK[outcome] > RANK[best[0]]:
342
+ best = (outcome, fields, typ, classical)
343
+ if outcome == "exact":
344
+ break
345
+ if not classical_added and outcome == "failed" and DECIDABLE.search(out):
346
+ classical_added = True
347
+ tries += [(t, True) for t, _ in tries if (t, True) not in tries]
348
+ i += 1
349
+ outcome, fields, typ, classical = best
350
+ res.update(fields)
351
+ variant = [v for v, on in (("pp.coercions.types", typ != primary), ("open scoped Classical", classical)) if on]
352
+ if variant and outcome != "failed":
353
+ res["type"] = typ
354
+ res["round_trip_variant"] = "; ".join(variant)
355
+ if classical:
356
+ res["round_trip_open"] = "Classical"
357
+ return res
358
+
359
+
360
+ def safe_one(entry, work, lake_dir, timeout):
361
+ try:
362
+ return one(entry, work, lake_dir, timeout)
363
+ except Exception as e: # never lose the run to one declaration
364
+ return {"decl": entry["decl"], "type": None, "status": "error", "levels": [], "modules": [], "rc": None,
365
+ "error": "driver error: %s: %s" % (type(e).__name__, e),
366
+ "failure": "resource" if getattr(e, "errno", None) in RESOURCE_ERRNOS else "extraction"}
367
+
368
+
369
+ def verdict(res):
370
+ if res.get("status") == "ok":
371
+ v = res.get("round_trip_variant")
372
+ return ("ok" if res.get("round_trip_exact") is not False else "ok (defeq, not syntactically equal)") + \
373
+ (" (with %s)" % v if v else "")
374
+ return "fail (%s)" % (res.get("failure") or "error")
375
+
376
+
377
+ def run_pool(entries, workers, work, lake_dir, timeout, done=None):
378
+ """Results in `entries` order; `done(entry, result)` runs in this thread as each one finishes."""
379
+ out = [None] * len(entries)
380
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, workers)) as ex:
381
+ futs = {ex.submit(safe_one, e, work, lake_dir, timeout): i for i, e in enumerate(entries)}
382
+ for f in concurrent.futures.as_completed(futs):
383
+ i = futs[f]
384
+ out[i] = f.result()
385
+ if done is not None:
386
+ done(entries[i], out[i])
387
+ return out
388
+
389
+
390
+ class Checkpoint:
391
+ """OUT.json.checkpoint.jsonl: a header line naming what the results belong to, then one line per
392
+ finished result (a later line for the same index replaces an earlier one)."""
393
+
394
+ def __init__(self, path, key):
395
+ self.path, self.key, self.fh = path, key, None
396
+
397
+ def load(self, entries):
398
+ """{index: result} of the settled results a matching checkpoint holds."""
399
+ if os.environ.get("LEAN_PKG_TYPES_RESUME", "1").strip() == "0" or not self.path.is_file():
400
+ return {}
401
+ got = {}
402
+ try:
403
+ lines = self.path.read_text(encoding="utf-8").splitlines()
404
+ head = json.loads(lines[0]) if lines else {}
405
+ if head.get("checkpoint") != CHECKPOINT or head.get("key") != self.key:
406
+ sys.stderr.write("lean-pkg types: %s is for another run (package, commit or driver); "
407
+ "starting afresh\n" % self.path)
408
+ return {}
409
+ for l in lines[1:]:
410
+ try:
411
+ rec = json.loads(l)
412
+ except ValueError: # a line cut short by a killed run
413
+ continue
414
+ i = rec.get("index")
415
+ if isinstance(i, int) and 0 <= i < len(entries) and rec.get("decl") == entries[i]["decl"] \
416
+ and isinstance(rec.get("result"), dict):
417
+ got[i] = rec["result"]
418
+ except (OSError, ValueError, IndexError) as e:
419
+ sys.stderr.write("lean-pkg types: cannot read %s (%s); starting afresh\n" % (self.path, e))
420
+ return {}
421
+ return {i: r for i, r in got.items() if r.get("failure") in SETTLED}
422
+
423
+ def open(self, kept):
424
+ """Rewrite the file with the header and the results kept from it, then append from here on."""
425
+ tmp = self.path.with_name(self.path.name + ".tmp")
426
+ with open(tmp, "w", encoding="utf-8") as fh:
427
+ fh.write(json.dumps({"checkpoint": CHECKPOINT, "key": self.key}) + "\n")
428
+ for i in sorted(kept):
429
+ fh.write(json.dumps({"index": i, "decl": kept[i]["decl"], "result": kept[i]},
430
+ ensure_ascii=False) + "\n")
431
+ tmp.replace(self.path)
432
+ self.fh = open(self.path, "a", encoding="utf-8")
433
+
434
+ def add(self, entry, res):
435
+ self.fh.write(json.dumps({"index": entry["index"], "decl": entry["decl"], "result": res},
436
+ ensure_ascii=False) + "\n")
437
+ self.fh.flush()
438
+ os.fsync(self.fh.fileno())
439
+
440
+ def close(self, remove):
441
+ if self.fh is not None:
442
+ self.fh.close()
443
+ if remove:
444
+ try:
445
+ self.path.unlink()
446
+ except OSError:
447
+ pass
448
+
449
+
450
+ def run_all(entries, jobs, work, lake_dir, timeout, pause, ckpt=None):
451
+ """Run every entry with `jobs` workers; while some fail on file-table exhaustion, halve the workers
452
+ and retry only those (at least two retry rounds, the last ones with one worker). Entries a matching
453
+ checkpoint already settled are not run again. -> (results, backoff rounds, resumed count)."""
454
+ kept = ckpt.load(entries) if ckpt is not None else {}
455
+ if ckpt is not None:
456
+ ckpt.open(kept)
457
+ total = len(entries)
458
+ if kept:
459
+ sys.stderr.write("lean-pkg types: resumed %d of %d result(s) from %s\n" % (len(kept), total, ckpt.path))
460
+ state = {"n": len(kept), "tag": ""}
461
+
462
+ def done(entry, res):
463
+ state["n"] += 1
464
+ sys.stderr.write("lean-pkg types: [%s%d/%d] %s %s\n" % (state["tag"], state["n"], state["total"],
465
+ entry["decl"], verdict(res)))
466
+ sys.stderr.flush()
467
+ if ckpt is not None:
468
+ ckpt.add(entry, res)
469
+
470
+ todo = [e for e in entries if e["index"] not in kept]
471
+ state["total"] = total
472
+ ran = run_pool(todo, jobs, work, lake_dir, timeout, done)
473
+ results = [kept.get(i) for i in range(total)]
474
+ for e, r in zip(todo, ran):
475
+ results[e["index"]] = r
476
+ backoff, workers, rnd = [], jobs, 0
477
+ while True:
478
+ idx = [i for i, r in enumerate(results) if r.get("failure") == "resource"]
479
+ if not idx or (rnd >= 2 and workers == 1):
480
+ break
481
+ rnd += 1
482
+ workers = max(1, workers // 2)
483
+ sys.stderr.write("lean-pkg types: %d declaration(s) hit 'too many open files'; retry %d with %d "
484
+ "worker(s)\n" % (len(idx), rnd, workers))
485
+ time.sleep(pause * rnd)
486
+ state.update(n=0, total=len(idx), tag="retry %d: " % rnd)
487
+ redo = run_pool([entries[i] for i in idx], workers, work, lake_dir, timeout, done)
488
+ for i, r in zip(idx, redo):
489
+ results[i] = r
490
+ backoff.append({"round": rnd, "jobs": workers, "retried": len(idx),
491
+ "recovered": sum(1 for r in redo if r.get("failure") != "resource")})
492
+ return results, backoff, len(kept)
493
+
494
+
495
+ def default_jobs():
496
+ """min(DEFAULT_JOBS, the CPUs this process may use: a Slurm allocation, not the whole node)."""
497
+ try:
498
+ cpus = len(os.sched_getaffinity(0))
499
+ except (AttributeError, OSError):
500
+ cpus = os.cpu_count() or 1
501
+ return max(1, min(DEFAULT_JOBS, cpus))
502
+
503
+
504
+ def summarize(results, jobs, backoff=(), resumed=0):
505
+ filled = sum(1 for r in results if r["status"] == "ok")
506
+ rt = sum(1 for r in results if r["status"] != "ok" and r.get("failure") == "round_trip")
507
+ errors = sum(1 for r in results if r["status"] != "ok" and r.get("failure") not in ("declaration", "round_trip"))
508
+ inexact = sum(1 for r in results if r["status"] == "ok" and r.get("round_trip_exact") is False)
509
+ variant = sum(1 for r in results if r["status"] == "ok" and r.get("round_trip_variant"))
510
+ return {"ok": errors == 0, "total": len(results), "filled": filled, "errors": errors,
511
+ "round_trip_failed": rt, "declaration_errors": len(results) - filled - errors - rt, "jobs": jobs,
512
+ "backoff": list(backoff), "round_trip_inexact": inexact, "resumed": resumed,
513
+ "round_trip_variant": variant}
514
+
515
+
516
+ def checkpoint_key():
517
+ """What a checkpoint's results depend on: the package, commit, Lake dir and the two Lean snippets."""
518
+ basis = {k: CONFIG.get(k) for k in ("schema", "package", "commit", "lake_dir", "snippet", "roundtrip_snippet")}
519
+ return hashlib.sha256(json.dumps(basis, sort_keys=True).encode("utf-8")).hexdigest()
520
+
521
+
522
+ def main():
523
+ if len(sys.argv) < 2 or not sys.argv[1]:
524
+ refuse("usage: cd <checkout> && bash DRIVER OUT.json")
525
+ out = pathlib.Path(sys.argv[1]).absolute()
526
+ lake_dir = pathlib.Path(CONFIG["lake_dir"]).absolute()
527
+ if not any((lake_dir / n).is_file() for n in ("lakefile.lean", "lakefile.toml")):
528
+ refuse("no lakefile.lean or lakefile.toml in %s; run from the package checkout" % lake_dir)
529
+ for tool, need in (("lake", True), ("lean", False)):
530
+ ok = is_elan(tool)
531
+ if ok is None and need:
532
+ refuse("%s is not on PATH (install elan)" % tool)
533
+ if ok is False:
534
+ refuse("%s on PATH (%s) is not elan's (%s); a %s outside elan ignores lean-toolchain"
535
+ % (tool, shutil.which(tool), elan_bin() / "bin" / tool, tool))
536
+ try:
537
+ head = subprocess.run(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
538
+ stdin=subprocess.DEVNULL).stdout.decode().strip()
539
+ except OSError:
540
+ head = ""
541
+ if head != CONFIG["commit"]:
542
+ refuse("checkout HEAD is %s, this driver is for %s; check out that commit first"
543
+ % (head or "(not a git checkout)", CONFIG["commit"]))
544
+ tc = lake_dir / "lean-toolchain"
545
+ toolchain = tc.read_text(encoding="utf-8").strip() if tc.is_file() else None
546
+ try:
547
+ jobs = max(1, int(os.environ.get("LEAN_PKG_TYPES_JOBS") or CONFIG["jobs"] or default_jobs()))
548
+ timeout = int(os.environ.get("LEAN_PKG_TYPES_TIMEOUT") or CONFIG["timeout"])
549
+ pause = float(os.environ.get("LEAN_PKG_TYPES_BACKOFF_SECONDS") or 5)
550
+ except ValueError as e:
551
+ refuse("LEAN_PKG_TYPES_JOBS / _TIMEOUT / _BACKOFF_SECONDS: %s" % e)
552
+ work = tempfile.mkdtemp(prefix="lean-pkg-types-")
553
+ ckpt = Checkpoint(out.with_name(out.name + ".checkpoint.jsonl"), checkpoint_key())
554
+ try:
555
+ entries = [dict(e, index=i) for i, e in enumerate(CONFIG["decls"])]
556
+ results, backoff, resumed = run_all(entries, jobs, work, lake_dir, timeout, pause, ckpt)
557
+ finally:
558
+ shutil.rmtree(work, ignore_errors=True)
559
+ if ckpt.fh is not None:
560
+ ckpt.fh.close()
561
+ ckpt.fh = None
562
+ summary = summarize(results, jobs, backoff, resumed)
563
+ doc = {"schema": CONFIG["schema"], "package": CONFIG["package"], "commit": head, "toolchain": toolchain,
564
+ "summary": summary, "results": results}
565
+ tmp = out.with_name(out.name + ".tmp")
566
+ tmp.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
567
+ tmp.replace(out)
568
+ ckpt.close(remove=summary["errors"] == 0)
569
+ sys.stderr.write("lean-pkg types: %d of %d filled (%d only defeq, not syntactically equal), %d extraction "
570
+ "error(s), %d round-trip failure(s), %d declaration error(s) -> %s\n"
571
+ % (summary["filled"], summary["total"], summary["round_trip_inexact"], summary["errors"],
572
+ summary["round_trip_failed"], summary["declaration_errors"], out))
573
+ if summary["errors"]:
574
+ sys.stderr.write("lean-pkg types: kept %s; a rerun with the same OUT.json runs only the unsettled "
575
+ "declarations\n" % ckpt.path)
576
+ if summary["errors"]:
577
+ sys.stderr.write("lean-pkg types: extraction failed for %d declaration(s) (see results[].rc, error, "
578
+ "output_tail); `--from-output` refuses this file unless --allow-partial\n" % summary["errors"])
579
+ sys.exit(2 if summary["filled"] == 0 else 1)
580
+
581
+
582
+ main()
583
+ '''
584
+
585
+
586
+ LEAN_THREADS_LINES = (
587
+ "# Shared cluster nodes (#34): the file table is per node, not per job, so several jobs' Lean\n"
588
+ "# processes can exhaust it together. One Lean thread per process unless the caller set\n"
589
+ "# LEAN_NUM_THREADS (an explicit value is kept); keep LEAN_PKG_TYPES_JOBS <= 2 as well.\n"
590
+ 'export LEAN_NUM_THREADS="${LEAN_NUM_THREADS:-1}"\n')
591
+
592
+
593
+ def driver_script(config: dict, *, lean_threads: bool = True) -> str:
594
+ """The self-contained driver: bash that hands an embedded python3 program its argument.
595
+ lean_threads (the --emit-script driver, run on a cluster node): default LEAN_NUM_THREADS to 1, keeping
596
+ an explicit value; the one-shot local run passes False and inherits the environment unchanged."""
597
+ cfg = json.dumps(json.dumps(config, ensure_ascii=True))
598
+ py = DRIVER_PY.replace("__CONFIG__", cfg)
599
+ names = ", ".join(d["decl"] for d in config["decls"][:3]) + (" ..." if len(config["decls"]) > 3 else "")
600
+ return ("#!/usr/bin/env bash\n"
601
+ f"# Generated by `lean-pkg comparator config --from-claims {config['package']} --emit-script`.\n"
602
+ f"# Elaborates {len(config['decls'])} declaration(s) ({names}) of {config['package']} at commit\n"
603
+ f"# {config['commit']} with `lake env lean` and writes the {SCHEMA} JSON to OUT.json.\n"
604
+ "# Usage: cd <package checkout> && bash THIS_FILE OUT.json\n"
605
+ "# Needs python3, git and elan's lake; build the package first (`lake build`). Writes only a\n"
606
+ "# temp dir and OUT.json. LEAN_PKG_TYPES_JOBS / LEAN_PKG_TYPES_TIMEOUT override the defaults;\n"
607
+ "# on 'too many open files' it halves the workers and retries. Exit 0 ok, 1 some extraction\n"
608
+ "# failed, 2 nothing filled (or refused). Progress: `[k/N] DECL ok|fail` on stderr; finished\n"
609
+ "# results go to OUT.json.checkpoint.jsonl, and a rerun with the same OUT.json resumes from it\n"
610
+ "# (LEAN_PKG_TYPES_RESUME=0 starts afresh).\n"
611
+ "set -euo pipefail\n"
612
+ + (LEAN_THREADS_LINES if lean_threads else "") +
613
+ 'if [ "$#" -ne 1 ]; then echo "usage: bash $0 OUT.json" >&2; exit 2; fi\n'
614
+ "exec python3 - \"$1\" <<'LEAN_PKG_DRIVER'\n"
615
+ f"{py}"
616
+ "LEAN_PKG_DRIVER\n")
617
+
618
+
619
+ def lake_dir_rel(repo: pathlib.Path, lake_env: str | None) -> str:
620
+ rel = gate_mod._safe_rel(lake_env, "--lake-env") if lake_env else "."
621
+ d = repo / rel
622
+ if not any((d / n).is_file() for n in LAKEFILES):
623
+ raise core.Fail(f"no lakefile.lean or lakefile.toml in {d}; `--challenge-from-type` needs a Lake "
624
+ f"package (--lake-env DIR names a sub-directory of the checkout)")
625
+ return rel
626
+
627
+
628
+ def module_of(file: object, lake_rel: str) -> str | None:
629
+ """`Demo/Main.lean` -> `Demo.Main` (relative to the Lake directory)."""
630
+ if not isinstance(file, str) or not file.endswith(".lean"):
631
+ return None
632
+ pp = pathlib.PurePosixPath(file)
633
+ if pp.is_absolute() or ".." in pp.parts:
634
+ return None
635
+ if lake_rel not in (".", ""):
636
+ try:
637
+ pp = pp.relative_to(pathlib.PurePosixPath(lake_rel))
638
+ except ValueError:
639
+ return None
640
+ parts = list(pp.with_suffix("").parts)
641
+ return ".".join(parts) if parts and all(parts) else None
642
+
643
+
644
+ def driver_config(name: str, head: str, lake_rel: str, claims: list[dict], jobs: int | None,
645
+ timeout: int) -> dict:
646
+ decls = []
647
+ for c in claims:
648
+ decl = str(c.get("decl") or "")
649
+ decls.append({"decl": decl, "claim": str(c.get("id") or ""), "file": c.get("file"),
650
+ "module": module_of(c.get("file"), lake_rel) if DECL_RE.match(decl) else None})
651
+ return {"schema": SCHEMA, "package": name, "commit": head, "lake_dir": lake_rel, "jobs": jobs,
652
+ "default_jobs": DEFAULT_JOBS, "timeout": timeout, "snippet": LEAN_SNIPPET,
653
+ "roundtrip_snippet": ROUNDTRIP_SNIPPET, "decls": decls}
654
+
655
+
656
+ def check_jobs_timeout(jobs: int | None, timeout: int | None) -> tuple[int | None, int]:
657
+ """(jobs, timeout). jobs None: the driver picks min(DEFAULT_JOBS, CPUs) on the host it runs on (#30)."""
658
+ j = jobs
659
+ t = DEFAULT_TIMEOUT if timeout is None else timeout
660
+ if j is not None and j < 1:
661
+ raise core.UsageError(f"--jobs {j}: must be at least 1")
662
+ if t < 1:
663
+ raise core.UsageError(f"--timeout {t}: must be at least 1 second")
664
+ return j, t
665
+
666
+
667
+ def refuse_non_elan() -> None:
668
+ for tool, need in (("lake", True), ("lean", False)):
669
+ where = shutil.which(tool)
670
+ if where is None:
671
+ if need:
672
+ raise core.Fail(f"{tool} is not on PATH; `--challenge-from-type` runs `lake env lean` "
673
+ f"(install elan, or use --emit-script on a host that has it)")
674
+ continue
675
+ if not cli.is_elan_proxy(where, tool):
676
+ raise core.Fail(f"{tool} on PATH ({where}) is not elan's ({cli.elan_bin() / tool}); a {tool} "
677
+ f"outside elan ignores the package's lean-toolchain")
678
+
679
+
680
+ def emit_path(repo: pathlib.Path, f: str, flag: str = "--emit-script") -> pathlib.Path:
681
+ """A file Lean-pkg writes beside the checkout (the driver, a --no-registry config): outside the
682
+ checkout, or under its .lake/ build dir."""
683
+ p = pathlib.Path(f).expanduser()
684
+ p = p if p.is_absolute() else pathlib.Path.cwd() / p
685
+ p = pathlib.Path(os.path.abspath(p))
686
+ root = pathlib.Path(os.path.abspath(repo))
687
+ try:
688
+ rel = p.relative_to(root)
689
+ except ValueError:
690
+ return p
691
+ if rel.parts[:1] != (".lake",) or len(rel.parts) < 2:
692
+ raise core.Fail(f"{flag} {f}: inside the checkout; write it outside, or under "
693
+ f"{root / '.lake'}/ (the build dir), so the checkout stays clean")
694
+ return p
695
+
696
+
697
+ def run_local(repo: pathlib.Path, config: dict) -> dict:
698
+ """Emit the driver into a temp dir, run it from the checkout, and return the parsed output."""
699
+ refuse_non_elan()
700
+ tmp = pathlib.Path(tempfile.mkdtemp(prefix="lean-pkg-types-"))
701
+ try:
702
+ script, out = tmp / "driver.sh", tmp / "types.json"
703
+ script.write_text(driver_script(config, lean_threads=False), encoding="utf-8")
704
+ p = subprocess.run(["bash", str(script), str(out)], cwd=repo, stdin=subprocess.DEVNULL,
705
+ capture_output=True, text=True, env=core.scrubbed_env()) # #27
706
+ # Exit 1/2 with an output file: some extractions failed; check_partial decides (#30).
707
+ if p.returncode not in (0, 1, 2) or not out.is_file():
708
+ tail = (p.stderr or p.stdout or "").strip().splitlines()
709
+ raise core.Fail(f"type driver failed (exit {p.returncode}): {tail[-1] if tail else 'no output'}")
710
+ return read_output(out, config["package"], config["commit"], str(out))
711
+ finally:
712
+ shutil.rmtree(tmp, ignore_errors=True)
713
+
714
+
715
+ def read_output(path: pathlib.Path, name: str, head: str, shown: str) -> dict:
716
+ try:
717
+ doc = json.loads(path.read_text(encoding="utf-8"))
718
+ except (OSError, ValueError) as e:
719
+ raise core.Fail(f"--from-output {shown}: cannot read JSON ({e}); nothing written") from e
720
+ if not isinstance(doc, dict) or doc.get("schema") != SCHEMA:
721
+ got = doc.get("schema") if isinstance(doc, dict) else None
722
+ raise core.Fail(f"--from-output {shown}: schema {got!r}, expected {SCHEMA!r}; nothing written")
723
+ if doc.get("package") != name:
724
+ raise core.Fail(f"--from-output {shown}: package {doc.get('package')!r}, not {name!r}; nothing written")
725
+ if doc.get("commit") != head:
726
+ raise core.Fail(f"--from-output {shown}: elaborated at commit {str(doc.get('commit'))[:12]}, but HEAD is "
727
+ f"{head[:12]}; re-run the driver at HEAD; nothing written")
728
+ results = doc.get("results")
729
+ if not isinstance(results, list) or not all(isinstance(r, dict) for r in results):
730
+ raise core.Fail(f"--from-output {shown}: results must be a list of objects; nothing written")
731
+ return doc
732
+
733
+
734
+ DECLARATION_ERRORS = ("unknown constant", "no Lean module for the claim's file")
735
+
736
+
737
+ def failure_of(result: dict | None) -> str | None:
738
+ """Why a result is not usable: None (ok), `declaration` (a per-declaration error Lean reported) or
739
+ `extraction` (Lean did not run to completion; also a missing result). Output written before #30
740
+ has no `failure`; there an `rc` other than 0, or an error that is not a declaration error, counts
741
+ as an extraction failure."""
742
+ if result is None:
743
+ return "extraction"
744
+ if result.get("status") == "ok":
745
+ return None
746
+ f = result.get("failure")
747
+ if f in ("declaration", "round_trip"):
748
+ return f
749
+ if f is not None:
750
+ return "extraction"
751
+ rc = result.get("rc")
752
+ if rc in (None, 0) and str(result.get("error") or "").startswith(DECLARATION_ERRORS):
753
+ return "declaration"
754
+ return "extraction"
755
+
756
+
757
+ def check_partial(results: list[dict | None], doc: dict, shown: str, allow_partial: bool) -> int:
758
+ """The number of extraction failures among `results`; refuses when there are any, unless
759
+ `allow_partial` (#30)."""
760
+ failed = sum(1 for r in results if failure_of(r) == "extraction")
761
+ if failed and not allow_partial:
762
+ filled = sum(1 for r in results if failure_of(r) is None)
763
+ summ = doc.get("summary") if isinstance(doc.get("summary"), dict) else {}
764
+ jobs = f" at {summ['jobs']} job(s)" if isinstance(summ.get("jobs"), int) else ""
765
+ raise core.Fail(f"{shown}: extraction failed for {failed} of {len(results)} declaration(s){jobs} "
766
+ f"({filled} filled); re-run the driver (lower LEAN_PKG_TYPES_JOBS), or pass "
767
+ f"--allow-partial to use the {filled} filled and mark the rest needs_restatement "
768
+ f"(extraction_failed); nothing written")
769
+ return failed
770
+
771
+
772
+ def first_line(s: object) -> str:
773
+ lines = [ln.strip() for ln in str(s or "").splitlines() if ln.strip()]
774
+ return lines[0] if lines else "no error text"
775
+
776
+
777
+ def fill(entry: dict, result: dict | None, summary: str, source: str, statements: str | None = None) -> dict:
778
+ """Turn a TODO scaffold entry into a pre-filled one, or record why it stays TODO. `statements`: the
779
+ package's declared statements module (#369), whose constants a Challenge may name like Mathlib's."""
780
+ tname, decl = entry["theorem_name"], entry["decl"]
781
+ failure = failure_of(result)
782
+ if result is None:
783
+ result = {"status": "error", "error": f"no result for {decl} in {source}"}
784
+ typ = result.get("type")
785
+ if failure is not None or not isinstance(typ, str) or not typ.strip():
786
+ entry["needs_restatement"] = True
787
+ entry["type_error"] = first_line(result.get("error") or "no type in the output")
788
+ if failure == "extraction":
789
+ entry["restatement_reason"] = "extraction_failed"
790
+ elif failure == "round_trip": # the printed type does not elaborate back to the declaration's (#31)
791
+ entry["restatement_reason"] = "round_trip_failed"
792
+ entry["type_error"] = " ".join(str(result.get("error") or "round-trip check failed").split())[:500]
793
+ if isinstance(typ, str) and typ.strip():
794
+ entry["printed_type"] = typ.strip()
795
+ return entry
796
+ levels = [lv for lv in result.get("levels") or [] if isinstance(lv, str) and lv]
797
+ modules = result.get("modules")
798
+ reason = None
799
+ if not isinstance(modules, list):
800
+ reason = "the output does not list the modules the type uses"
801
+ else:
802
+ foreign = sorted({str(m) for m in modules if str(m).split(".", 1)[0] not in VOCAB_ROOTS
803
+ and str(m) != statements})
804
+ if foreign:
805
+ reason = "the type uses project definitions (" + ", ".join(foreign[:5]) + \
806
+ (", ..." if len(foreign) > 5 else "") + ")"
807
+ if reason is None and any(ch in typ for ch in UNPARSEABLE):
808
+ reason = "the printed type has inaccessible names or elided proofs and will not re-elaborate"
809
+ if reason is None and result.get("round_trip") != "ok":
810
+ reason = "the output has no round-trip check of the printed type (a driver older than #31); re-run it"
811
+ if reason is None and result.get("round_trip_exact") is False:
812
+ reason = ("the printed type is only definitionally equal to the declaration's, not syntactically "
813
+ "(round_trip_exact false); check it states what the claim states")
814
+ head = f"theorem {tname}" + (".{" + ", ".join(levels) + "}" if levels else "")
815
+ body = typ.strip()
816
+ doc = summary.replace("-/", "- /").replace("\n", " ").strip()
817
+ # The text passed the round trip only under `open scoped Classical` (a decidability instance): the
818
+ # Challenge and Solution need it too.
819
+ opens = "open scoped Classical in\n" if result.get("round_trip_open") == "Classical" else ""
820
+ challenge = f"{opens}/-- {doc} -/\n{head} :\n {body.replace(chr(10), chr(10) + ' ')} := by\n sorry"
821
+ if reason:
822
+ challenge = f"-- TODO: restate in Mathlib vocabulary: {reason}\n" + challenge
823
+ entry["type"] = body
824
+ entry["needs_restatement"] = reason is not None
825
+ if reason:
826
+ entry["restatement_reason"] = reason
827
+ entry["challenge"] = challenge
828
+ entry["solution"] = (f"{opens}{head} :\n {body.replace(chr(10), chr(10) + ' ')} := by\n"
829
+ f" exact @_root_.{decl}")
830
+ return entry