From 3193a674d2ef16414a61e7b9d00bbd991af71ec2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 16:35:19 -0700 Subject: [PATCH] Run the trail workers in a process pool so a worker that raises or dies fails the build, count the cores the process may use, and test both --- web/build.py | 45 +++++++++++++++++++++++------------ web/tests/builtsite.py | 2 +- web/tests/run.py | 5 +++- web/tests/test_build_store.py | 38 +++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 17 deletions(-) diff --git a/web/build.py b/web/build.py index e974741..a12864b 100644 --- a/web/build.py +++ b/web/build.py @@ -9,6 +9,7 @@ import sys sys.dont_write_bytecode = True import argparse +import concurrent.futures import hashlib import json import multiprocessing @@ -676,13 +677,20 @@ PARALLEL_FROM = 16 # fewer trails than this: not worth the workers _JOB = None +def usable_cores(): + """The cores this process may run on (os.process_cpu_count is new in Python 3.13).""" + try: + return len(os.sched_getaffinity(0)) or 1 + except AttributeError: + return os.cpu_count() or 1 + + def job_count(): """Worker processes: LONGHIKES_JOBS if set, else the cores this process may use (at most 8).""" env = os.environ.get("LONGHIKES_JOBS", "") if env.isdigit(): return max(1, int(env)) - cores = getattr(os, "process_cpu_count", os.cpu_count)() or 1 - return min(cores, 8) + return min(usable_cores(), 8) def fork_context(): @@ -725,15 +733,23 @@ def build_trails(recs, out_dir, code_mtime, args, only, stats): _JOB = (recs, out_dir, code_mtime, args.force, only) results = [None] * len(recs) order = sorted(range(len(recs)), key=lambda i: -tree_size(recs[i]["id"])) # biggest first + # A process pool, not multiprocessing.Pool: a worker that raises, or is killed, makes the + # build fail (BrokenProcessPool) where Pool would wait for it for ever. try: - with ctx.Pool(jobs) as pool: - for i, result, files, counts, warnings in pool.imap_unordered(_trail_job, order, chunksize=1): - recs[i]["derived"]["files"] = files - results[i] = result - for name, n in counts.items(): - setattr(stats, name, getattr(stats, name) + n) - for message in warnings: - warn(message) + with concurrent.futures.ProcessPoolExecutor(jobs, mp_context=ctx) as pool: + try: + futures = [pool.submit(_trail_job, i) for i in order] + for done in concurrent.futures.as_completed(futures): + i, result, files, counts, warnings = done.result() + recs[i]["derived"]["files"] = files + results[i] = result + for name, n in counts.items(): + setattr(stats, name, getattr(stats, name) + n) + for message in warnings: + warn(message) + except BaseException: + pool.shutdown(wait=False, cancel_futures=True) + raise finally: _JOB = None return results @@ -754,8 +770,8 @@ def start_archives(recs, out_dir, stats): build_archive(name, recs, out_dir, stats) return None _JOB = (recs, out_dir) - pool = ctx.Pool(min(len(ARCHIVES), job_count())) - return pool, [pool.apply_async(_archive_job, (name,)) for name in ARCHIVES] + pool = concurrent.futures.ProcessPoolExecutor(min(len(ARCHIVES), job_count()), mp_context=ctx) + return pool, [pool.submit(_archive_job, name) for name in ARCHIVES] def finish_archives(started, stats): @@ -765,11 +781,10 @@ def finish_archives(started, stats): pool, pending = started try: for result in pending: - for name, n in result.get().items(): + for name, n in result.result().items(): setattr(stats, name, getattr(stats, name) + n) finally: - pool.close() - pool.join() + pool.shutdown(wait=True, cancel_futures=True) _JOB = None diff --git a/web/tests/builtsite.py b/web/tests/builtsite.py index 9a2da45..ebedf04 100644 --- a/web/tests/builtsite.py +++ b/web/tests/builtsite.py @@ -134,7 +134,7 @@ def warm(workers=None): if "fork" not in multiprocessing.get_all_start_methods(): return os.makedirs(SCANS, exist_ok=True) - count = workers or min(getattr(os, "process_cpu_count", os.cpu_count)() or 1, 8) + count = workers or min(len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1), 8) with multiprocessing.get_context("fork").Pool(count) as pool: for _ in pool.imap_unordered(_scan_one, keys, chunksize=8): pass diff --git a/web/tests/run.py b/web/tests/run.py index f6fea4c..8b30a96 100644 --- a/web/tests/run.py +++ b/web/tests/run.py @@ -31,7 +31,10 @@ SLOW_FIRST = ("test_thumbs", "test_google_tag", "test_pages", "test_saved", "tes def cores(): - return getattr(os, "process_cpu_count", os.cpu_count)() or 1 + try: + return len(os.sched_getaffinity(0)) or 1 # the cores this process may use + except AttributeError: + return os.cpu_count() or 1 def modules_under(only): diff --git a/web/tests/test_build_store.py b/web/tests/test_build_store.py index 9c69982..0ee839e 100644 --- a/web/tests/test_build_store.py +++ b/web/tests/test_build_store.py @@ -11,6 +11,7 @@ import random import shutil import sys import tempfile +import time import unittest import zipfile from unittest import mock @@ -162,6 +163,43 @@ class BuildShortcutsTest(unittest.TestCase): self.build(again, cache, 1) # a new directory, filled from the store same_tree(self, first, again) + def test_the_worker_count_follows_the_cores_this_process_may_use_and_the_setting(self): + with mock.patch.dict(os.environ, {"LONGHIKES_JOBS": ""}): + with mock.patch.object(os, "sched_getaffinity", lambda pid: {0}): + self.assertEqual(build.job_count(), 1) + with mock.patch.object(os, "sched_getaffinity", lambda pid: set(range(32))): + self.assertEqual(build.job_count(), 8) + with mock.patch.dict(os.environ, {"LONGHIKES_JOBS": "1"}): + self.assertEqual(build.job_count(), 1) + + def test_a_worker_that_raises_fails_the_build_and_leaves_no_site(self): + out, cache = self.dirs("raises") + real = build.compute_trail + + def broken(rec, files, tdir, stats): + if rec["id"] == self.ids[3]: + raise RuntimeError("worker trouble") + return real(rec, files, tdir, stats) + + for jobs in (1, 4): + with self.subTest(jobs=jobs), mock.patch.object(build, "compute_trail", broken): + with self.assertRaisesRegex(RuntimeError, "worker trouble"): + self.build(out, cache + str(jobs), jobs) + self.assertFalse(os.path.exists(os.path.join(out, "index.html"))) + self.assertFalse(os.path.exists(os.path.join(out, "data", "trails.json"))) + + def test_a_worker_that_dies_fails_the_build_instead_of_hanging(self): + out, cache = self.dirs("dies") + + def dying(rec, files, tdir, stats): + os._exit(3) + + with mock.patch.object(build, "compute_trail", dying): + started = time.time() + with self.assertRaises(Exception): + self.build(out, cache, 4) + self.assertLess(time.time() - started, 120) + def test_a_changed_source_is_worked_out_again(self): out, cache = self.dirs("change") self.build(out, cache, 1)