diff --git a/CHANGELOG.md b/CHANGELOG.md index bcbb8cc8..6ffc18a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- A read of a plan in a Jira epic converts every issue description in one `adf_codec` container run, however many issues the epic holds. The codec builds its image inside one of the machine's heavy slots that `run-heavy` shares, so sessions reading at once build it once. - A project config may name its plan as `jira:https:///browse/`: the plan is then read from the open child issues of that Jira Cloud epic, in backlog order, with the credentials in the config's `env-file`. Such a plan is only read so far: file, edit and finish its issues in Jira. - A new `adf_codec` package converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back with `@larvit/adf-codec` 0.3.1. It runs in a pinned Node container with a memory limit and no network, and returns adf-codec's error codes as a `Failure`. No tool calls it yet. - The new `todo-item list [--release ]` prints the plan's items in the plan's order, `todo-item edit ` sets an item's cells or detail, and `todo-item move --release ` moves it to another release; each change ranks the plan. Agents now read and change the plan's items only with `todo-item`, and the tools read the plan as it stands through one store, `bin/plan_store`, so a later backend can keep a plan outside `todo.md`. `todo-item list --release` with a bad version exits 2, and `finish --no-changelog` also drops an item no chunk built. diff --git a/README.md b/README.md index 301fc28d..615e4282 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a `bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. -- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. +- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does. @@ -186,7 +186,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `loop_claude` runs `chunk-preflight` as a process of its own. - `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it. - `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too. -- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. +- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read. - `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory. diff --git a/bin/adf_codec/convert.py b/bin/adf_codec/convert.py index 4bc4b482..02fb5afd 100644 --- a/bin/adf_codec/convert.py +++ b/bin/adf_codec/convert.py @@ -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: + """Why adf-codec refused one of the documents handed to adfs_to_markdown, and that document's index among them.""" + 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 doesn't wait.""" + 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, in {folder}, to build the shim's image; `fuser {folder}/slot-*` names the processes that hold them", 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. Once this process holds the slot, it inspects 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 a document at index {out.index}, past the {len(documents)} it was handed") + 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] diff --git a/bin/adf_codec/node_shim/shim.mjs b/bin/adf_codec/node_shim/shim.mjs index 6c889399..eeb0b601 100644 --- a/bin/adf_codec/node_shim/shim.mjs +++ b/bin/adf_codec/node_shim/shim.mjs @@ -1,7 +1,8 @@ // Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument: // to-adf stdin is markdown, stdout is the ADF document as JSON -// to-markdown stdin is an ADF document as JSON, stdout is markdown -// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}. +// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order +// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}, +// with "index", the refused document's place in the array, beside "error" in to-markdown. // Exit 1: the shim could not run, and stderr says why. import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec' @@ -13,19 +14,33 @@ async function readStdin() { return Buffer.concat(chunks).toString('utf8') } -function finish(result, render) { - if (result.ok) { - process.stdout.write(render(result.value)) - return 0 - } - process.stdout.write(JSON.stringify({ error: result.error })) +function refuse(refusal) { + process.stdout.write(JSON.stringify(refusal)) return REFUSED } +function toAdf(markdown) { + const result = portableMarkdownToAdf(markdown) + if (!result.ok) return refuse({ error: result.error }) + process.stdout.write(JSON.stringify(result.value)) + return 0 +} + +function toMarkdown(documents) { + const texts = [] + for (const [index, document] of documents.entries()) { + const result = adfToPortableMarkdown(document) + if (!result.ok) return refuse({ index, error: result.error }) + texts.push(result.value) + } + process.stdout.write(JSON.stringify(texts)) + return 0 +} + async function main(mode) { const input = await readStdin() - if (mode === 'to-adf') return finish(portableMarkdownToAdf(input), (doc) => JSON.stringify(doc)) - if (mode === 'to-markdown') return finish(adfToPortableMarkdown(JSON.parse(input)), (markdown) => markdown) + if (mode === 'to-adf') return toAdf(input) + if (mode === 'to-markdown') return toMarkdown(JSON.parse(input)) throw new Error(`mode must be to-adf or to-markdown, not ${mode}`) } diff --git a/bin/adf_codec/test_adf_codec.py b/bin/adf_codec/test_adf_codec.py index 470b288f..6029f0ff 100644 --- a/bin/adf_codec/test_adf_codec.py +++ b/bin/adf_codec/test_adf_codec.py @@ -1,4 +1,6 @@ +import contextlib import json +import os import shutil import subprocess @@ -6,6 +8,7 @@ import pytest from adf_codec import convert from failure import Failure +from machine_load import slots DOC = {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hi"}]}]} @@ -27,10 +30,40 @@ def test_markdown_to_adf_returns_the_document_the_shim_printed(): assert run.calls == [("to-adf", "Hi\n")] -def test_adf_to_markdown_sends_the_document_as_json_and_returns_the_text(): - run = fake(0, "Hi\n") +def test_adfs_to_markdown_sends_every_document_in_one_run_and_returns_the_texts_in_order(): + run = fake(0, json.dumps(["Hi\n", "Yo\n"])) + assert convert.adfs_to_markdown([DOC, DOC], run) == ["Hi\n", "Yo\n"] + assert run.calls == [("to-markdown", json.dumps([DOC, DOC]))] + + +def test_adfs_to_markdown_of_no_documents_runs_no_container(): + run = fake(1) + assert convert.adfs_to_markdown([], run) == [] + assert run.calls == [] + + +def test_a_refused_document_names_its_index(): + refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + refused = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal))) + assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)")) + + +def test_a_refusal_whose_index_is_past_the_documents_becomes_a_failure(): + refusal = {"index": 2, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + failure = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal))) + assert failure == Failure("the adf-codec shim refused a document at index 2, past the 2 it was handed") + + +@pytest.mark.parametrize("out", ["not json", json.dumps(["Hi\n"]), json.dumps({"0": "Hi\n"}), json.dumps(["Hi\n", 7])]) +def test_texts_that_do_not_match_the_documents_become_a_failure(out): + failure = convert.adfs_to_markdown([DOC, DOC], fake(0, out)) + assert failure == Failure(f"the adf-codec shim printed output that is not a JSON array of 2 texts: {out}") + + +def test_adf_to_markdown_returns_the_text_of_its_one_document(): + run = fake(0, json.dumps(["Hi\n"])) assert convert.adf_to_markdown(DOC, run) == "Hi\n" - assert run.calls == [("to-markdown", json.dumps(DOC))] + assert run.calls == [("to-markdown", json.dumps([DOC]))] def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message(): @@ -40,7 +73,7 @@ def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message(): def test_a_refusal_without_a_position_names_the_path(): - refusal = {"error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}} + refusal = {"index": 0, "error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}} failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal))) assert failure == Failure("adf-codec refused the input with unsupported-node-shape: bad node (at content.0)") @@ -87,7 +120,7 @@ def test_the_container_command_line_is_exactly_this(): def test_a_refusal_at_the_root_says_the_document(): - refusal = {"error": {"code": "not-an-adf-document", "message": "no type", "path": []}} + refusal = {"index": 0, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}} failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal))) assert failure == Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)") @@ -143,24 +176,83 @@ def test_an_image_that_exists_is_not_built(tmp_path): assert run_docker.lines == [(["docker", "image", "inspect", tag], "", convert.RUN_SECONDS)] -def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit(tmp_path): +class Slot: + """Stands in for a heavy slot: records the docker lines run while it is held, or yields the given Failure.""" + def __init__(self, run_docker, failure: Failure | None = None): + self.run_docker, self.failure, self.held_lines = run_docker, failure, None + + @contextlib.contextmanager + def __call__(self): + before = len(self.run_docker.lines) + yield self.failure + self.held_lines = self.run_docker.lines[before:] + + +def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit_inside_a_heavy_slot(tmp_path): + missing = convert.Ran(1, "", "") + run_docker = scripted(missing, missing, convert.Ran(0, "", "")) + slot = Slot(run_docker) + tag = convert.image_tag(shim_dir(tmp_path)) + assert convert.ensure_image(tmp_path, run_docker, slot) == tag + inspect = (["docker", "image", "inspect", tag], "", convert.RUN_SECONDS) + build = (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS) + assert run_docker.lines == [inspect, inspect, build] + assert slot.held_lines == [inspect, build] + + +def test_an_image_another_process_built_while_this_one_waited_for_a_slot_is_not_built_again(tmp_path): run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(0, "", "")) tag = convert.image_tag(shim_dir(tmp_path)) - assert convert.ensure_image(tmp_path, run_docker) == tag - assert run_docker.lines[1] == (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS) + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == tag + assert len(run_docker.lines) == 2 + + +def test_a_heavy_slot_that_cannot_be_taken_fails_before_the_build(tmp_path): + run_docker = scripted(convert.Ran(1, "", "")) + shim_dir(tmp_path) + down = Failure("cannot take a heavy slot in /x: Permission denied") + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker, down)) == down + assert len(run_docker.lines) == 1 def test_a_failed_build_becomes_a_failure_with_its_stderr(tmp_path): - run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n")) + run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n")) shim_dir(tmp_path) - assert convert.ensure_image(tmp_path, run_docker) == Failure("building the adf-codec shim's image failed with exit 5: no network") + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == Failure("building the adf-codec shim's image failed with exit 5: no network") -def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path): +DOWN, MISSING = Failure("docker is not installed"), convert.Ran(1, "", "") + + +@pytest.mark.parametrize("answers", [(DOWN,), (MISSING, DOWN), (MISSING, MISSING, DOWN)], ids=["first inspect", "second inspect", "build"]) +def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path, answers): shim_dir(tmp_path) - down = Failure("docker is not installed") - assert convert.ensure_image(tmp_path, scripted(down)) == down - assert convert.ensure_image(tmp_path, scripted(convert.Ran(1, "", ""), down)) == down + run_docker = scripted(*answers) + assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == DOWN + + +def test_a_heavy_slot_is_held_until_the_block_ends(tmp_path): + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held: + assert held is None + assert slots.taken_slot(tmp_path / "run-heavy", 1) is None + slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1) + os.close(fd) + + +def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path): + (tmp_path / "run-heavy").mkdir() + slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1) + try: + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path), slots.HELD: "0"}, 1) as held: + assert held is None + finally: + os.close(fd) + + +def test_a_heavy_slot_folder_that_cannot_be_made_yields_a_failure(tmp_path): + (tmp_path / "run-heavy").write_text("a file where the folder goes") + with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held: + assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'run-heavy'}: ") def test_container_run_runs_the_image_on_the_text(tmp_path): @@ -182,5 +274,8 @@ def test_round_trip_through_the_real_container(): assert isinstance(markdown, str) and markdown.startswith("# Title") and "**bold**" in markdown refused = convert.adf_to_markdown({"type": "nope"}) assert isinstance(refused, Failure) and "not-an-adf-document" in refused.reason + assert convert.adfs_to_markdown([doc, doc]) == [markdown, markdown] + second = convert.adfs_to_markdown([doc, {"type": "nope"}]) + assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason crashed = convert.answer("to-markdown", "not json", convert.container_run) assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ") diff --git a/bin/machine_load/slots.py b/bin/machine_load/slots.py index c8424608..74cbb255 100644 --- a/bin/machine_load/slots.py +++ b/bin/machine_load/slots.py @@ -8,6 +8,8 @@ import typing CPUS_PER_SLOT = 4 # Seconds between tries while every slot is held; a slot frees as its command exits. POLL_SECONDS = 1 +# Names the environment variable run-heavy sets for the command it runs. A process that finds it set already holds a slot, and takes no second one. +HELD = "RUN_HEAVY_SLOT" def usable_cpus() -> int | None: diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index 470dff78..81383554 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -4,13 +4,12 @@ An item is an open child issue. Its ID is the issue's number, so every child mus The store only reads so far: every write is a Failure.""" import base64 -import concurrent.futures import dataclasses import pathlib import re import typing -from adf_codec.convert import adf_to_markdown +from adf_codec.convert import adfs_to_markdown, Refused from plan_store.markdown_edits import bold_cell from project_config.settings import Epic from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE @@ -30,13 +29,11 @@ TIMEOUT = 30 PAGE = 100 # The pages one read asks for at most, so an answer that never names a last page ends the read. MAX_PAGES = 100 -# The adf-codec containers run at once, each converting one description: one heavy slot's CPUs. -CONVERSIONS = 4 READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira" # Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] -ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure] +ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure] def http_json(method: str, url: str, authorization: str, body: object) -> object: @@ -75,7 +72,7 @@ class JiraPlan: epic: Epic env_file: pathlib.Path http: Http = http_json - to_markdown: ToMarkdown = adf_to_markdown + to_markdown: ToMarkdown = adfs_to_markdown @property def label(self) -> str: @@ -164,8 +161,8 @@ def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | items = [item(issue, project, ids) for issue in issues] if failed := next((found for found in items if isinstance(found, Failure)), None): return failed - # The descriptions convert last, since each costs a container run, which a read that fails doesn't need. - texts = details(issues, to_markdown) + # The descriptions convert last, since that costs a container run, which a read that fails doesn't need. + texts = details(issues, epic, to_markdown) if isinstance(texts, Failure): return texts return Plan([dataclasses.replace(found, detail=texts.get(found.id, "")) for found in items if isinstance(found, Item)]) @@ -175,19 +172,15 @@ def number(key: str) -> int: return int(key.rpartition("-")[2]) -def details(issues: list[Issue], to_markdown: ToMarkdown) -> dict[int, str] | Failure: - """Each described issue's description as markdown, under the issue's number. The first converts alone, since that run builds the codec's image where the machine has none; the rest convert CONVERSIONS at a time.""" +def details(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> dict[int, str] | Failure: + """Each described issue's description as markdown, under the issue's number, all converted at once.""" described = [(issue, issue.description) for issue in issues if issue.description is not None] - texts: list[str | Failure] = [to_markdown(description) for _, description in described[:1]] - if not any(isinstance(text, Failure) for text in texts): - with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: - texts += pool.map(to_markdown, [description for _, description in described[1:]]) - found = {} - for (issue, _), text in zip(described, texts): - if isinstance(text, Failure): - return Failure(f"{issue.key}'s description: {text.reason}") - found[issue.number] = text.strip() - return found + texts = to_markdown([description for _, description in described]) + if isinstance(texts, Refused): + return Failure(f"{described[texts.index][0].key}'s description: {texts.failure.reason}") + if isinstance(texts, Failure): + return Failure(f"cannot convert the descriptions of {epic.key}'s children to markdown: {texts.reason}") + return {issue.number: text.strip() for (issue, _), text in zip(described, texts)} def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index f05e009a..7d233c33 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -2,8 +2,6 @@ import base64 import pathlib import sys import tempfile -import threading -import time import unittest import unittest.mock @@ -13,6 +11,7 @@ from project_config.settings import Epic from failure import Failure from plan_store import jira_epic from plan_store.stores import Plan +from adf_codec.convert import Refused from release_plan.release import release_of EPIC = Epic("https://acme.atlassian.net", "ABC-12") @@ -48,7 +47,7 @@ class JiraPlan(unittest.TestCase): self.calls: list[tuple[str, str, str, object]] = [] self.epic: object = {"key": "ABC-12"} self.epic_calls: list[tuple[str, str, str, object]] = [] - self.converted: list[object] = [] + self.converted: list[list[dict[str, object]]] = [] def http(self, method: str, url: str, authorization: str, body: object) -> object: """Stands in for Jira: answers self.epic to the request for the epic, and the next of self.pages to each search.""" @@ -58,9 +57,9 @@ class JiraPlan(unittest.TestCase): self.calls.append((method, url, authorization, body)) return self.pages[len(self.calls) - 1] - def to_markdown(self, document: dict[str, object]) -> str | Failure: - self.converted.append(document) - return text_of(document) + def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure: + self.converted.append(documents) + return [text_of(document) for document in documents] def store(self) -> jira_epic.JiraPlan: return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown) @@ -167,22 +166,6 @@ class JiraPlan(unittest.TestCase): with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2): self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages")) - def test_converts_at_most_four_descriptions_at_once(self): - lock, running, most = threading.Lock(), [0], [0] - - def slow(document: dict[str, object]) -> str: - with lock: - running[0] += 1 - most[0] = max(most[0], running[0]) - time.sleep(0.02) - with lock: - running[0] -= 1 - return "text" - - self.pages = [{"issues": [issue(f"ABC-{number}", description=adf("Why.")) for number in range(1, 41)]}] - self.assertIsInstance(jira_epic.JiraPlan(EPIC, self.env, self.http, slow).read(), Plan) - self.assertLessEqual(most[0], 4) - def test_an_issue_in_another_shape_fails_the_read_naming_it(self): good = issue("ABC-1") for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator] @@ -191,22 +174,20 @@ class JiraPlan(unittest.TestCase): self.assertIsInstance(failure, Failure) self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr] - def test_converts_each_description_once_and_none_for_an_issue_without_one(self): + def test_converts_every_description_in_one_run_and_none_for_an_issue_without_one(self): found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four."))) self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."]) - self.assertEqual(len(self.converted), 3) - - def test_a_first_description_the_codec_refuses_converts_no_other(self): - calls: list[object] = [] - store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: calls.append(document) or Failure("no docker")) # type: ignore[func-returns-value] - self.pages = [{"issues": [issue("ABC-1", description=adf("One.")), issue("ABC-2", description=adf("Two."))]}] - self.assertEqual(store.read(), Failure("ABC-1's description: no docker")) - self.assertEqual(len(calls), 1) + self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]]) def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self): - store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused")) + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused"))) + self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}] + self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused")) + + def test_a_codec_that_cannot_run_fails_the_read(self): + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed")) self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}] - self.assertEqual(store.read(), Failure("ABC-34's description: adf-codec refused")) + self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed")) def test_an_env_file_without_the_credentials_fails_before_any_request(self): self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n") diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 4f4ad6b4..27e7a965 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -36,11 +36,10 @@ import typing from run_heavy.capped_docker import CANNOT_RUN, NOT_FOUND, PATH_ENTRY, SHARE_VARIABLE, without_path_entry from failure import Failure +from machine_load.slots import HELD, slot_count, slot_folder, waited_slot from machine_load.memory import Memory -from machine_load.slots import slot_count, slot_folder, waited_slot OWN_FAILURE = 125 -HELD = "RUN_HEAVY_SLOT" USAGE = "usage: run-heavy [...]" diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 1cf0f40f..c3e1286e 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2050,3 +2050,20 @@ Read most (opens and searches): - `bin/run-tests` 1 - `bin/run_tests/main.py` 1 - `ci.sh` 1 + +## Reading cost, chunk 2c4de5662b08, finished 2026-11-14T19:06:19Z + +84663 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/plan_store/stores.py` 5 +- `todo.md` 3 +- `bin/project_config/templates.py` 2 +- `CLAUDE.md` 1 +- `README.md` 1 +- `bin/larv_review/plan.py` 1 +- `bin/loop_claude/cycle/chunk_items.py` 1 +- `bin/plan_store/contract.py` 1 +- `bin/release_plan/todo_table.py` 1 +- `bin/todo_item/main.py` 1 diff --git a/todo.md b/todo.md index 20c64850..624d3d43 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 379 | 0.11.0 | | | **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.** | 3 | 2 | 3 | 6 | 4 | code health by 2, 1.5 by 2 | 3.2 | | 378 | 0.11.0 | | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 | | 353 | 0.11.0 | | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | | 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | @@ -20,7 +19,7 @@ | 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 | | 377 | 0.11.0 | | | **Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | | 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 | -| 352 | 0.11.0 | 379 | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 | +| 352 | 0.11.0 | | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 | | 355 | 0.11.0 | | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 | | 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 | | 372 | 0.11.0 | | | **Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 | @@ -86,31 +85,6 @@ ## Details -### 379. 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. - -Two changes in `bin/adf_codec/`, in one item since both change the codec and its tests. Item 352 waits for this one. It waits for item 351, which adds `bin/plan_store/jira_epic.py`. - -**One container per read.** Today a read of a Jira epic with N described issues starts N containers, four at a time: `details` in `bin/plan_store/jira_epic.py` calls `adf_to_markdown` in `bin/adf_codec/convert.py` once per description. `todo-item show ` converts all N to print one, and `larv-review needs-scoring-run` converts all N twice, since it reads a plan outside the checkout twice. To keep that bearable, `details` carries a thread pool, the constant `CONVERSIONS` and a rule that the first description converts alone. Two later items get harder while this stands: - -- Item 352 scores each issue a teammate filed, and its worker reads an issue's scope with `todo-item show `. Scoring M unscored issues of an epic with N described ones is M × N container runs: 20 unscored issues in an epic of 40 is 800 runs. Item 352 would otherwise have to add a way to read one item past `PlanStore.read()`, which changes the protocol, `FilePlan`, the fakes, the contract and four readers. -- Item 375 runs several chunks at once. `CONVERSIONS = 4` is commented as one heavy slot's CPUs, but no slot is taken, so K chunks that read the plan at once run 4 × K containers. - -Items 353 and 355 add a conversion to each read of the goals and of each record in Confluence, each with a container start of its own. - -The smallest change leaves `Plan` as it is, a plain value holding every detail: - -- `bin/adf_codec/node_shim/shim.mjs` gets a mode that takes a JSON array of ADF documents on stdin and prints a JSON array of markdown texts. A refused document answers with its index, so the Failure still names the issue. -- `convert.py` gets one function beside `adf_to_markdown` that takes the documents and returns the texts, or a Failure naming the index. -- `JiraPlan.to_markdown` takes that function, and `details` becomes one call. The thread pool, `CONVERSIONS`, the `concurrent.futures` import and the first-converts-alone rule go. - -A read then costs one container whatever the epic's size: `show` one, `needs-scoring-run` two, and item 352's scoring M runs. The price: one container of 256m holds every description of the epic at once, and one 60-second limit covers them all. A hundred descriptions are a few megabytes of JSON, so neither should bind; if one does, raise that one constant. - -**A heavy slot around the image build.** Today `ensure_image` in `convert.py` runs `docker build` from Python, so rule-hook's `run-heavy` rule, which sees only a session's Bash commands, doesn't make it wait. The decision "machine load: a heavy command waits for one of the machine's heavy slots" names `docker build` as heavy. `chunk-preflight` reaches the build through `JiraPlan.read()`, in process and outside its per-tool timeout. One read builds once, but two processes each inspect, find no image, and build. Item 375 starts several chunks of one project at once: on a new machine, or after a release that bumps the shim or adf-codec, each chunk's `chunk-preflight` builds, each with 1 GiB and up to 300 seconds, all outside the slots. - -In `ensure_image`, where the inspect finds no image, take a slot with `machine_load.slots.waited_slot`, inspect again, build only if the image is still missing, and free the slot. A second process then waits and finds the first one's image, and the codec stays the one place that knows it builds. The one `docker run` a read keeps is short and carries its limits, so it takes no slot. - -Scores: L 3, since the change spans the Node shim, its image, `convert.py` and `jira_epic.py`. I 3, since every reader of a plan in Jira runs it. R is above 5, so this item ships alone. - ### 378. Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`. lilleman's call, 2026-11-14: split from item 351. Item IDs stay `int`: the Jira store holds the project key and an issue's number is the item's ID. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` already give the ticket-style names `CLAUDE.md`'s ticket rules ask for. Make a project with a Jira plan get them without spelling its key twice, or document the two templates where the plan setting is documented, whichever is simpler, and check `chunk-preflight` names the worktree the same way.