guldo-cli 0.1.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 (134) hide show
  1. guldo/__init__.py +0 -0
  2. guldo/_src/COMPILER.md +329 -0
  3. guldo/_src/DEPLOY.md +200 -0
  4. guldo/_src/LAUNCH.md +85 -0
  5. guldo/_src/PROTOCOL.md +294 -0
  6. guldo/_src/RULES.md +25 -0
  7. guldo/_src/SUBMIT.md +170 -0
  8. guldo/_src/__init__.py +0 -0
  9. guldo/_src/attest.py +257 -0
  10. guldo/_src/build_site.py +958 -0
  11. guldo/_src/bundle_templates/check.py +1382 -0
  12. guldo/_src/bundle_templates/qcheck.py +253 -0
  13. guldo/_src/bundle_templates/qscore.py +402 -0
  14. guldo/_src/bundle_templates/score.py +649 -0
  15. guldo/_src/certificate.py +828 -0
  16. guldo/_src/certs_site.py +108 -0
  17. guldo/_src/claims.py +343 -0
  18. guldo/_src/compile_domain.py +1312 -0
  19. guldo/_src/compile_quality.py +286 -0
  20. guldo/_src/count_runner.py +248 -0
  21. guldo/_src/counted.py +274 -0
  22. guldo/_src/declared.py +215 -0
  23. guldo/_src/deploy/Caddyfile +48 -0
  24. guldo/_src/deploy/ledger-backup.service +9 -0
  25. guldo/_src/deploy/ledger-backup.sh +73 -0
  26. guldo/_src/deploy/ledger-backup.timer +10 -0
  27. guldo/_src/deploy/ledger-export.service +12 -0
  28. guldo/_src/deploy/ledger-export.timer +9 -0
  29. guldo/_src/deploy/ledger-web.service +38 -0
  30. guldo/_src/deploy/pin_cpu.sh +34 -0
  31. guldo/_src/deploy/provision_eval.sh +128 -0
  32. guldo/_src/deploy_smoke.py +148 -0
  33. guldo/_src/dlog_experiment.py +165 -0
  34. guldo/_src/domains/aidecode/compiled.json +586 -0
  35. guldo/_src/domains/aidecode/decl.py +134 -0
  36. guldo/_src/domains/aidecode/reference.py +73 -0
  37. guldo/_src/domains/aiinfer/compiled.json +722 -0
  38. guldo/_src/domains/aiinfer/decl.py +91 -0
  39. guldo/_src/domains/aiinfer/reference.py +42 -0
  40. guldo/_src/domains/dlog/compiled.json +248 -0
  41. guldo/_src/domains/dlog/decl.py +41 -0
  42. guldo/_src/domains/dlog/reference.py +10 -0
  43. guldo/_src/domains/maxcut/compiled.json +291 -0
  44. guldo/_src/domains/maxcut/decl.py +46 -0
  45. guldo/_src/domains/maxcut/reference.py +16 -0
  46. guldo/_src/drift_check.py +89 -0
  47. guldo/_src/export_bundle.py +750 -0
  48. guldo/_src/extrapolate.py +326 -0
  49. guldo/_src/families.py +53 -0
  50. guldo/_src/gen_cheat_table.py +36 -0
  51. guldo/_src/gpu_meter.py +634 -0
  52. guldo/_src/gpu_runner.py +63 -0
  53. guldo/_src/harness.py +273 -0
  54. guldo/_src/instances.py +86 -0
  55. guldo/_src/instances_factor.py +40 -0
  56. guldo/_src/instances_mlwe.py +69 -0
  57. guldo/_src/judge.py +278 -0
  58. guldo/_src/limits_plan.py +158 -0
  59. guldo/_src/official.py +189 -0
  60. guldo/_src/ops.py +281 -0
  61. guldo/_src/portal.py +313 -0
  62. guldo/_src/portal_core.py +57 -0
  63. guldo/_src/power.py +174 -0
  64. guldo/_src/prereg.py +173 -0
  65. guldo/_src/public_portal.py +500 -0
  66. guldo/_src/quality_core.py +126 -0
  67. guldo/_src/recheck.py +236 -0
  68. guldo/_src/remeasure.py +88 -0
  69. guldo/_src/report_html.py +493 -0
  70. guldo/_src/results/.keep +0 -0
  71. guldo/_src/rounds.py +846 -0
  72. guldo/_src/runner.py +52 -0
  73. guldo/_src/sandbox/Dockerfile +11 -0
  74. guldo/_src/sandbox/Dockerfile.v2 +19 -0
  75. guldo/_src/sandbox/README.md +40 -0
  76. guldo/_src/sandbox/linux_selftest.py +117 -0
  77. guldo/_src/sandbox/meter.py +89 -0
  78. guldo/_src/sandbox/meter_core.py +28 -0
  79. guldo/_src/site_assets.py +176 -0
  80. guldo/_src/site_live_check.py +79 -0
  81. guldo/_src/solvers/aidecode_flops_kv.py +73 -0
  82. guldo/_src/solvers/aidecode_flops_lossy.py +73 -0
  83. guldo/_src/solvers/aidecode_flops_ref.py +64 -0
  84. guldo/_src/solvers/aidecode_kv.py +76 -0
  85. guldo/_src/solvers/aidecode_kv_f32.py +77 -0
  86. guldo/_src/solvers/aidecode_lossy.py +76 -0
  87. guldo/_src/solvers/aidecode_repeat.py +5 -0
  88. guldo/_src/solvers/aiinfer_batched.py +40 -0
  89. guldo/_src/solvers/aiinfer_f32.py +41 -0
  90. guldo/_src/solvers/aiinfer_gpu_batched.py +42 -0
  91. guldo/_src/solvers/aiinfer_gpu_ref.py +45 -0
  92. guldo/_src/solvers/aiinfer_lossy.py +42 -0
  93. guldo/_src/solvers/baseline_bkz.py +14 -0
  94. guldo/_src/solvers/cheat_lookup.py +24 -0
  95. guldo/_src/solvers/cheat_table.json +1 -0
  96. guldo/_src/solvers/cheat_table_v1_stale.json +1 -0
  97. guldo/_src/solvers/daemon_cpu_hider.py +17 -0
  98. guldo/_src/solvers/dlog_bsgs.py +19 -0
  99. guldo/_src/solvers/dlog_stride4.py +18 -0
  100. guldo/_src/solvers/egg_base.py +11 -0
  101. guldo/_src/solvers/egg_eightaxis.py +68 -0
  102. guldo/_src/solvers/egg_template.py +11 -0
  103. guldo/_src/solvers/factor_brent.py +34 -0
  104. guldo/_src/solvers/factor_floyd.py +19 -0
  105. guldo/_src/solvers/factor_trial_fast_py.py +21 -0
  106. guldo/_src/solvers/factor_trial_np.py +21 -0
  107. guldo/_src/solvers/factor_trial_py.py +12 -0
  108. guldo/_src/solvers/fixed_overhead_ref.py +21 -0
  109. guldo/_src/solvers/fork_bomb.py +18 -0
  110. guldo/_src/solvers/gpu_noop.py +6 -0
  111. guldo/_src/solvers/hostile_probe.py +36 -0
  112. guldo/_src/solvers/kill_meter.py +27 -0
  113. guldo/_src/solvers/memory_bomb.py +10 -0
  114. guldo/_src/solvers/noop.py +5 -0
  115. guldo/_src/solvers/orphan_cpu_hider.py +16 -0
  116. guldo/_src/solvers/planted_peek.py +23 -0
  117. guldo/_src/solvers/sleeping_daemon_hang.py +12 -0
  118. guldo/_src/solvers/small_n_trick.py +22 -0
  119. guldo/_src/solvers/starter_template.py +21 -0
  120. guldo/_src/solvers/stdout_flood.py +9 -0
  121. guldo/_src/solvers/tmp_fill.py +10 -0
  122. guldo/_src/solvers/tuned_bkz.py +25 -0
  123. guldo/_src/static_check.py +214 -0
  124. guldo/_src/submit_check.py +166 -0
  125. guldo/_src/svp.py +889 -0
  126. guldo/_src/tensorops.py +304 -0
  127. guldo/_src/tflops.py +453 -0
  128. guldo/_src/tflops_runner.py +134 -0
  129. guldo/cli.py +60 -0
  130. guldo_cli-0.1.0.dist-info/METADATA +30 -0
  131. guldo_cli-0.1.0.dist-info/RECORD +134 -0
  132. guldo_cli-0.1.0.dist-info/WHEEL +5 -0
  133. guldo_cli-0.1.0.dist-info/entry_points.txt +2 -0
  134. guldo_cli-0.1.0.dist-info/top_level.txt +1 -0
