Files
computer-playbook/roles/web-app-docs/files/python/infinito_docs/build_queue.py
T
kevinveenbirkenbachandClaude Opus 5 ff89a02067 fix(web-app-docs): take the builds nobody waits for off the awaited path
On a cold container the docs Playwright suite triggers four serial Sphinx builds and waits for the last one. test-languages.js polls /deployed/de/ for 200 and got 202 for 55.6 minutes in job 110003713825 of run 36745666606, after which the suite budget expired and five further specs never ran. The suite has never passed on a first attempt; it used to go green only on the harness retry, which 7127c6b96b removed for budget timeouts, so a structural overrun became a red job.

Measured cost per build, from run 36558500327 where the whole queue drained on a kept stack: container up 12:15:52, the spec green at 13:21:41 answering on its first poll, next container start only at 13:30:45. Four builds in 65 minutes 49 seconds, so at most 16.5 minutes each - not the sixty to ninety minutes 40688e4ded estimated.

Three of the four builds were none of the test's business. fetch() queued latest in the foreground although nothing waits on it at startup, and _refresh_stale_sites did the same for every servable version; both now use the background lane, which is what its own docstring describes. test-front-page.js reached GET /latest/, and reaching an unbuilt version queues its build - it now asserts the redirect from the Location header without following it, and checks the same page shape against /deployed/, which is built anyway. The release tag that test-on-demand-build.js clicks stays, and now runs behind the awaited work instead of in front of it.

The translation could only be queued after its base finished, because the 202 branch returns before _translation is reachable, so it always sorted behind whatever the sibling specs had queued meanwhile. The 202 branch now carries the language segment along, admitted by translatable(), which answers from the snapshot catalog on disk before any build; build_language still re-checks the written index.

Moving a version into the background lane exposed that status() read only the foreground one, so a waiting version would have been reported as missing rather than queued to the versions overview and to /api/versions. is_queued() now covers both lanes, mirroring _dequeue, which always removed from both. Two of the five unit failures this change first produced disappeared on that fix alone, which is what shows they pinned real behaviour; the three that pinned the lane itself were rewritten to assert the behaviour instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-01 11:32:08 +02:00

125 lines
4.1 KiB
Python

"""The build queue, the cross-replica builder lock and the daemon loop.
``Queue`` is a mixin of :class:`infinito_docs.library.Library`. A marker is a
file named ``version`` or ``version:code``; the background lane holds the
builds nobody is waiting on - the daemon's own prefetch and every language no
visitor has asked for.
"""
from __future__ import annotations
import fcntl
import subprocess
import sys
import time
from infinito_docs.builder import DEPLOYED, QUEUE_SEPARATOR
POLL_SECONDS = 2
BACKGROUND_LANE = "background"
class Queue:
def request(self, version, code=None, background=False):
"""Queue a build of ``version``, or of one of its translated sites.
Args:
version: ``latest`` or a release tag.
code: ISO 639-1 code to build instead of the version's own site.
background: queue behind everything a visitor is waiting on.
"""
head, _ = self.refs()
if not head and version != DEPLOYED:
return
if code is None:
if self._current(version, head):
return
marker = version
elif not self.translatable(version, code) or self._translation_current(
version, code, head
):
return
else:
marker = f"{version}{QUEUE_SEPARATOR}{code}"
lane = self.queue / BACKGROUND_LANE if background else self.queue
lane.mkdir(parents=True, exist_ok=True)
if background and (self.queue / marker).exists():
return
queued = lane / marker
if queued.exists():
return
queued.touch()
def is_queued(self, marker):
"""Whether ``marker`` waits in either lane.
Args:
marker: queue file name, ``version`` or ``version:code``.
"""
return (self.queue / marker).exists() or (
self.queue / BACKGROUND_LANE / marker
).exists()
def _dequeue(self, marker):
"""Drop ``marker`` from both lanes.
Args:
marker: queue file name, ``version`` or ``version:code``.
"""
(self.queue / marker).unlink(missing_ok=True)
(self.queue / BACKGROUND_LANE / marker).unlink(missing_ok=True)
def next_queued(self):
"""Return the oldest marker a visitor is waiting on, else the oldest background one."""
for lane in (self.queue, self.queue / BACKGROUND_LANE):
if not lane.is_dir():
continue
waiting = sorted(
(marker for marker in lane.iterdir() if marker.is_file()),
key=lambda marker: marker.stat().st_mtime,
)
if waiting:
return waiting[0].name
return None
def acquire_builder(self):
"""Try to become the builder of all replicas without blocking.
Returns:
``True`` while this process holds the builder lock.
"""
if self._lock_handle is not None:
return True
self.lock_file.parent.mkdir(parents=True, exist_ok=True)
handle = self.lock_file.open("a+")
try:
fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
handle.close()
return False
self._lock_handle = handle
return True
def run_builder(self, interval):
while not self.acquire_builder():
time.sleep(POLL_SECONDS)
if self.snapshot.is_dir():
self.request(DEPLOYED)
next_fetch = 0.0
while True:
if time.monotonic() >= next_fetch:
try:
self.fetch()
except (OSError, subprocess.CalledProcessError) as exc:
print(f"fetch of {self.repository} failed: {exc}", file=sys.stderr)
next_fetch = time.monotonic() + interval
marker = self.next_queued()
if marker is None:
time.sleep(POLL_SECONDS)
continue
version, separator, code = marker.partition(QUEUE_SEPARATOR)
if separator:
self.build_language(version, code)
else:
self.build(version)