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,10 @@
1
+ # The first built-in site profile (site-profile/1; docs/sites.md). The acknowledgement is the cluster's
2
+ # official wording, verbatim: changing it changes every page that carries it.
3
+ schema: site-profile/1
4
+ name: easley
5
+ title: Auburn University Easley Cluster
6
+ url: https://hpc.auburn.edu/hpc/docs/hpcdocs/build/html/easley/intro.html
7
+ acknowledgement: "This work was completed in part with resources provided by the [Auburn University Easley Cluster](https://hpc.auburn.edu/hpc/docs/hpcdocs/build/html/easley/intro.html)."
8
+ mention: the Easley Cluster
9
+ mention_pattern: 'Easley\s+Cluster'
10
+ scheduler: slurm
@@ -0,0 +1,12 @@
1
+ # The built-in GitHub Actions site profile (site-profile/1; docs/sites.md; proposal 0008). Its scheduler,
2
+ # github-actions, is built-in only and renders this sentence only from a corroborated run (sentence level 2,
3
+ # `--corroborate`); offline (level 1) a receipt backs the compute job but the page carries no sentence.
4
+ # mention_pattern is narrow on purpose: a CI badge or "tests run on GitHub Actions" is not a claim.
5
+ schema: site-profile/1
6
+ name: github-actions
7
+ title: GitHub Actions
8
+ url: https://docs.github.com/en/actions
9
+ acknowledgement: "Verification ran on [GitHub Actions](https://docs.github.com/en/actions) hosted runners ({runs})."
10
+ mention: GitHub Actions
11
+ mention_pattern: 'Verification\s+ran\s+on\s+\[?GitHub\s+Actions'
12
+ scheduler: github-actions
lean_pkg/sites.py ADDED
@@ -0,0 +1,225 @@
1
+ # lean-pkg sites -- compute site profiles: where gates ran, how a receipt shows it, how the page credits it
2
+ """Site profiles (docs/sites.md; design: docs/design/sites-and-ci-receipts.md).
3
+
4
+ A *site* is a place verification jobs run: a cluster, later a CI service. Its profile is data, a
5
+ `site-profile/1` YAML file, never a code path:
6
+
7
+ schema: site-profile/1
8
+ name: NAME # the coverage.yaml compute[].cluster value; [a-z][a-z0-9-]*, at most 40
9
+ title: TEXT # the linked name in the acknowledgement
10
+ url: https://... # where the title links
11
+ acknowledgement: TEXT # the sentence the page renders, verbatim; must contain [title](url)
12
+ mention: TEXT # how a refusal names the site ("the Easley Cluster")
13
+ mention_pattern: REGEX # README text that claims the site (case-insensitive); must match the
14
+ # acknowledgement, so a backed page passes its own check
15
+ scheduler: slurm # the job system whose receipts back the site (SCHEDULERS)
16
+ x-NAME: ANY # optional extension keys, tolerated and never read
17
+
18
+ Where profiles come from, in this order (the order of the Acknowledgments sentences):
19
+
20
+ 1. built-in: `site_profiles/*.yaml` shipped with lean-pkg (Easley is the first);
21
+ 2. the package's own: `lean-pkg-sites/<name>.yaml` committed at HEAD in the package directory, so the
22
+ page renders the same on every machine and in CI. A package profile may not reuse a built-in name.
23
+
24
+ A *scheduler* is code, not data: it is how a committed receipt shows a job ran (`job_re`, the receipt
25
+ `job_id` spelling; coverage.JOB_INDEX, its reader), and from which corroboration level a site of it renders
26
+ its sentence (`sentence_level`). Slurm: `slurm-<J>`, which `receipt slurm` writes only after sacct shows the
27
+ job COMPLETED, or a comparator receipt whose Slurm claim (job_id J, host_policy `Slurm job J ...`) carries a
28
+ valid sacct seal (`comparator-receipt --seal-sacct`); sentence level 1. GitHub Actions (proposal 0008):
29
+ `gha-<run_id>-<run_attempt>`, a lower-tier receipt, or a comparator receipt written on a GitHub-hosted runner
30
+ (stage S5), whose additive `ci` block passes level 1 (ci_github.py);
31
+ sentence level 2, so the page carries its sentence only once the run is corroborated, never offline. A
32
+ built-in-only scheduler (`builtin_only`) may be named by a built-in profile alone: no package writes its own
33
+ wording for its evidence sentence. The acknowledgement token `{runs}` (filled with the corroborated runs'
34
+ links) is allowed only in a built-in profile whose scheduler has sentence_level > 1.
35
+
36
+ The rule every profile carries (unchanged from the Easley-only code it replaced): a site's sentence
37
+ appears only when coverage.yaml lists the site with job ids and every listed id is the job of a receipt of
38
+ the site's scheduler committed at HEAD; a README that mentions the site without that backing fails `page
39
+ --check`. Receipts carry no site identity (a Slurm job number alone does not name a cluster), so the
40
+ declaration is what names the site and the receipt is what shows a job of that scheduler ran.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import functools
46
+ import pathlib
47
+ import re
48
+ from dataclasses import dataclass
49
+
50
+ import yaml
51
+
52
+ from . import core
53
+
54
+ SCHEMA = "site-profile/1"
55
+ KEYS = ("schema", "name", "title", "url", "acknowledgement", "mention", "mention_pattern", "scheduler")
56
+ NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,39}$")
57
+ EXTENSION_RE = re.compile(r"^x-[a-z][a-z0-9-]*$")
58
+ HTTPS_URL_RE = re.compile(r"^https://[A-Za-z0-9.-]+(?::\d+)?/[A-Za-z0-9._~/%+-]*$")
59
+ BUILTIN_DIR = pathlib.Path(__file__).resolve().parent / "site_profiles"
60
+ PACKAGE_DIR = "lean-pkg-sites" # package-relative; profiles committed at HEAD
61
+ LIMITS = {"title": 120, "acknowledgement": 400, "mention": 80, "mention_pattern": 200}
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Scheduler:
66
+ name: str
67
+ label: str
68
+ job_re: re.Pattern
69
+ example: str
70
+ placeholder: str
71
+ sentence_level: int = 1 # the corroboration level from which a site of it renders its sentence
72
+ builtin_only: bool = False # only a built-in profile may name it
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Site:
77
+ name: str
78
+ title: str
79
+ url: str
80
+ acknowledgement: str
81
+ mention: str
82
+ mention_re: re.Pattern
83
+ scheduler: str
84
+ source: str # "built-in" or the package-relative path of its file
85
+
86
+
87
+ SLURM = Scheduler(name="slurm", label="Slurm", job_re=re.compile(r"^slurm-\d+(?:_\d+)?$"),
88
+ example="slurm-12345", placeholder="slurm-J")
89
+ GITHUB_ACTIONS = Scheduler(name="github-actions", label="GitHub Actions", job_re=re.compile(r"^gha-\d+-\d+$"),
90
+ example="gha-123456789-1", placeholder="gha-R-A", sentence_level=2, builtin_only=True)
91
+ SCHEDULERS: dict[str, Scheduler] = {SLURM.name: SLURM, GITHUB_ACTIONS.name: GITHUB_ACTIONS}
92
+ RUNS_TOKEN = "{runs}" # in an acknowledgement: the corroborated runs' links (sentence_level > 1)
93
+
94
+
95
+ class _StrictLoader(yaml.SafeLoader):
96
+ """safe_load, but a mapping that repeats a key is an error."""
97
+
98
+
99
+ def _no_duplicates(loader, node, deep=False):
100
+ keys = [loader.construct_object(k, deep=deep) for k, _v in node.value]
101
+ dup = sorted({str(k) for k in keys if keys.count(k) > 1})
102
+ if dup:
103
+ raise yaml.constructor.ConstructorError(None, None, f"duplicate key {dup[0]!r}", node.start_mark)
104
+ return yaml.SafeLoader.construct_mapping(loader, node, deep=deep)
105
+
106
+
107
+ _StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _no_duplicates)
108
+
109
+
110
+ def parse(text: str, where: str, source: str) -> tuple[Site | None, list[str]]:
111
+ """(profile, []) for a valid site-profile/1 document, else (None, errors), each prefixed by where."""
112
+ try:
113
+ doc = yaml.load(text, Loader=_StrictLoader)
114
+ except yaml.YAMLError as e:
115
+ return None, [f"{where}: not YAML ({str(e).splitlines()[0]})"]
116
+ if not isinstance(doc, dict):
117
+ return None, [f"{where}: must be a mapping with keys {', '.join(KEYS)}"]
118
+ errors = [f"{where}: missing key {k}" for k in KEYS if k not in doc]
119
+ # `x-NAME` keys are an extension namespace: tolerated, never read (an operator's own data, e.g. a lab's
120
+ # scheduler options); every other unknown key is refused
121
+ errors += [f"{where}: unknown key {k!r}" for k in doc
122
+ if k not in KEYS and not (isinstance(k, str) and EXTENSION_RE.match(k))]
123
+ if errors:
124
+ return None, errors
125
+ bad = [k for k in KEYS if not isinstance(doc[k], str) or not doc[k].strip() or "\n" in doc[k]]
126
+ if bad:
127
+ return None, [f"{where}: {k}: must be one non-empty line of text" for k in bad]
128
+ if doc["schema"] != SCHEMA:
129
+ errors.append(f"{where}: schema: must be {SCHEMA}, got {doc['schema']!r}")
130
+ if not NAME_RE.match(doc["name"]):
131
+ errors.append(f"{where}: name: must match {NAME_RE.pattern}, got {doc['name']!r}")
132
+ for k, n in LIMITS.items():
133
+ if len(doc[k]) > n:
134
+ errors.append(f"{where}: {k}: at most {n} characters")
135
+ if not HTTPS_URL_RE.match(doc["url"]):
136
+ errors.append(f"{where}: url: must be an https URL")
137
+ if any(c in doc["acknowledgement"] for c in "<>`|"):
138
+ errors.append(f"{where}: acknowledgement: may not contain < > ` or | (it is rendered as Markdown)")
139
+ if f"[{doc['title']}]({doc['url']})" not in doc["acknowledgement"]:
140
+ errors.append(f"{where}: acknowledgement: must contain the link [{doc['title']}]({doc['url']})")
141
+ sched = SCHEDULERS.get(doc["scheduler"])
142
+ if sched is None:
143
+ errors.append(f"{where}: scheduler: must be one of {', '.join(SCHEDULERS)}, got {doc['scheduler']!r}")
144
+ elif sched.builtin_only and source != "built-in":
145
+ errors.append(f"{where}: scheduler: {sched.name} is built-in only (the built-in {sched.name} profile "
146
+ f"words its evidence sentence; a package profile may not)")
147
+ if RUNS_TOKEN in doc["acknowledgement"] and not (
148
+ source == "built-in" and sched is not None and sched.sentence_level > 1):
149
+ errors.append(f"{where}: acknowledgement: the token {RUNS_TOKEN} is allowed only in a built-in profile "
150
+ f"whose scheduler renders its sentence from a corroborated run (sentence level > 1)")
151
+ try:
152
+ mention_re = re.compile(doc["mention_pattern"], re.I)
153
+ except re.error as e:
154
+ mention_re = None
155
+ errors.append(f"{where}: mention_pattern: not a regular expression ({e})")
156
+ if mention_re is not None and not mention_re.search(doc["acknowledgement"]):
157
+ errors.append(f"{where}: mention_pattern: must match the acknowledgement (a backed page must pass "
158
+ f"its own check)")
159
+ if errors:
160
+ return None, errors
161
+ return Site(name=doc["name"], title=doc["title"], url=doc["url"], acknowledgement=doc["acknowledgement"],
162
+ mention=doc["mention"], mention_re=mention_re, scheduler=doc["scheduler"], source=source), []
163
+
164
+
165
+ @functools.lru_cache(maxsize=1)
166
+ def _builtin() -> tuple[Site, ...]:
167
+ out = []
168
+ for path in sorted(BUILTIN_DIR.glob("*.yaml")):
169
+ site, errors = parse(path.read_text(encoding="utf-8"), f"built-in site profile {path.name}", "built-in")
170
+ if errors:
171
+ raise RuntimeError("; ".join(errors)) # a packaging defect, caught by the tests
172
+ if site.name != path.stem:
173
+ raise RuntimeError(f"built-in site profile {path.name}: name {site.name!r} is not the file name")
174
+ out.append(site)
175
+ return tuple(out)
176
+
177
+
178
+ def builtin() -> dict[str, Site]:
179
+ """The built-in profiles by name, in file-name order."""
180
+ return {s.name: s for s in _builtin()}
181
+
182
+
183
+ def names() -> tuple[str, ...]:
184
+ """The built-in profile names (the accepted compute[].cluster values of a package with none of its own)."""
185
+ return tuple(builtin())
186
+
187
+
188
+ def package_profiles(repo: pathlib.Path) -> tuple[dict[str, Site], list[str]]:
189
+ """({name: profile}, errors) for the package's own profiles, `lean-pkg-sites/*.yaml` committed at HEAD."""
190
+ p = core.git(repo, "ls-tree", "-z", "--name-only", "HEAD", "--", f"{PACKAGE_DIR}/")
191
+ rels = sorted(x for x in (p.stdout.split("\0") if p.returncode == 0 else []) if x)
192
+ out: dict[str, Site] = {}
193
+ errors: list[str] = []
194
+ taken = builtin()
195
+ for rel in rels:
196
+ if not rel.endswith(".yaml") or rel.count("/") != 1:
197
+ errors.append(f"{rel}: {PACKAGE_DIR}/ holds only <name>.yaml site profiles")
198
+ continue
199
+ raw = core.git_show_bytes(repo, rel)
200
+ site, errs = parse((raw or b"").decode("utf-8", errors="replace"), f"{rel} at HEAD", rel)
201
+ if errs:
202
+ errors += errs
203
+ elif site.name != pathlib.PurePosixPath(rel).stem:
204
+ errors.append(f"{rel} at HEAD: name {site.name!r} is not the file name")
205
+ elif site.name in taken:
206
+ errors.append(f"{rel} at HEAD: {site.name!r} is a built-in site profile; a package may not redefine "
207
+ f"it (its acknowledgement is the site's own wording)")
208
+ else:
209
+ out[site.name] = site
210
+ return out, errors
211
+
212
+
213
+ def for_repo(repo: pathlib.Path | None) -> dict[str, Site]:
214
+ """Every profile a package can name: built-in, then its own; a malformed own profile refuses."""
215
+ profiles = builtin()
216
+ if repo is None:
217
+ return profiles
218
+ own, errors = package_profiles(repo)
219
+ if errors:
220
+ raise core.Fail(f"{len(errors)} site profile problem(s) (docs/sites.md):\n " + "\n ".join(errors))
221
+ return {**profiles, **own}
222
+
223
+
224
+ def scheduler_of(site: Site) -> Scheduler:
225
+ return SCHEDULERS[site.scheduler]
lean_pkg/stacks.py ADDED
@@ -0,0 +1,373 @@
1
+ # lean-pkg stacks -- the declared LTS stacks (proposal 0004) and the check of a package against one
2
+ """The LTS stacks lean-pkg declares (schema `lean-pkg-stack/1`, proposal 0004, docs/stacks/).
3
+
4
+ Source of truth: `docs/stacks/lts-YYYY.MM.yaml` in the lean-pkg repository, the reviewed files beside their
5
+ pages. The wheel ships a byte-identical copy of each under `lean_pkg/data/stacks/` (written by `make docs`;
6
+ tests/test_stacks.py fails when a copy differs or is missing), and this module reads only that packaged copy,
7
+ so an installed lean-pkg behaves the same inside and outside a lean-pkg checkout.
8
+
9
+ declared a stack whose `published` is set (declared after its matrix passed)
10
+ window published <= day <= supported_until
11
+ current the newest declared stack whose window covers today (none: no stack is current)
12
+
13
+ A package opts in with `stack: NAME` in its coverage.yaml. `check()` compares the package's committed pins
14
+ with the stack: `lean-toolchain`, the Mathlib commit in `lake-manifest.json` (against the stack's commit,
15
+ never only the tag name: a tag can be moved) and, when a comparator receipt is given, its toolchain digests
16
+ against `comparator_tools.binaries_sha256` (recorded for Linux x86_64). Every finding is a warning:
17
+ the stack key never makes a check pass or fail (proposal 0004, "How a package opts in" and "Trust model").
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime as dt
23
+ import functools
24
+ import json
25
+ import pathlib
26
+ import re
27
+
28
+ import yaml
29
+
30
+ from . import core
31
+
32
+ SCHEMA = "lean-pkg-stack/1"
33
+ DATA_DIR = pathlib.Path(__file__).resolve().parent / "data" / "stacks"
34
+ DOCS_URL = "https://github.com/lean-pkg/lean-pkg/blob/main/docs/stacks/{name}.md"
35
+ HEX40 = re.compile(r"^[0-9a-f]{40}$")
36
+ HEX64 = re.compile(r"^[0-9a-f]{64}$")
37
+ TOOLCHAIN = re.compile(r"^leanprover/lean4:v(\d+)\.(\d+)\.(\d+)$") # a release, never an rc or nightly
38
+ VERSION = re.compile(r"^v(\d+)\.(\d+)\.(\d+)(?:-rc(\d+))?$")
39
+ NAME = re.compile(r"^lts-(\d{4})\.(04|10)$") # decided: April and October
40
+ RANGE = re.compile(r"^>=(\d+)\.(\d+)\.(\d+),<(\d+)\.(\d+)$")
41
+ CHOICES = ("current", "none") # `new --stack` besides a name
42
+
43
+ TOP_KEYS = {"schema", "name", "defined", "published", "lean_toolchain", "lean_commit", "mathlib", "lean_pkg",
44
+ "palomar_floor", "comparator_tools", "supported_until", "successor", "tested", "migration_cases",
45
+ "advisories"}
46
+ MATHLIB_KEYS = {"rev", "commit"}
47
+ FLOOR_KEYS = {"minimum", "satisfied"}
48
+ TOOLS_KEYS = {"mechanism", "sources", "release_asset", "binaries_sha256"}
49
+ SOURCE_KEYS = {"lake_comparator", "leanexport", "leanchecker", "nanoda_lib", "con_ron"}
50
+ ASSET_KEYS = {"name", "sha256"}
51
+ TESTED_KEYS = {"package", "commit", "moved", "build", "result"}
52
+ MIGRATION_KEYS = {"package", "commit", "reason", "to_move"}
53
+ RESULTS = {"verified", "built", "migration", "pending", "blocked", "failed"}
54
+
55
+
56
+ class StackError(ValueError):
57
+ """A shipped stack file is malformed (a packaging bug: tests/test_stacks.py refuses it first)."""
58
+
59
+
60
+ def version_key(v: str) -> tuple[int, int, int, int]:
61
+ m = VERSION.match(v)
62
+ if not m:
63
+ raise ValueError(v)
64
+ a, b, c, rc = m.groups()
65
+ return int(a), int(b), int(c), int(rc) if rc else 1 << 30 # a release sorts after its candidates
66
+
67
+
68
+ def digest_keys() -> set[str]:
69
+ return {k.removesuffix("_sha256") for k in core.COMPARATOR_TOOLCHAIN_DIGESTS}
70
+
71
+
72
+ def validate(doc) -> list[str]:
73
+ """Problems of one stack document; [] when it is a valid lean-pkg-stack/1 file (closed keys)."""
74
+ p: list[str] = []
75
+
76
+ def closed(where: str, d, keys: set[str]) -> bool:
77
+ if not isinstance(d, dict):
78
+ p.append(f"{where}: not a mapping")
79
+ return False
80
+ if set(d) != keys:
81
+ p.append(f"{where}: keys {sorted(set(d) ^ keys)} differ from the schema")
82
+ return False
83
+ return True
84
+
85
+ if not closed("stack", doc, TOP_KEYS):
86
+ return p
87
+ if doc["schema"] != SCHEMA:
88
+ p.append(f"schema: {doc['schema']!r}")
89
+ if not isinstance(doc["name"], str) or not NAME.match(doc["name"]):
90
+ p.append(f"name: {doc['name']!r} is not lts-YYYY.04 or lts-YYYY.10")
91
+ for k in ("defined", "supported_until"):
92
+ if not isinstance(doc[k], dt.date):
93
+ p.append(f"{k}: not a date")
94
+ if doc["published"] is not None and not isinstance(doc["published"], dt.date):
95
+ p.append("published: neither null nor a date")
96
+ m = TOOLCHAIN.match(str(doc["lean_toolchain"]))
97
+ if not m:
98
+ p.append(f"lean_toolchain: {doc['lean_toolchain']!r} is not a Lean release")
99
+ if not HEX40.match(str(doc["lean_commit"])):
100
+ p.append("lean_commit: not a 40-hex commit")
101
+ if closed("mathlib", doc["mathlib"], MATHLIB_KEYS):
102
+ rev = str(doc["mathlib"]["rev"])
103
+ if not VERSION.match(rev) or "-rc" in rev:
104
+ p.append(f"mathlib.rev: {rev!r} is not a release tag")
105
+ elif m and rev != "v" + ".".join(m.groups()):
106
+ p.append(f"mathlib.rev: {rev} is not the tag of the toolchain")
107
+ if not HEX40.match(str(doc["mathlib"]["commit"])):
108
+ p.append("mathlib.commit: not a 40-hex commit")
109
+ if not RANGE.match(str(doc["lean_pkg"])):
110
+ p.append(f"lean_pkg: {doc['lean_pkg']!r} is not a >=X.Y.Z,<A.B range")
111
+ if closed("palomar_floor", doc["palomar_floor"], FLOOR_KEYS) and m:
112
+ floor = str(doc["palomar_floor"]["minimum"])
113
+ ok = VERSION.match(floor) is not None and version_key(floor) <= version_key("v" + ".".join(m.groups()))
114
+ if doc["palomar_floor"]["satisfied"] is not ok:
115
+ p.append(f"palomar_floor.satisfied: {doc['palomar_floor']['satisfied']} but {floor} vs the toolchain "
116
+ f"says {ok}")
117
+ t = doc["comparator_tools"]
118
+ if closed("comparator_tools", t, TOOLS_KEYS):
119
+ if t["mechanism"] not in ("toolchain", "legacy"):
120
+ p.append(f"comparator_tools.mechanism: {t['mechanism']!r}")
121
+ if closed("comparator_tools.sources", t["sources"], SOURCE_KEYS):
122
+ for k, v in t["sources"].items():
123
+ if v != "in-tree" and not HEX40.match(str(v)):
124
+ p.append(f"comparator_tools.sources.{k}: neither in-tree nor a 40-hex commit")
125
+ if closed("comparator_tools.release_asset", t["release_asset"], ASSET_KEYS):
126
+ if not HEX64.match(str(t["release_asset"]["sha256"])):
127
+ p.append("comparator_tools.release_asset.sha256: not a SHA-256")
128
+ if closed("comparator_tools.binaries_sha256", t["binaries_sha256"], digest_keys()):
129
+ for k, v in t["binaries_sha256"].items():
130
+ if not HEX64.match(str(v)):
131
+ p.append(f"comparator_tools.binaries_sha256.{k}: not a SHA-256")
132
+ if doc["successor"] is not None and not NAME.match(str(doc["successor"])):
133
+ p.append(f"successor: {doc['successor']!r}")
134
+ if not isinstance(doc["tested"], list) or not doc["tested"]:
135
+ p.append("tested: not a non-empty list")
136
+ else:
137
+ for i, e in enumerate(doc["tested"]):
138
+ if closed(f"tested[{i}]", e, TESTED_KEYS):
139
+ if e["result"] not in RESULTS:
140
+ p.append(f"tested[{i}].result: {e['result']!r}")
141
+ if e["commit"] is not None and not HEX40.match(str(e["commit"])):
142
+ p.append(f"tested[{i}].commit: not a 40-hex commit")
143
+ if doc["published"] is not None and any(e.get("result") in ("pending", "blocked", "failed")
144
+ for e in doc["tested"] if isinstance(e, dict)):
145
+ p.append("published: set while a matrix entry is pending, blocked or failed (declared after the "
146
+ "matrix passes)")
147
+ if not isinstance(doc["migration_cases"], list):
148
+ p.append("migration_cases: not a list")
149
+ else:
150
+ for i, e in enumerate(doc["migration_cases"]):
151
+ if closed(f"migration_cases[{i}]", e, MIGRATION_KEYS):
152
+ if not HEX40.match(str(e["commit"])):
153
+ p.append(f"migration_cases[{i}].commit: not a 40-hex commit")
154
+ for k in ("reason", "to_move"):
155
+ if not str(e[k] or "").strip():
156
+ p.append(f"migration_cases[{i}].{k}: empty")
157
+ if not isinstance(doc["advisories"], list):
158
+ p.append("advisories: not a list")
159
+ return p
160
+
161
+
162
+ def load_dir(d: pathlib.Path) -> dict[str, dict]:
163
+ """Every lts-*.yaml of d, validated, by name (file order = name order = chronological)."""
164
+ out: dict[str, dict] = {}
165
+ for f in sorted(d.glob("lts-*.yaml")):
166
+ try:
167
+ doc = yaml.safe_load(f.read_text(encoding="utf-8"))
168
+ except (OSError, UnicodeDecodeError, yaml.YAMLError) as e:
169
+ raise StackError(f"stack file {f.name}: unreadable ({e})") from None
170
+ problems = validate(doc)
171
+ if problems:
172
+ raise StackError(f"stack file {f.name}: {'; '.join(problems)}")
173
+ if f.stem != doc["name"]:
174
+ raise StackError(f"stack file {f.name}: names {doc['name']}")
175
+ out[doc["name"]] = doc
176
+ return out
177
+
178
+
179
+ @functools.lru_cache(maxsize=None)
180
+ def _cached(d: str) -> tuple[tuple[str, dict], ...]:
181
+ return tuple(load_dir(pathlib.Path(d)).items())
182
+
183
+
184
+ def load() -> dict[str, dict]:
185
+ """The stacks this lean-pkg ships (all of them, declared or not), by name."""
186
+ return dict(_cached(str(DATA_DIR)))
187
+
188
+
189
+ def today() -> dt.date:
190
+ return dt.date.today()
191
+
192
+
193
+ def declared(stacks: dict[str, dict] | None = None) -> dict[str, dict]:
194
+ """The declared stacks (published set), by name."""
195
+ return {n: s for n, s in (load() if stacks is None else stacks).items() if s["published"] is not None}
196
+
197
+
198
+ def window(stack: dict, day: dt.date | None = None) -> str:
199
+ """'before' (not yet published, or published after day), 'in', or 'past' (after supported_until)."""
200
+ day = day or today()
201
+ if stack["published"] is None or day < stack["published"]:
202
+ return "before"
203
+ return "in" if day <= stack["supported_until"] else "past"
204
+
205
+
206
+ def current(day: dt.date | None = None, stacks: dict[str, dict] | None = None) -> dict | None:
207
+ """The newest declared stack whose window covers day (default today); None when there is none."""
208
+ inside = [s for s in declared(stacks).values() if window(s, day) == "in"]
209
+ return max(inside, key=lambda s: (s["published"], s["name"])) if inside else None
210
+
211
+
212
+ def declared_list(stacks: dict[str, dict] | None = None) -> str:
213
+ d = declared(stacks)
214
+ return ", ".join(f"{n} ({s['published']} to {s['supported_until']})" for n, s in d.items()) or "(none)"
215
+
216
+
217
+ def resolve(value: str, day: dt.date | None = None) -> dict | None:
218
+ """`new --stack VALUE`: a declared stack's name, `current` or `none`. UsageError otherwise."""
219
+ if value == "none":
220
+ return None
221
+ if value == "current":
222
+ cur = current(day)
223
+ if cur is None:
224
+ raise core.UsageError(f"--stack current: no declared stack covers {day or today()}; declared: "
225
+ f"{declared_list()} (name one, or --stack none)")
226
+ return cur
227
+ d = declared()
228
+ if value not in d:
229
+ undeclared = " (defined but not declared yet)" if value in load() else ""
230
+ raise core.UsageError(f"--stack {value!r}{undeclared}: not a declared stack; declared: {declared_list()}; "
231
+ f"or current, none")
232
+ return d[value]
233
+
234
+
235
+ def toolchain_version(stack: dict) -> str:
236
+ return stack["lean_toolchain"].split(":", 1)[1]
237
+
238
+
239
+ def page_url(name: str) -> str:
240
+ return DOCS_URL.format(name=name)
241
+
242
+
243
+ def _range_ok(rng: str, version: str) -> bool | None:
244
+ m = RANGE.match(rng)
245
+ v = re.match(r"^(\d+)\.(\d+)\.(\d+)", version or "")
246
+ if not m or not v:
247
+ return None
248
+ lo = tuple(int(x) for x in m.groups()[:3])
249
+ hi = tuple(int(x) for x in m.groups()[3:])
250
+ have = tuple(int(x) for x in v.groups())
251
+ return lo <= have and have[:2] < hi
252
+
253
+
254
+ def _manifest_mathlib(blob: bytes | None) -> dict | None:
255
+ """{rev, input_rev} of the mathlib package in a lake-manifest.json; {} when it lists none; None when the
256
+ manifest is absent or unreadable."""
257
+ try:
258
+ data = json.loads(blob.decode("utf-8")) if blob is not None else None
259
+ except (ValueError, UnicodeDecodeError):
260
+ return None
261
+ pkgs = data.get("packages") if isinstance(data, dict) else None
262
+ if not isinstance(pkgs, list):
263
+ return None
264
+ for p in pkgs:
265
+ if isinstance(p, dict) and str(p.get("name", "")).casefold() in ("mathlib", "«mathlib»"):
266
+ return {"rev": str(p.get("rev") or "") or None, "input_rev": str(p.get("inputRev") or "") or None}
267
+ return {}
268
+
269
+
270
+ def declared_key(repo: pathlib.Path, rev: str = "HEAD") -> str | None:
271
+ """The `stack:` value of coverage.yaml committed at rev (None: no file, no key, or unreadable YAML). Read
272
+ loosely: the stack check never depends on the rest of the coverage file being valid."""
273
+ blob = core.git_show_bytes(repo, "coverage.yaml", rev)
274
+ if blob is None:
275
+ return None
276
+ try:
277
+ doc = yaml.safe_load(blob.decode("utf-8"))
278
+ except (UnicodeDecodeError, yaml.YAMLError):
279
+ return None
280
+ v = doc.get("stack") if isinstance(doc, dict) else None
281
+ return str(v) if v is not None else None
282
+
283
+
284
+ def check(repo: pathlib.Path, name: str, rev: str = "HEAD", comparator: dict | None = None,
285
+ comparator_path: str | None = None, day: dt.date | None = None,
286
+ stacks: dict[str, dict] | None = None) -> dict:
287
+ """The package at repo (committed at rev) against the stack it declares. The JSON view:
288
+ {name, declared, matches, supported_until, window, toolchain, mathlib, comparator_tools, lean_pkg,
289
+ mismatches[], warnings[]}. matches: the toolchain and the Mathlib commit both match (None when the stack
290
+ is not declared here); comparator digests and the window only warn."""
291
+ from . import __version__
292
+ d = declared(stacks)
293
+ out: dict = {"name": name, "declared": name in d, "matches": None, "supported_until": None, "window": None,
294
+ "toolchain": None, "mathlib": None, "comparator_tools": None, "lean_pkg": None,
295
+ "mismatches": [], "warnings": []}
296
+ if name not in d:
297
+ out["warnings"].append(f"coverage.yaml declares stack {name}, which lean-pkg {__version__} does not "
298
+ f"declare (declared: {declared_list(stacks)}); the pins are not checked")
299
+ return out
300
+ s = d[name]
301
+ out["supported_until"] = s["supported_until"].isoformat()
302
+ out["window"] = window(s, day)
303
+ if out["window"] == "past":
304
+ out["warnings"].append(f"stack {name} is past its window (supported until {s['supported_until']}); "
305
+ f"move to {s['successor'] or 'a newer stack'} (docs/stacks/README.md)")
306
+ elif out["window"] == "before":
307
+ out["warnings"].append(f"stack {name}'s window starts {s['published']}")
308
+ in_range = _range_ok(s["lean_pkg"], __version__)
309
+ out["lean_pkg"] = {"range": s["lean_pkg"], "version": __version__, "in_range": in_range}
310
+ if in_range is False:
311
+ out["warnings"].append(f"lean-pkg {__version__} is outside stack {name}'s supported range {s['lean_pkg']}")
312
+ tc_blob = core.git_show_bytes(repo, "lean-toolchain", rev)
313
+ tc = tc_blob.decode("utf-8", "replace").strip() if tc_blob is not None else None
314
+ tc_ok = tc == s["lean_toolchain"]
315
+ out["toolchain"] = {"stack": s["lean_toolchain"], "package": tc, "matches": tc_ok}
316
+ if not tc_ok:
317
+ out["mismatches"].append(f"lean-toolchain is {tc or '(not committed)'}, the stack pins {s['lean_toolchain']}")
318
+ ml = _manifest_mathlib(core.git_show_bytes(repo, "lake-manifest.json", rev))
319
+ want_rev, want_commit = s["mathlib"]["rev"], s["mathlib"]["commit"]
320
+ if ml == {}: # a package without Mathlib: the toolchain is the whole pin
321
+ out["mathlib"] = {"stack_rev": want_rev, "stack_commit": want_commit, "package": None, "input_rev": None,
322
+ "matches": None}
323
+ ml_ok = True
324
+ else:
325
+ commit = (ml or {}).get("rev")
326
+ ml_ok = commit == want_commit
327
+ out["mathlib"] = {"stack_rev": want_rev, "stack_commit": want_commit, "package": commit,
328
+ "input_rev": (ml or {}).get("input_rev"), "matches": ml_ok}
329
+ if ml is None:
330
+ out["mismatches"].append("lake-manifest.json is not committed (or unreadable): the Mathlib pin is "
331
+ "unknown")
332
+ elif not ml_ok:
333
+ shown = f"{commit[:12]}" if commit else "(no rev)"
334
+ out["mismatches"].append(f"Mathlib is at {shown} (input rev {(ml or {}).get('input_rev')}), the stack "
335
+ f"pins {want_rev} = {want_commit[:12]}")
336
+ out["matches"] = tc_ok and ml_ok
337
+ if comparator is not None:
338
+ out["comparator_tools"] = comparator_check(s, comparator, comparator_path)
339
+ if out["comparator_tools"]["differ"]:
340
+ which = f"the comparator receipt {comparator_path}" if comparator_path else "the comparator receipt"
341
+ out["warnings"].append(f"{which} records tool digests that differ from stack {name}'s "
342
+ f"({', '.join(out['comparator_tools']['differ'])}); the stack's digests are "
343
+ f"those of Linux x86_64")
344
+ for m in out["mismatches"]:
345
+ out["warnings"].append(f"stack {name}: {m}")
346
+ return out
347
+
348
+
349
+ def comparator_check(stack: dict, comp: dict, path: str | None = None) -> dict:
350
+ """A comparator receipt's toolchain digests against the stack's binaries_sha256: {receipt, mechanism,
351
+ matches, differ[]} (differ: digest keys that differ or are missing; a legacy receipt differs as a whole)."""
352
+ want = stack["comparator_tools"]["binaries_sha256"]
353
+ mech = comp.get("mechanism") or "legacy"
354
+ tools = comp.get("tools") if isinstance(comp.get("tools"), dict) else {}
355
+ if mech != stack["comparator_tools"]["mechanism"]:
356
+ differ = ["mechanism"]
357
+ else:
358
+ differ = sorted(f"{k}_sha256" for k, v in want.items() if tools.get(f"{k}_sha256") != v)
359
+ return {"receipt": path, "mechanism": mech, "matches": not differ, "differ": differ}
360
+
361
+
362
+ def summary_line(res: dict) -> tuple[str, str]:
363
+ """(level, detail) for a doctor line or a verify note."""
364
+ if not res["declared"]:
365
+ return "warn", res["warnings"][0]
366
+ head = f"on stack {res['name']} (supported until {res['supported_until']})"
367
+ if res["matches"] and not res["warnings"]:
368
+ return "ok", head
369
+ if res["matches"]:
370
+ return "warn", head + "; " + "; ".join(res["warnings"])
371
+ return "warn", f"declares stack {res['name']} but its pins differ: " + "; ".join(res["mismatches"]) + (
372
+ "" if len(res["warnings"]) == len(res["mismatches"]) else
373
+ "; " + "; ".join(w for w in res["warnings"] if not w.startswith(f"stack {res['name']}: ")))