guldo/_src/runner.py ADDED
@@ -0,0 +1,52 @@
1
+ """Child process: load a solver module, read one instance on stdin, print its answer as one JSON line on stdout.
2
+
3
+ Payload: {"args": [...]} and the solver is called as solve(*args). The older lattice payload {"basis": ..., "bound2": ...}
4
+ is still accepted. Answers: None (no answer), an integer, or a list of integers.
5
+
6
+ Anything the solver prints goes to STDERR, not stdout: stdout is the answer channel, and a stray print() would otherwise
7
+ corrupt it and get a correct solver marked wrong. (The harness also parses only the last line of stdout, so output a C
8
+ extension writes straight to file descriptor 1 cannot corrupt the answer either.)"""
9
+ import importlib.util
10
+ import json
11
+ import numbers
12
+ import os
13
+ import resource
14
+ import sys
15
+
16
+ # CPU cap set HERE (soft == hard, so the solver cannot raise it) rather than via subprocess preexec_fn, which is not
17
+ # safe when the harness spawns from several threads. Set before the solver module is even imported.
18
+ _lim = os.environ.get("SVP_CPU_LIMIT")
19
+ if _lim:
20
+ resource.setrlimit(resource.RLIMIT_CPU, (int(_lim), int(_lim)))
21
+
22
+
23
+ def normalize(out):
24
+ """Turn a solver's return value into something JSON-serializable, or raise TypeError for anything else."""
25
+ if out is None:
26
+ return None
27
+ if isinstance(out, bool):
28
+ raise TypeError("solve() returned a bool; return an int, a list of ints, or None")
29
+ if isinstance(out, numbers.Integral):
30
+ return int(out)
31
+ if isinstance(out, (list, tuple)):
32
+ if any(isinstance(c, bool) or not isinstance(c, numbers.Integral) for c in out):
33
+ raise TypeError("solve() returned a list containing non-integers")
34
+ return [int(c) for c in out]
35
+ raise TypeError(f"solve() returned {type(out).__name__}; return an int, a list of ints, or None")
36
+
37
+
38
+ def main():
39
+ path = sys.argv[1]
40
+ real_out, sys.stdout = sys.stdout, sys.stderr # solver prints (even at import time) cannot reach the answer channel
41
+ spec = importlib.util.spec_from_file_location("submission", path)
42
+ mod = importlib.util.module_from_spec(spec)
43
+ spec.loader.exec_module(mod)
44
+ req = json.loads(sys.stdin.read())
45
+ args = req["args"] if "args" in req else [req["basis"], req["bound2"]]
46
+ answer = normalize(mod.solve(*args))
47
+ real_out.write("\n" + json.dumps(answer) + "\n") # leading newline: the answer is always on its own, last line
48
+ real_out.flush()
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
@@ -0,0 +1,11 @@
1
+ # SUPERSEDED by Dockerfile.v2 (kept for the record). This version is WEAKER: no root meter, so CPU of orphaned
2
+ # descendants is not billed, and fpylll fails to import (missing cysignals). Do not use.
3
+ # Judge-side sandbox for UNTRUSTED submissions. One instance at a time, one pinned core, no network,
4
+ # read-only root, and the seed file is never mounted: the harness feeds instances on stdin only.
5
+ FROM python:3.12-slim
6
+ RUN pip install --no-cache-dir fpylll numpy
7
+ RUN useradd -m -u 10001 solver
8
+ WORKDIR /work
9
+ COPY runner.py /work/runner.py
10
+ USER solver
11
+ ENTRYPOINT ["python3", "/work/runner.py"]
@@ -0,0 +1,19 @@
1
+ # Judge-side sandbox for UNTRUSTED submissions (supersedes sandbox/Dockerfile).
2
+ # Build from the project root: docker build -t svp-solver -f sandbox/Dockerfile.v2 .
3
+ # meter.py runs as root and drops the solver child to uid 10001; the seed is never in the image or any mount.
4
+ FROM python:3.12-slim AS build
5
+ RUN apt-get update && apt-get install -y --no-install-recommends gcc g++ libc6-dev && rm -rf /var/lib/apt/lists/*
6
+ # Versions match the host venv the baselines were developed against. The base image is a floating tag: record its
7
+ # ID in every results file (harness does: meta "image") and rebuild only deliberately. Build with these pins is UNTESTED
8
+ # (Docker was not available when they were added).
9
+ RUN pip install --no-cache-dir --prefix=/install fpylll==0.6.4 cysignals==1.12.6 "numpy>=2,<3"
10
+
11
+ FROM python:3.12-slim
12
+ COPY --from=build /install /usr/local
13
+ RUN useradd -m -u 10001 solver
14
+ WORKDIR /work
15
+ COPY sandbox/strategies/default.json /opt/fplll/strategies/default.json
16
+ COPY runner.py /work/runner.py
17
+ COPY sandbox/meter.py /work/meter.py
18
+ COPY sandbox/meter_core.py /work/meter_core.py
19
+ ENTRYPOINT ["python3", "/work/meter.py"]
@@ -0,0 +1,40 @@
1
+ # Sandbox for judging untrusted submissions
2
+
3
+ harness.py today isolates only by fresh process, empty cwd, scrubbed env and RLIMIT_CPU. That is fine for your own
4
+ solvers, not for strangers'. For a real competition run each (instance, submission) pair like this, from a judge-side
5
+ driver that owns the seed (the container never sees it):
6
+
7
+ docker build --load -t svp-solver -f sandbox/Dockerfile.v2 .
8
+ docker run --rm -i --network none --read-only --tmpfs /tmp --cpus 1 --memory 4g --pids-limit 64 \
9
+ --cap-drop ALL --cap-add SETUID --cap-add SETGID --cap-add KILL --security-opt no-new-privileges -e BUDGET=120 \
10
+ -v "$PWD/submissions/x.py:/work/submission.py:ro" svp-solver /work/submission.py < payload.json
11
+
12
+ This is exactly the command `harness.py --sandbox docker` runs (test_docker_shim.py fails if the two ever differ), plus `--name` so the
13
+ host can kill the container on a timeout. Things that look optional and are not:
14
+ - `-e BUDGET=<cpu seconds>`: the meter reads its cap from the environment and fails without it.
15
+ - `--cap-add SETUID --cap-add SETGID`: the meter runs as root and must drop the solver to uid 10001; with every capability dropped
16
+ `setuid()` fails and no solver ever starts. The solver itself ends up with no capabilities (and `no-new-privileges` is set).
17
+ - `--cap-add KILL`: the meter (root) must signal solver processes that run as another uid; without CAP_KILL every `kill` fails with EPERM, the
18
+ wall deadline is never enforced, and a sleeping daemon is only stopped by the host's backstop (found by the first CI run of test_sandbox).
19
+ - `payload.json` is `{"args": [...]}`: `[basis rows, bound2]` for the lattice families, `[n]` for factoring.
20
+ - To pin a core as well, add `--cpuset-cpus N` by hand; the harness does not (see "Still open" in README.md).
21
+
22
+ Requirements the judge must hold to:
23
+ 1. Same machine, same pinned core, for baseline and every submission. Report CPU model in the results.
24
+ 2. Seed file lives outside the container and outside any mounted path.
25
+ 3. `--pids-limit` and a single `--cpus 1` stop fork/thread tricks from buying CPU time the meter doesn't see.
26
+ (CPU time is summed over children by the host, so threads would still be billed; the limit prevents resource games.)
27
+ 4. Time CPU via the host's cgroup/`docker stats` accounting, not the submission's own clock.
28
+
29
+ Status: harness.py has `--sandbox docker` (hardened `docker run`, named container killed and removed on host timeout,
30
+ image ID recorded in every results file) and sandbox/Dockerfile.v2 + meter.py are the supported path; the older
31
+ sandbox/Dockerfile is superseded and weaker. UNVERIFIED: after the meter was rewritten to reap and bill orphaned
32
+ descendants and to kill every solver-uid process at the wall deadline, Docker became unavailable and test_sandbox.py
33
+ never passed. Run `python3 -m unittest test_sandbox -v` (needs the image) before trusting any sandboxed result.
34
+ The harness-side control flow is tested with a fake `docker` (test_docker_shim.py), which does not test the sandbox.
35
+ Docker-free way to verify the meter: copy the project to any Linux machine (a throwaway VM or CI runner) and run
36
+ `sudo python3 sandbox/linux_selftest.py` (or `make linux-selftest`). It runs the orphan, daemon, hang and privilege
37
+ red-team solvers through meter.py directly (the meter's SOLVER_UID and RUNNER are env-overridable for this) and prints
38
+ PASS/FAIL per check. It does not test the container flags (read-only filesystem, no network, pid cap), which still need
39
+ Docker. It has not been executed yet: it was written on macOS, where it only skips.
40
+ Judge rule: the seed file must live outside the project tree and outside any mount (judge.py new-seed enforces it).
@@ -0,0 +1,117 @@
1
+ """Verify sandbox/meter.py on any Linux machine, WITHOUT Docker. Needs root (the meter drops the solver to an unprivileged
2
+ uid) and the project checked out. Intended for a throwaway VM or CI runner:
3
+
4
+ sudo python3 sandbox/linux_selftest.py
5
+
6
+ It feeds the red-team solvers through meter.py exactly as the container entrypoint would and checks:
7
+ * an orphaned child burning 4 CPU-s is BILLED (>= 3.5 s), not hidden
8
+ * a double-forked daemon burning 4 CPU-s is billed
9
+ * a sleeping daemon holding the stdout pipe cannot hang the meter (it finishes, flagged overrun, within the deadline)
10
+ * the solver runs as the unprivileged uid and cannot setuid(0)
11
+ Exit 0 = all pass. It does NOT test the Docker flags (read-only fs, no network, pid cap): those need the container.
12
+ STATUS: written on macOS; never executed on Linux.
13
+ """
14
+ import json
15
+ import os
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ ROOT = os.path.dirname(HERE)
23
+ UID = 54321 # unprivileged uid for the solver; created if missing
24
+
25
+
26
+ def ensure_user():
27
+ r = subprocess.run(["id", str(UID)], capture_output=True)
28
+ if r.returncode:
29
+ subprocess.run(["useradd", "-M", "-u", str(UID), "-s", "/usr/sbin/nologin", "svpsolver"], check=True)
30
+
31
+
32
+ def run_meter(solver_src, budget=3):
33
+ """Run solver source through meter.py; returns (parsed meter JSON, wall seconds)."""
34
+ with tempfile.TemporaryDirectory() as td:
35
+ os.chmod(td, 0o755)
36
+ path = os.path.join(td, "submission.py")
37
+ with open(path, "w") as f:
38
+ f.write(solver_src)
39
+ os.chmod(path, 0o644)
40
+ env = {"PATH": os.environ.get("PATH", ""), "BUDGET": str(budget), "SOLVER_UID": str(UID),
41
+ "RUNNER": os.path.join(ROOT, "runner.py")}
42
+ t0 = time.time()
43
+ r = subprocess.run([sys.executable, os.path.join(HERE, "meter.py"), path], input=json.dumps(
44
+ {"basis": [[1]], "bound2": 1}).encode(), capture_output=True, env=env, timeout=budget * 3 + 40)
45
+ wall = time.time() - t0
46
+ return json.loads(r.stdout.decode().strip().splitlines()[-1]), wall
47
+
48
+
49
+ ORPHAN = """
50
+ import os, sys, time
51
+ def solve(basis, bound2):
52
+ if os.fork() == 0:
53
+ t = time.process_time()
54
+ while time.process_time() - t < 4.0: pass
55
+ sys.stdout.write("null"); sys.stdout.flush(); os._exit(0)
56
+ os._exit(0)
57
+ """
58
+ DAEMON = """
59
+ import os, time
60
+ def solve(basis, bound2):
61
+ if os.fork() == 0:
62
+ os.setsid()
63
+ if os.fork() == 0:
64
+ for fd in (0, 1, 2): os.close(fd)
65
+ t = time.process_time()
66
+ while time.process_time() - t < 4.0: pass
67
+ os._exit(0)
68
+ return None
69
+ """
70
+ SLEEPER = """
71
+ import os, time
72
+ def solve(basis, bound2):
73
+ if os.fork() == 0:
74
+ os.setsid()
75
+ while True: time.sleep(1)
76
+ os._exit(0)
77
+ """
78
+ WHOAMI = """
79
+ import os
80
+ def solve(basis, bound2):
81
+ try:
82
+ os.setuid(0); root = True
83
+ except PermissionError:
84
+ root = False
85
+ raise RuntimeError(repr({"uid": os.getuid(), "can_setuid_root": root}))
86
+ """
87
+
88
+
89
+ def main():
90
+ if not sys.platform.startswith("linux") or os.geteuid() != 0:
91
+ print("SKIP: needs Linux and root")
92
+ return 0
93
+ ensure_user()
94
+ failures = []
95
+
96
+ def check(name, cond, detail):
97
+ print(("PASS " if cond else "FAIL ") + name + " " + detail)
98
+ if not cond:
99
+ failures.append(name)
100
+
101
+ m, wall = run_meter(ORPHAN, budget=10)
102
+ check("orphaned child CPU is billed", m["cpu"] >= 3.5, f"billed {m['cpu']:.2f}s of ~4.0s real")
103
+ m, wall = run_meter(DAEMON, budget=10)
104
+ check("detached daemon CPU is billed", m["cpu"] >= 3.5, f"billed {m['cpu']:.2f}s of ~4.0s real")
105
+ m, wall = run_meter(SLEEPER, budget=2) # deadline = 2*3+10 = 16 s
106
+ check("sleeping daemon cannot hang the meter", wall < 40 and m["overrun"], f"returned after {wall:.1f}s overrun={m['overrun']}")
107
+ left = subprocess.run(["pgrep", "-u", str(UID)], capture_output=True, text=True).stdout.split()
108
+ check("no solver processes are left behind", not left, f"left: {left}")
109
+ m, _ = run_meter(WHOAMI, budget=5)
110
+ check("solver is unprivileged and cannot setuid(0)", f"'uid': {UID}" in m["err"] and "'can_setuid_root': False" in m["err"],
111
+ m["err"].strip().splitlines()[-1][:120] if m["err"].strip() else "no stderr")
112
+ print("\nALL PASS" if not failures else f"\nFAILED: {failures}")
113
+ return 1 if failures else 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ sys.exit(main())
@@ -0,0 +1,89 @@
1
+ """Judge-controlled container entrypoint. Runs as root; the solver runs as an unprivileged uid in a child process, so it
2
+ cannot read /proc/<meter>/fd or forge the meter's result. CPU = rusage of that child (user+sys). Emits ONE JSON line."""
3
+ import ctypes
4
+ import json
5
+ import os
6
+ import resource
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+ import time
11
+
12
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
+ import meter_core # noqa: E402
14
+
15
+ SOLVER_UID = int(os.environ.get("SOLVER_UID", "10001")) # overridable so the meter can be self-tested outside Docker
16
+ RUNNER = os.environ.get("RUNNER", "/work/runner.py")
17
+ budget = float(os.environ["BUDGET"])
18
+ payload = sys.stdin.buffer.read()
19
+ deadline = time.time() + budget * 3 + 10
20
+ ctypes.CDLL(None).prctl(36, 1, 0, 0, 0) # PR_SET_CHILD_SUBREAPER: orphans reparent to us even if we are not PID 1
21
+
22
+
23
+ def solver_pids():
24
+ pids = []
25
+ for d in os.listdir("/proc"):
26
+ if d.isdigit():
27
+ try:
28
+ with open(f"/proc/{d}/status") as f:
29
+ for line in f:
30
+ if line.startswith("Uid:"):
31
+ if int(line.split()[1]) == SOLVER_UID:
32
+ pids.append(int(d))
33
+ break
34
+ except OSError:
35
+ pass
36
+ return pids
37
+
38
+
39
+ def drop():
40
+ resource.setrlimit(resource.RLIMIT_CPU, (int(budget) + 1, int(budget) + 1))
41
+ os.setgroups([])
42
+ os.setgid(SOLVER_UID)
43
+ os.setuid(SOLVER_UID)
44
+
45
+
46
+ p = subprocess.Popen([sys.executable, RUNNER, sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
47
+ stderr=subprocess.PIPE, preexec_fn=drop, cwd="/tmp",
48
+ env={"PATH": os.environ.get("PATH", ""), "OMP_NUM_THREADS": "1", "PYTHONHASHSEED": "0"})
49
+
50
+
51
+ def kill_all():
52
+ for pid in solver_pids():
53
+ try:
54
+ os.kill(pid, signal.SIGKILL)
55
+ except OSError:
56
+ pass
57
+
58
+
59
+ def reap():
60
+ try:
61
+ while os.waitpid(-1, os.WNOHANG)[0]:
62
+ pass
63
+ except ChildProcessError:
64
+ pass
65
+
66
+
67
+ def try_finish():
68
+ try:
69
+ return p.communicate(timeout=1)
70
+ except subprocess.TimeoutExpired:
71
+ return None
72
+
73
+
74
+ overrun = False
75
+ try:
76
+ out, err = p.communicate(payload, timeout=max(deadline - time.time(), 1))
77
+ except subprocess.TimeoutExpired:
78
+ # Kill EVERY solver process before collecting output: an orphan still holding the stdout pipe would otherwise block
79
+ # communicate() forever (a sleeping daemon could hang the judge). Logic + tests: meter_core.py, test_meter_core.py.
80
+ out, err = meter_core.kill_until_done(kill_all, try_finish)
81
+ overrun = True
82
+
83
+ # Orphaned descendants (double-fork, parent exits first) reparent to us. Wait for ALL of them and reap them, so their
84
+ # CPU lands in RUSAGE_CHILDREN; kill whatever is still alive at the wall deadline.
85
+ overrun |= meter_core.drain(solver_pids, kill_all, reap, time.time, time.sleep, deadline)
86
+
87
+ r = resource.getrusage(resource.RUSAGE_CHILDREN)
88
+ sys.stdout.write(json.dumps({"cpu": r.ru_utime + r.ru_stime, "rc": p.returncode, "overrun": overrun,
89
+ "out": out.decode(errors="replace")[-4_000_000:], "err": err.decode(errors="replace")[-1500:]}))
@@ -0,0 +1,28 @@
1
+ """Pure control logic of the judge's meter, with every OS interaction injected so it can be tested on any machine against
2
+ a simulated process table and clock (see test_meter_core.py). meter.py supplies the real /proc, kill, waitpid and clock."""
3
+
4
+
5
+ def kill_until_done(kill_all, try_finish):
6
+ """After the wall deadline: keep killing every solver process until the pipe is closed and the result is collected.
7
+ try_finish() returns the result, or None if something still holds the pipe. Re-killing each round matters: a solver
8
+ that keeps forking can add a pipe holder after any single snapshot of the process table."""
9
+ while True:
10
+ kill_all()
11
+ res = try_finish()
12
+ if res is not None:
13
+ return res
14
+
15
+
16
+ def drain(solver_pids, kill_all, reap, now, sleep, deadline, poll=0.02):
17
+ """Wait until no solver process is left, reaping as we go so their CPU is billed. At/after `deadline` kill whatever
18
+ is alive (every round, so kill-resistant or respawning processes are still caught). Returns True if the deadline had
19
+ to be enforced (an overrun)."""
20
+ overrun = False
21
+ while True:
22
+ reap()
23
+ if not solver_pids():
24
+ return overrun
25
+ if now() > deadline:
26
+ overrun = True
27
+ kill_all()
28
+ sleep(poll)
@@ -0,0 +1,176 @@
1
+ """CSS and JavaScript for the Guldo site (written to site/assets/ by build_site.py).
2
+
3
+ Design: a measuring-instrument feel. Cool neutrals, one validated blue for the data, mono numerals, restrained type. Every
4
+ colour is a token defined on :root, with dark values redefined for the system setting and for the manual toggle."""
5
+
6
+ CSS = """
7
+ :root{--bg:#F2F4F6;--card:#FCFCFB;--ink:#10151A;--ink2:#444C54;--muted:#626C76;--line:#D6DCE1;--line2:#E6EAEE;
8
+ --accent:#2A78D6;--on-accent:#FFFFFF;--accent-ink:#1B5CAB;--accent-soft:#BBD5F3;--ok:#1D6B3B;--ok-bg:#DCEFE2;--warn:#8A4B00;--warn-bg:#F9E8CC;
9
+ --idle:#4F5961;--idle-bg:#E3E6E9;--chip:#EAEFF5;
10
+ --display:"Bricolage Grotesque","Avenir Next","Segoe UI",system-ui,sans-serif;--body:"Instrument Sans","Segoe UI",system-ui,sans-serif;
11
+ --mono:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,monospace;--maxw:1040px}
12
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#0E1113;--card:#171B1E;--ink:#ECEFF1;--ink2:#BCC4CA;--muted:#929CA4;
13
+ --line:#2B3237;--line2:#22282C;--accent:#3987E5;--on-accent:#08121D;--accent-ink:#7DB3F2;--accent-soft:#1E3F66;--ok:#79D09A;--ok-bg:#16301F;--warn:#F0B565;
14
+ --warn-bg:#3A2A10;--idle:#B6BEC5;--idle-bg:#262B2F;--chip:#1E252B;color-scheme:dark}}
15
+ :root[data-theme="dark"]{--bg:#0E1113;--card:#171B1E;--ink:#ECEFF1;--ink2:#BCC4CA;--muted:#929CA4;--line:#2B3237;--line2:#22282C;
16
+ --accent:#3987E5;--on-accent:#08121D;--accent-ink:#7DB3F2;--accent-soft:#1E3F66;--ok:#79D09A;--ok-bg:#16301F;--warn:#F0B565;--warn-bg:#3A2A10;
17
+ --idle:#B6BEC5;--idle-bg:#262B2F;--chip:#1E252B;color-scheme:dark}
18
+ *{box-sizing:border-box}
19
+ html{scroll-behavior:smooth;scroll-padding-top:72px}
20
+ body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.62 var(--body);padding-inline:max(16px,4vw);padding-block:0 64px}
21
+ .wrap{max-width:var(--maxw);margin:0 auto}
22
+ .skip{position:absolute;left:-999px;top:8px;background:var(--ink);color:var(--card);padding:8px 12px;border-radius:6px;z-index:20}
23
+ .skip:focus{left:8px}
24
+ a{color:var(--accent-ink);text-underline-offset:3px;text-decoration-thickness:1px}
25
+ a:hover{text-decoration-thickness:2px}
26
+ :focus-visible{outline:2px solid var(--ink);outline-offset:2px;border-radius:3px}
27
+ header.top{display:flex;flex-wrap:wrap;align-items:center;gap:10px 22px;padding-block:18px;border-bottom:1px solid var(--line)}
28
+ .brand{font:600 18px var(--display);letter-spacing:-.01em;color:var(--ink);text-decoration:none;display:flex;gap:9px;align-items:center}
29
+ .brand svg{flex:none}
30
+ nav.main{display:flex;flex-wrap:wrap;gap:4px 18px;margin-left:auto;align-items:center}
31
+ nav.main a{color:var(--ink2);text-decoration:none;font-size:14.5px;padding:4px 0;border-bottom:2px solid transparent}
32
+ nav.main a:hover{color:var(--ink)} nav.main a[aria-current="page"]{color:var(--ink);border-bottom-color:var(--accent)}
33
+ .theme{font:600 13px var(--body);background:var(--chip);color:var(--ink2);border:1px solid var(--line);border-radius:999px;padding:5px 12px;cursor:pointer}
34
+ .theme:hover{color:var(--ink)}
35
+ h1{font:600 clamp(34px,6.2vw,62px)/1.02 var(--display);letter-spacing:-.03em;margin:0 0 16px;text-wrap:balance}
36
+ h2{font:600 clamp(23px,3.4vw,31px)/1.15 var(--display);letter-spacing:-.02em;margin:0 0 12px;text-wrap:balance}
37
+ h3{font:600 18px/1.3 var(--display);letter-spacing:-.01em;margin:0 0 6px}
38
+ p{margin:0 0 14px;max-width:68ch} ul,ol{margin:0 0 14px;padding-left:22px;max-width:68ch} li{margin-bottom:6px}
39
+ .lede{font-size:clamp(17px,2.2vw,20px);color:var(--ink2);max-width:58ch;line-height:1.55}
40
+ .muted{color:var(--muted)} .small{font-size:13.5px} .mono{font-family:var(--mono);font-variant-numeric:tabular-nums} .strong{font-weight:600}
41
+ main{padding-block:44px 8px;display:grid;gap:64px}
42
+ section.block{display:grid;gap:18px}
43
+ .kicker{font:600 12px/1.35 var(--body);letter-spacing:.09em;text-transform:uppercase;color:var(--muted);margin:0 0 10px}
44
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:22px;min-width:0}
45
+ .hero{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(0,1fr);gap:40px;align-items:center}
46
+ @media (max-width:820px){.hero{grid-template-columns:1fr;gap:28px}}
47
+ .result{display:grid;gap:10px}
48
+ .result .num{font:600 clamp(56px,9vw,96px)/.95 var(--display);letter-spacing:-.04em;color:var(--accent-ink)}
49
+ .result .num small{font:600 .3em var(--display);letter-spacing:0;margin-left:8px;color:var(--ink2)}
50
+ .btnrow{display:flex;flex-wrap:wrap;gap:10px;margin-top:6px}
51
+ .btn{display:inline-block;font:600 15px var(--body);padding:11px 18px;border-radius:9px;text-decoration:none;border:1px solid var(--line);color:var(--ink);background:var(--card)}
52
+ .btn.primary{background:var(--accent);border-color:var(--accent);color:var(--on-accent)} .btn:hover{filter:brightness(.97)}
53
+ .grid3{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(250px,100%),1fr));gap:16px}
54
+ .grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(215px,1fr));gap:14px}
55
+ .step{display:grid;grid-template-columns:minmax(0,1fr);gap:8px;align-content:start}
56
+ .step .n{font:600 13px var(--mono);color:var(--accent-ink);background:var(--chip);width:30px;height:30px;border-radius:50%;display:grid;place-items:center}
57
+ .pill{display:inline-flex;gap:6px;align-items:center;border-radius:999px;padding:3px 11px 3px 8px;font-size:13px;font-weight:600;width:fit-content}
58
+ .pill svg{flex:none}
59
+ .pill.ok{background:var(--ok-bg);color:var(--ok)} .pill.warn{background:var(--warn-bg);color:var(--warn)} .pill.idle{background:var(--idle-bg);color:var(--idle)}
60
+ .pill.info{background:var(--chip);color:var(--accent-ink)}
61
+ .status{display:grid;gap:10px}
62
+ .status .row{display:grid;grid-template-columns:minmax(110px,150px) 1fr;gap:6px 16px;align-items:start;padding-block:10px;border-top:1px solid var(--line2)}
63
+ .status .row:first-child{border-top:0}
64
+ @media (max-width:560px){.status .row{grid-template-columns:1fr}}
65
+ .banner{display:flex;gap:12px;align-items:flex-start;background:var(--warn-bg);color:var(--warn);border-radius:10px;padding:12px 16px;margin-top:22px}
66
+ .banner p{margin:0;color:var(--ink);font-size:14.5px;max-width:none} .banner svg{flex:none;margin-top:3px}
67
+ .scroll{overflow-x:auto}
68
+ table.lb{border-collapse:collapse;width:100%;font-size:14.5px}
69
+ .lb th{font:600 11.5px/1.2 var(--body);letter-spacing:.06em;text-transform:uppercase;color:var(--muted);text-align:left;padding:8px 14px 8px 0;border-bottom:1px solid var(--line)}
70
+ .lb td{padding:11px 14px 11px 0;border-bottom:1px solid var(--line2);vertical-align:top}
71
+ .lb .num{text-align:right;font-variant-numeric:tabular-nums} .lb tr.why td{padding-top:0}
72
+ .lb ul{margin:4px 0 0;padding-left:18px;color:var(--ink2);font-size:13px}
73
+ dl.facts{display:grid;gap:7px;margin:0;font-size:14.5px} dl.facts div{display:grid;grid-template-columns:minmax(120px,200px) 1fr;gap:12px} dt{color:var(--muted)} dd{margin:0;min-width:0}
74
+ @media (max-width:560px){dl.facts div{grid-template-columns:1fr;gap:0}}
75
+ figure{margin:0;display:grid;gap:8px} figcaption{font-weight:600;font-size:14px}
76
+ svg.chart{width:100%;height:auto;display:block;overflow:visible}
77
+ .grid{stroke:var(--line);stroke-width:1} .zero{stroke:var(--muted);stroke-width:1.2}
78
+ .tick,.n,.axis{fill:var(--ink2);font:11.5px var(--body)} .n{fill:var(--muted);font:11px var(--mono)} .axis{fill:var(--muted)}
79
+ .bar.used{fill:var(--accent)} .bar.usable{fill:var(--accent-soft);stroke:var(--accent);stroke-width:1.2}
80
+ .bar.unusable{fill:none;stroke:var(--muted);stroke-width:1.2;stroke-dasharray:4 3}
81
+ .credit{stroke:var(--ink);stroke-width:1.4;stroke-dasharray:6 4} .creditlbl{fill:var(--ink);font:600 12px var(--body)}
82
+ .pt.used{fill:var(--accent);stroke:var(--card);stroke-width:1.5} .pt.other{fill:none;stroke:var(--muted);stroke-width:1.5}
83
+ .whisk{stroke:var(--accent);stroke-width:1.6}
84
+ .bar:focus-visible,.pt:focus-visible{outline:2px solid var(--ink);outline-offset:2px}
85
+ .legend{display:flex;flex-wrap:wrap;gap:6px 16px;align-items:center;font-size:13px;color:var(--ink2);margin:0}
86
+ .sw{display:inline-block;width:12px;height:12px;border-radius:3px;margin-right:6px;vertical-align:-1px}
87
+ .sw.used{background:var(--accent)} .sw.usable{background:var(--accent-soft);border:1.2px solid var(--accent)} .sw.unusable{border:1.2px dashed var(--muted)}
88
+ .sw.line{width:18px;height:0;border-top:2px dashed var(--ink);border-radius:0;margin-left:10px}
89
+ details{border-top:1px solid var(--line2);padding-block:8px} details summary{cursor:pointer;font-weight:600;font-size:14.5px;padding:6px 0}
90
+ pre,code{font-family:var(--mono);font-size:13px} pre{background:var(--chip);border:1px solid var(--line2);border-radius:8px;padding:12px 14px;overflow-x:auto;margin:0 0 14px;max-width:100%;white-space:pre-wrap;word-break:break-word}
91
+ code{background:var(--chip);border-radius:4px;padding:1px 5px} pre code{background:none;padding:0}
92
+ .cmd{display:flex;gap:10px;align-items:flex-start;background:var(--chip);border:1px solid var(--line2);border-radius:8px;padding:10px 12px;margin-bottom:10px;min-width:0;max-width:100%}
93
+ .cmd code{background:none;flex:1;min-width:0;white-space:pre-wrap;overflow-wrap:anywhere} .cmd button{flex:none}
94
+ button.copy{font:600 12.5px var(--body);border:1px solid var(--line);background:var(--card);color:var(--ink2);border-radius:6px;padding:4px 10px;cursor:pointer}
95
+ .verify{display:grid;gap:10px;max-width:640px}
96
+ .verify textarea,.verify select{font:13px var(--mono);padding:10px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--ink);width:100%;min-width:0}
97
+ .verify textarea{min-height:64px;resize:vertical}
98
+ .vres{font-weight:600;min-height:1.5em}
99
+ .vres.good{color:var(--ok)} .vres.bad{color:var(--warn)}
100
+ .tl{display:grid;gap:0;border-left:2px solid var(--line);margin-left:6px;padding-left:20px}
101
+ .tl .item{padding-block:10px;position:relative} .tl .item::before{content:"";position:absolute;left:-27px;top:17px;width:10px;height:10px;border-radius:50%;background:var(--accent);border:2px solid var(--bg)}
102
+ .tl .item.void::before{background:var(--muted)}
103
+ footer.foot{margin-top:72px;padding-top:24px;border-top:1px solid var(--line);color:var(--muted);font-size:13.5px;display:grid;gap:8px}
104
+ footer.foot p{max-width:80ch;margin:0}
105
+ #tip{position:fixed;z-index:30;pointer-events:none;background:var(--ink);color:var(--card);font-size:12.5px;line-height:1.4;padding:7px 10px;border-radius:6px;max-width:300px;opacity:0;transition:opacity .08s}
106
+ @media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}#tip{transition:none}}
107
+ @media (max-width:560px){.card{padding:16px}main{gap:48px}}
108
+ """
109
+
110
+ JS = """
111
+ (function () {
112
+ var root = document.documentElement;
113
+ function store(k, v) { try { if (v === undefined) return localStorage.getItem(k); localStorage.setItem(k, v); } catch (e) { return null; } }
114
+ var saved = store('theme');
115
+ if (saved === 'dark' || saved === 'light') root.setAttribute('data-theme', saved);
116
+ var tbtn = document.getElementById('theme-toggle');
117
+ function isDark() { var t = root.getAttribute('data-theme'); return t ? t === 'dark' : window.matchMedia('(prefers-color-scheme: dark)').matches; }
118
+ function label() { if (tbtn) { tbtn.textContent = isDark() ? 'Light mode' : 'Dark mode'; tbtn.setAttribute('aria-pressed', String(isDark())); } }
119
+ if (tbtn) { tbtn.addEventListener('click', function () { var next = isDark() ? 'light' : 'dark'; root.setAttribute('data-theme', next); store('theme', next); label(); }); label(); }
120
+
121
+ var tip = document.getElementById('tip');
122
+ function show(e) {
123
+ var t = e.target && e.target.getAttribute && e.target.getAttribute('data-tip');
124
+ if (!tip) return;
125
+ if (!t) { tip.style.opacity = 0; return; }
126
+ tip.textContent = t; tip.style.opacity = 1;
127
+ var r = e.target.getBoundingClientRect();
128
+ var x = (e.clientX || r.left) + 14, y = (e.clientY || r.top) + 14;
129
+ tip.style.left = Math.min(x, window.innerWidth - tip.offsetWidth - 8) + 'px';
130
+ tip.style.top = Math.min(y, window.innerHeight - tip.offsetHeight - 8) + 'px';
131
+ }
132
+ document.addEventListener('mousemove', show);
133
+ document.addEventListener('focusin', show);
134
+ document.addEventListener('focusout', function () { if (tip) tip.style.opacity = 0; });
135
+
136
+ document.querySelectorAll('button.copy').forEach(function (b) {
137
+ b.addEventListener('click', function () {
138
+ var text = b.getAttribute('data-copy') || '';
139
+ var done = function () { var old = b.textContent; b.textContent = 'Copied'; setTimeout(function () { b.textContent = old; }, 1400); };
140
+ var fallback = function () {
141
+ var code = b.parentElement.querySelector('code'); if (code) { var s = window.getSelection(), r = document.createRange(); r.selectNodeContents(code); s.removeAllRanges(); s.addRange(r); }
142
+ b.textContent = 'Press Ctrl+C'; setTimeout(function () { b.textContent = 'Copy'; }, 2000);
143
+ };
144
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fallback); else fallback();
145
+ });
146
+ });
147
+
148
+ async function sha256hex(text) {
149
+ var bytes = new TextEncoder().encode(text.trim());
150
+ var digest = await crypto.subtle.digest('SHA-256', bytes);
151
+ return Array.prototype.map.call(new Uint8Array(digest), function (x) { return x.toString(16).padStart(2, '0'); }).join('');
152
+ }
153
+ var form = document.getElementById('verify');
154
+ if (form) {
155
+ var manifestEl = document.getElementById('runs-manifest');
156
+ var runs = []; try { runs = JSON.parse(manifestEl.textContent); } catch (e) { runs = []; }
157
+ var sel = document.getElementById('v-run'), seed = document.getElementById('v-seed'), res = document.getElementById('v-result');
158
+ runs.forEach(function (r, i) { var o = document.createElement('option'); o.value = String(i); o.textContent = r.label; sel.appendChild(o); });
159
+ function current() { return runs[Number(sel.value)]; }
160
+ document.getElementById('v-fill').addEventListener('click', function () {
161
+ var r = current(); if (!r) return;
162
+ if (r.seed) { seed.value = r.seed; res.textContent = 'Revealed seed filled in. Press Check.'; res.className = 'vres'; }
163
+ else { res.textContent = 'This run has no revealed seed on this site yet.'; res.className = 'vres bad'; }
164
+ });
165
+ document.getElementById('v-check').addEventListener('click', async function () {
166
+ var r = current();
167
+ if (!r) { res.textContent = 'Choose a run first.'; res.className = 'vres bad'; return; }
168
+ if (!seed.value.trim()) { res.textContent = 'Paste a seed first.'; res.className = 'vres bad'; return; }
169
+ if (!(window.crypto && crypto.subtle)) { res.textContent = 'This browser cannot compute SHA-256 here (it needs a secure context).'; res.className = 'vres bad'; return; }
170
+ var h = await sha256hex(seed.value);
171
+ if (h === r.commit) { res.textContent = 'Match. This seed hashes to the commitment published before the run: ' + h.slice(0, 16) + '...'; res.className = 'vres good'; }
172
+ else { res.textContent = 'No match. This seed hashes to ' + h.slice(0, 16) + '..., not ' + r.commit.slice(0, 16) + '...'; res.className = 'vres bad'; }
173
+ });
174
+ }
175
+ })();
176
+ """
@@ -0,0 +1,79 @@
1
+ """Check the PUBLISHED static site: read-only GETs, nothing is sent or changed.
2
+
3
+ python3 site_live_check.py https://guldo.org
4
+
5
+ It checks that every page answers over HTTPS, that the page links resolve, and that the download on the Install page is exactly the file whose SHA-256 the page shows
6
+ (the check that tells you a visitor really gets what the page says). Exit 0: all passed, 1: something failed, 2: the site could not be reached. For the dynamic
7
+ submission service use deploy_smoke.py instead; this is only for the static site.
8
+ """
9
+ import hashlib
10
+ import re
11
+ import sys
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+
16
+ PAGES = ["index.html", "install.html", "domains.html", "guide.html", "method.html", "results.html", "preregistrations.html", "compete.html", "certify.html", "claims.html", "limits.html"]
17
+
18
+
19
+ def get(url, binary=False):
20
+ req = urllib.request.Request(url, headers={"User-Agent": "guldo-site-check"})
21
+ with urllib.request.urlopen(req, timeout=30) as r:
22
+ data = r.read(64 * 1024 * 1024)
23
+ return r.status, (data if binary else data.decode("utf-8", "replace")), r.geturl()
24
+
25
+
26
+ def main(argv=None):
27
+ argv = sys.argv[1:] if argv is None else argv
28
+ if len(argv) != 1 or not argv[0].startswith(("http://", "https://")):
29
+ print("usage: site_live_check.py https://your.domain", file=sys.stderr)
30
+ return 2
31
+ base = argv[0].rstrip("/") + "/"
32
+ results = []
33
+
34
+ def check(name, ok, detail=""):
35
+ results.append(ok)
36
+ print(f" {'PASS' if ok else 'FAIL'} {name}{': ' + detail if detail else ''}")
37
+ try:
38
+ status, text, final = get(base)
39
+ except (urllib.error.URLError, OSError, ValueError) as e:
40
+ print(f"could not reach {base}: {e}", file=sys.stderr)
41
+ return 2
42
+ check("home page answers", status == 200, final)
43
+ check("served over HTTPS", final.startswith("https://"), "the address you gave redirects to " + final if not final.startswith("https://") else "")
44
+ bodies = {}
45
+ for page in PAGES:
46
+ try:
47
+ s, t, _ = get(urllib.parse.urljoin(base, page))
48
+ bodies[page] = t
49
+ check(f"{page}", s == 200 and "<h1" in t)
50
+ except (urllib.error.URLError, OSError) as e:
51
+ check(f"{page}", False, str(e)[:100])
52
+ missing = []
53
+ for page, t in bodies.items():
54
+ for href in re.findall(r'href="([^"#?]+)"', t):
55
+ if re.match(r"^(https?:|mailto:|data:)", href):
56
+ continue
57
+ try:
58
+ get(urllib.parse.urljoin(urllib.parse.urljoin(base, page), href))
59
+ except (urllib.error.URLError, OSError):
60
+ missing.append(f"{page} -> {href}")
61
+ check("every internal link resolves", not missing, "; ".join(sorted(set(missing))[:5]))
62
+ install = bodies.get("install.html", "")
63
+ m = re.search(r'href="(downloads/([A-Za-z0-9._-]+\.zip))"', install)
64
+ h = re.search(r"\b([0-9a-f]{64})\b", install)
65
+ if not (m and h):
66
+ check("the Install page shows a download and its SHA-256", False, "not found")
67
+ else:
68
+ try:
69
+ _, data, _ = get(urllib.parse.urljoin(base, m.group(1)), binary=True)
70
+ got = hashlib.sha256(data).hexdigest()
71
+ check("the download matches the hash on the page", got == h.group(1), f"{m.group(2)}: page says {h.group(1)[:16]}..., file is {got[:16]}...")
72
+ except (urllib.error.URLError, OSError) as e:
73
+ check("the download can be fetched", False, str(e)[:100])
74
+ print("ALL PASSED" if all(results) else "SOMETHING FAILED")
75
+ return 0 if all(results) else 1
76
+
77
+
78
+ if __name__ == "__main__":
79
+ sys.exit(main())