Convert every description of a plan read in one adf-codec container run, and take a heavy slot around the build of the codec's image
CI / tests (pull_request) Successful in 2m57s

This commit is contained in:
2026-11-14 20:11:11 +01:00
parent 9b145d488f
commit 9b1a45a993
7 changed files with 245 additions and 94 deletions
+91 -16
View File
@@ -2,14 +2,18 @@
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
"""
import contextlib
import dataclasses
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import typing
from failure import Failure
from machine_load.slots import HELD, slot_count, slot_folder, usable_cpus, waited_slot
SHIM = pathlib.Path(__file__).resolve().parent / "node_shim"
SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs")
@@ -31,6 +35,15 @@ class Ran:
Run = typing.Callable[[str, str], Ran | Failure]
# Runs a docker command line on a text, in at most the given seconds, or fails to run it.
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
# Holds one of the machine's heavy slots for a with block, or yields why none could be taken.
Slot = typing.Callable[[], typing.ContextManager[Failure | None]]
@dataclasses.dataclass(frozen=True)
class Refused:
"""adf-codec refused the document at index of those handed to adfs_to_markdown."""
index: int
failure: Failure
def image_tag(shim: pathlib.Path) -> str:
@@ -55,17 +68,54 @@ def docker(args: list[str], text: str, seconds: int, call: typing.Callable[...,
return Ran(done.returncode, done.stdout, done.stderr)
def ensure_image(shim: pathlib.Path, run_docker: Docker = docker) -> str | Failure:
"""The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag."""
@contextlib.contextmanager
def heavy_slot(env: typing.Mapping[str, str] = os.environ, slots: int | None = None) -> typing.Iterator[Failure | None]:
"""Holds one of the machine's heavy slots, which run-heavy shares, for the with block; under run-heavy the process already holds one, so it waits for none."""
if HELD in env:
yield None
return
folder = slot_folder(env, pathlib.Path.home())
count = slot_count(usable_cpus()) if slots is None else slots
try:
folder.mkdir(parents=True, exist_ok=True)
_, fd = waited_slot(folder, count, lambda: print(f"adf-codec: waiting for a heavy slot, of {count} on this machine, to build the shim's image", file=sys.stderr, flush=True))
except OSError as failure:
yield Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}")
return
try:
yield None
finally:
os.close(fd)
def ensure_image(shim: pathlib.Path, run_docker: Docker = docker, slot: Slot = heavy_slot) -> str | Failure:
"""The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag.
The build waits for a heavy slot, since `docker build` is heavy. Once the slot is held it looks again, as another process may have built the image meanwhile."""
tag = image_tag(shim)
found = image_found(tag, run_docker)
if found is not False:
return tag if found is True else found
with slot() as refused:
if refused is not None:
return refused
found = image_found(tag, run_docker)
if found is not False:
return tag if found is True else found
return build_image(shim, tag, run_docker)
def image_found(tag: str, run_docker: Docker) -> bool | Failure:
found = run_docker(["docker", "image", "inspect", tag], "", RUN_SECONDS)
if isinstance(found, Failure) or found.status == 0:
return found if isinstance(found, Failure) else tag
built = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(built, Failure):
return built
if built.status != 0:
return Failure(f"building the adf-codec shim's image failed with exit {built.status}: {built.err.strip()}")
return found if isinstance(found, Failure) else found.status == 0
def build_image(shim: pathlib.Path, tag: str, run_docker: Docker) -> str | Failure:
ran = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(ran, Failure):
return ran
if ran.status != 0:
return Failure(f"building the adf-codec shim's image failed with exit {ran.status}: {ran.err.strip()}")
return tag
@@ -76,8 +126,8 @@ def container_run(mode: str, text: str, run_docker: Docker = docker, shim: pathl
return run_docker(docker_args(image, mode), text, RUN_SECONDS)
def answer(mode: str, text: str, run: Run) -> str | Failure:
"""What the shim printed for text, or a Failure saying why it gave no answer."""
def answer(mode: str, text: str, run: Run) -> str | Refused | Failure:
"""What the shim printed for text, or why it gave no answer: a Refused where it named the refused document's index."""
ran = run(mode, text)
if isinstance(ran, Failure):
return ran
@@ -88,18 +138,22 @@ def answer(mode: str, text: str, run: Run) -> str | Failure:
return Failure(f"the adf-codec shim failed with exit {ran.status}: {ran.err.strip()}")
def refusal(out: str) -> Failure:
def refusal(out: str) -> Refused | Failure:
try:
error = json.loads(out)["error"]
refused = json.loads(out)
error = refused["error"]
where = f"line {error['position']['line']}" if "position" in error else ".".join(str(step) for step in error["path"]) or "the document"
return Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})")
except (ValueError, KeyError, TypeError):
failure = Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})")
return Refused(refused["index"], failure) if isinstance(refused.get("index"), int) else failure
except (ValueError, KeyError, TypeError, AttributeError):
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown."""
out = answer("to-adf", markdown, run)
if isinstance(out, Refused):
return out.failure
if isinstance(out, Failure):
return out
try:
@@ -109,6 +163,27 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing
return document
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start."""
if not documents:
return []
out = answer("to-markdown", json.dumps(documents), run)
if isinstance(out, Refused) and not 0 <= out.index < len(documents):
return Failure(f"the adf-codec shim refused document {out.index} of the {len(documents)} handed to it, counting from 0")
if isinstance(out, Refused | Failure):
return out
try:
texts = json.loads(out)
except ValueError:
texts = None
if not isinstance(texts, list) or len(texts) != len(documents) or not all(isinstance(text, str) for text in texts):
return Failure(f"the adf-codec shim printed output that is not a JSON array of {len(documents)} texts: {out.strip()}")
return texts
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document."""
return answer("to-markdown", json.dumps(document), run)
texts = adfs_to_markdown([document], run)
if isinstance(texts, Refused):
return texts.failure
return texts if isinstance(texts, Failure) else texts[0]