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

This commit is contained in:
swaits committed 2026-11-20 16:35:19 -07:00
1 parent 5d86a42ad1
commit 3193a674d2
4 files changed
+73 -17

No files matched your search

+30 -15
View File
@@ -9,6 +9,7 @@ import sys
sys.dont_write_bytecode = True sys.dont_write_bytecode = True
import argparse import argparse
import concurrent.futures
import hashlib import hashlib
import json import json
import multiprocessing import multiprocessing
@@ -676,13 +677,20 @@ PARALLEL_FROM = 16 # fewer trails than this: not worth the workers
_JOB = None _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(): def job_count():
"""Worker processes: LONGHIKES_JOBS if set, else the cores this process may use (at most 8).""" """Worker processes: LONGHIKES_JOBS if set, else the cores this process may use (at most 8)."""
env = os.environ.get("LONGHIKES_JOBS", "") env = os.environ.get("LONGHIKES_JOBS", "")
if env.isdigit(): if env.isdigit():
return max(1, int(env)) return max(1, int(env))
cores = getattr(os, "process_cpu_count", os.cpu_count)() or 1 return min(usable_cores(), 8)
return min(cores, 8)
def fork_context(): 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) _JOB = (recs, out_dir, code_mtime, args.force, only)
results = [None] * len(recs) results = [None] * len(recs)
order = sorted(range(len(recs)), key=lambda i: -tree_size(recs[i]["id"])) # biggest first 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: try:
with ctx.Pool(jobs) as pool: with concurrent.futures.ProcessPoolExecutor(jobs, mp_context=ctx) as pool:
for i, result, files, counts, warnings in pool.imap_unordered(_trail_job, order, chunksize=1): try:
recs[i]["derived"]["files"] = files futures = [pool.submit(_trail_job, i) for i in order]
results[i] = result for done in concurrent.futures.as_completed(futures):
for name, n in counts.items(): i, result, files, counts, warnings = done.result()
setattr(stats, name, getattr(stats, name) + n) recs[i]["derived"]["files"] = files
for message in warnings: results[i] = result
warn(message) 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: finally:
_JOB = None _JOB = None
return results return results
@@ -754,8 +770,8 @@ def start_archives(recs, out_dir, stats):
build_archive(name, recs, out_dir, stats) build_archive(name, recs, out_dir, stats)
return None return None
_JOB = (recs, out_dir) _JOB = (recs, out_dir)
pool = ctx.Pool(min(len(ARCHIVES), job_count())) pool = concurrent.futures.ProcessPoolExecutor(min(len(ARCHIVES), job_count()), mp_context=ctx)
return pool, [pool.apply_async(_archive_job, (name,)) for name in ARCHIVES] return pool, [pool.submit(_archive_job, name) for name in ARCHIVES]
def finish_archives(started, stats): def finish_archives(started, stats):
@@ -765,11 +781,10 @@ def finish_archives(started, stats):
pool, pending = started pool, pending = started
try: try:
for result in pending: 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) setattr(stats, name, getattr(stats, name) + n)
finally: finally:
pool.close() pool.shutdown(wait=True, cancel_futures=True)
pool.join()
_JOB = None _JOB = None
+1 -1
View File
@@ -134,7 +134,7 @@ def warm(workers=None):
if "fork" not in multiprocessing.get_all_start_methods(): if "fork" not in multiprocessing.get_all_start_methods():
return return
os.makedirs(SCANS, exist_ok=True) 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: with multiprocessing.get_context("fork").Pool(count) as pool:
for _ in pool.imap_unordered(_scan_one, keys, chunksize=8): for _ in pool.imap_unordered(_scan_one, keys, chunksize=8):
pass pass
+4 -1
View File
@@ -31,7 +31,10 @@ SLOW_FIRST = ("test_thumbs", "test_google_tag", "test_pages", "test_saved", "tes
def cores(): 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): def modules_under(only):
+38
View File
@@ -11,6 +11,7 @@ import random
import shutil import shutil
import sys import sys
import tempfile import tempfile
import time
import unittest import unittest
import zipfile import zipfile
from unittest import mock from unittest import mock
@@ -162,6 +163,43 @@ class BuildShortcutsTest(unittest.TestCase):
self.build(again, cache, 1) # a new directory, filled from the store self.build(again, cache, 1) # a new directory, filled from the store
same_tree(self, first, again) 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): def test_a_changed_source_is_worked_out_again(self):
out, cache = self.dirs("change") out, cache = self.dirs("change")
self.build(out, cache, 1) self.build(out, cache, 1)