Answer principles round 2: 0 🔴, 1 🟡 (0 misread); remove ci.sh's container when a patch cut stops it, show task-bench's count defaults where they apply, and take ci.sh's bound from the forge's wait
CI / tests (pull_request) Successful in 4m47s
CI / tests (pull_request) Successful in 4m47s
This commit is contained in:
@@ -4,33 +4,43 @@ import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from deploy_release.patch import Ci, CiRan
|
||||
from failure import Failure
|
||||
from deploy_release.trace import Say
|
||||
from forge.pulls import WAIT_SECONDS
|
||||
|
||||
# As long as forge.pulls waits for a pull request's checks, which run the same ci.sh.
|
||||
CI_SECONDS = 30 * 60
|
||||
# How long a stopped ci.sh has to end on SIGINT, which a container's CLI passes on to its container, before it is killed.
|
||||
# As long as a pull request's checks get, since they run the same ci.sh.
|
||||
CI_SECONDS = WAIT_SECONDS
|
||||
# How long a stopped ci.sh has to end on SIGINT before it is killed.
|
||||
GRACE_SECONDS = 10
|
||||
# How long docker has to remove a stopped ci.sh's container.
|
||||
REMOVE_SECONDS = 60
|
||||
# Where ci.sh reads the name to give its test container.
|
||||
CONTAINER = "CI_CONTAINER"
|
||||
|
||||
# Removes the container of a name, running or not; a Failure where it may still run.
|
||||
Remove = typing.Callable[[str], Failure | None]
|
||||
|
||||
|
||||
def ci_runner(log: pathlib.Path, seconds: float, say: Say, grace: float = GRACE_SECONDS) -> Ci:
|
||||
"""Runs ci.sh in a worktree with its output in log, as it comes. A Failure where it can't start, where log can't be written, or where it still runs after seconds, which stops it and each process it started."""
|
||||
def ci_runner(log: pathlib.Path, seconds: float, say: Say, container: str, remove: Remove, grace: float = GRACE_SECONDS) -> Ci:
|
||||
"""Runs ci.sh in a worktree with its output in log, as it comes, and its test container named container. A Failure where it can't start, where log can't be written, or where it still runs after seconds, which stops it, each process it started and that container."""
|
||||
def run(worktree: pathlib.Path) -> CiRan | Failure:
|
||||
say(f"ci.sh's output goes to {log}; it is stopped where it still runs after {lasting(seconds)}")
|
||||
try:
|
||||
with log.open("w", encoding="utf-8") as output:
|
||||
# In a session of its own, ci.sh and each process it starts share one process group, which `stopped` ends whole.
|
||||
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
process = subprocess.Popen(["sh", "ci.sh"], cwd=worktree, stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, CONTAINER: container})
|
||||
try:
|
||||
code = process.wait(timeout=seconds)
|
||||
except subprocess.TimeoutExpired:
|
||||
stopped(process, grace)
|
||||
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped; {log} holds its output")
|
||||
left = stopped(process, grace, container, remove)
|
||||
running = f", but its container {container} may still run: {left.reason}" if left else ""
|
||||
return Failure(f"ci.sh still ran after {lasting(seconds)} and was stopped{running}; {log} holds its output")
|
||||
except BaseException:
|
||||
# The cut is ending, as on Ctrl-C, which reaches only this process's group.
|
||||
stopped(process, grace)
|
||||
stopped(process, grace, container, remove)
|
||||
raise
|
||||
return CiRan(code, log.read_text(encoding="utf-8", errors="replace"))
|
||||
except OSError as failure:
|
||||
@@ -38,8 +48,8 @@ def ci_runner(log: pathlib.Path, seconds: float, say: Say, grace: float = GRACE_
|
||||
return run
|
||||
|
||||
|
||||
def stopped(process: subprocess.Popen[bytes], grace: float) -> None:
|
||||
"""End process's whole group: SIGINT first, then SIGKILL once grace seconds have passed."""
|
||||
def stopped(process: subprocess.Popen[bytes], grace: float, container: str, remove: Remove) -> Failure | None:
|
||||
"""End process's whole group, SIGINT first, then SIGKILL once grace seconds have passed, and then its container; a Failure where the container may still run."""
|
||||
try:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
@@ -49,6 +59,19 @@ def stopped(process: subprocess.Popen[bytes], grace: float) -> None:
|
||||
with contextlib.suppress(ProcessLookupError):
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
# The daemon runs the container, outside the group, and no signal to ci.sh's docker CLI ends the tests in it. It is removed last, once nothing in the group can start it.
|
||||
left = remove(container)
|
||||
return left
|
||||
|
||||
|
||||
def removed_container(container: str, run: typing.Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> Failure | None:
|
||||
"""Removes container with docker, running or not; None too where no such container exists."""
|
||||
argv = ["docker", "rm", "--force", container]
|
||||
try:
|
||||
ran = run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=REMOVE_SECONDS)
|
||||
except (OSError, subprocess.TimeoutExpired) as failure:
|
||||
return Failure(f"{' '.join(argv)} failed: {failure}")
|
||||
return Failure(f"{' '.join(argv)} failed: {ran.stderr.strip()}") if ran.returncode else None
|
||||
|
||||
|
||||
def lasting(seconds: float) -> str:
|
||||
|
||||
@@ -70,7 +70,7 @@ import shlex
|
||||
import sys
|
||||
import time
|
||||
|
||||
from deploy_release.ci_script import ci_runner, CI_SECONDS
|
||||
from deploy_release.ci_script import ci_runner, CI_SECONDS, removed_container
|
||||
from deploy_release.cut import cut
|
||||
from deploy_release.patch import cut_patch
|
||||
from deploy_release.deploy import deploy
|
||||
@@ -104,7 +104,7 @@ def main(argv: list[str]) -> int:
|
||||
file = None if isinstance(begun, Failure) else begun
|
||||
say = trace.saying(file, now, sys.stderr)
|
||||
if commits is not None:
|
||||
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say))
|
||||
moved = cut_patch(clone, checkout, commits, time.sleep, say, ci_runner(folder / f"{name}-ci.log", CI_SECONDS, say, f"deploy-release-ci-{name}", removed_container))
|
||||
else:
|
||||
moved = cut(clone, checkout, time.sleep, say)
|
||||
if isinstance(moved, Failure):
|
||||
|
||||
@@ -734,6 +734,8 @@ class PatchCi(unittest.TestCase):
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.worktree)])
|
||||
self.log = self.worktree / "ci.log"
|
||||
self.said: list[str] = []
|
||||
self.removed: list[str] = []
|
||||
self.remove = lambda container: self.removed.append(container)
|
||||
|
||||
def test_passes_where_ci_sh_exits_zero(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
@@ -759,7 +761,7 @@ class PatchCi(unittest.TestCase):
|
||||
|
||||
def test_the_runner_writes_ci_shs_output_to_the_log_as_it_runs_and_gives_its_exit_code(self):
|
||||
(self.worktree / "ci.sh").write_text("echo out\necho err >&2\nexit 3\n")
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree)
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(ran, patch.CiRan(3, "out\nerr\n"))
|
||||
self.assertEqual(self.log.read_text(), "out\nerr\n")
|
||||
self.assertEqual(self.said, [f"ci.sh's output goes to {self.log}; it is stopped where it still runs after 30 seconds"])
|
||||
@@ -767,7 +769,7 @@ class PatchCi(unittest.TestCase):
|
||||
def test_the_runner_stops_a_ci_sh_that_hangs_with_what_it_started_and_says_so(self):
|
||||
(self.worktree / "ci.sh").write_text("echo started\nsleep 60 &\necho $! >child.pid\nwait\n")
|
||||
began = time.monotonic()
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, grace=0.2)(self.worktree)
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertLess(time.monotonic() - began, 20)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
||||
self.assertEqual(self.log.read_text(), "started\n")
|
||||
@@ -777,15 +779,49 @@ class PatchCi(unittest.TestCase):
|
||||
time.sleep(0.05)
|
||||
self.assertFalse(still_runs(child), "the process ci.sh started still runs")
|
||||
|
||||
def test_the_runner_names_ci_shs_container_and_removes_it_where_it_stops_ci_sh(self):
|
||||
(self.worktree / "ci.sh").write_text('echo "$CI_CONTAINER"\nsleep 60\n')
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", self.remove, grace=0.2)(self.worktree)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped; {self.log} holds its output"))
|
||||
self.assertEqual(self.log.read_text(), "ci-of-a-test\n")
|
||||
self.assertEqual(self.removed, ["ci-of-a-test"])
|
||||
|
||||
def test_the_runner_says_where_the_container_of_a_stopped_ci_sh_may_still_run(self):
|
||||
(self.worktree / "ci.sh").write_text("sleep 60\n")
|
||||
ran = ci_script.ci_runner(self.log, 0.5, self.said.append, "ci-of-a-test", lambda container: Failure("docker rm --force ci-of-a-test failed: no daemon"), grace=0.2)(self.worktree)
|
||||
self.assertEqual(ran, Failure(f"ci.sh still ran after 0.5 seconds and was stopped, but its container ci-of-a-test may still run: docker rm --force ci-of-a-test failed: no daemon; {self.log} holds its output"))
|
||||
|
||||
def test_the_runner_removes_no_container_where_ci_sh_ends_in_time(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertEqual(self.removed, [])
|
||||
|
||||
def test_removing_a_container_gives_a_failure_where_docker_fails_and_none_where_it_removes(self):
|
||||
asked: list[list[str]] = []
|
||||
def docker(code: int, stderr: str):
|
||||
return lambda argv, **options: asked.append(argv) or subprocess.CompletedProcess(argv, code, "", stderr)
|
||||
self.assertIsNone(ci_script.removed_container("ci-of-a-test", docker(0, "")))
|
||||
self.assertEqual(asked, [["docker", "rm", "--force", "ci-of-a-test"]])
|
||||
self.assertEqual(ci_script.removed_container("ci-of-a-test", docker(1, "Cannot connect to the Docker daemon\n")), Failure("docker rm --force ci-of-a-test failed: Cannot connect to the Docker daemon"))
|
||||
|
||||
def test_removing_a_container_gives_a_failure_where_docker_cannot_start(self):
|
||||
def no_docker(argv, **options):
|
||||
raise FileNotFoundError("docker")
|
||||
self.assertEqual(ci_script.removed_container("ci-of-a-test", no_docker), Failure("docker rm --force ci-of-a-test failed: docker"))
|
||||
|
||||
def test_ci_sh_names_its_container_only_where_it_is_given_a_name(self):
|
||||
script = (pathlib.Path(__file__).resolve().parents[2] / "ci.sh").read_text()
|
||||
self.assertIn('${CI_CONTAINER:+--name "$CI_CONTAINER"}', script)
|
||||
|
||||
def test_the_runner_gives_a_failure_where_ci_sh_cannot_start(self):
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append)(self.worktree / "gone")
|
||||
ran = ci_script.ci_runner(self.log, 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree / "gone")
|
||||
self.assertIsInstance(ran, Failure)
|
||||
self.assertIn("ci.sh could not run: ", ran.reason)
|
||||
self.assertIn(str(self.worktree / "gone"), ran.reason)
|
||||
|
||||
def test_the_runner_gives_a_failure_where_the_log_cannot_be_written(self):
|
||||
(self.worktree / "ci.sh").write_text("exit 0\n")
|
||||
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append)(self.worktree)
|
||||
ran = ci_script.ci_runner(self.worktree / "no-folder" / "ci.log", 30, self.said.append, "ci-of-a-test", self.remove)(self.worktree)
|
||||
self.assertIsInstance(ran, Failure)
|
||||
self.assertIn(str(self.worktree / "no-folder" / "ci.log"), ran.reason)
|
||||
|
||||
|
||||
+17
-12
@@ -322,22 +322,27 @@ def checked(given: dict[str, str], env: typing.Mapping[str, str]) -> dict[str, s
|
||||
for name in ("--image", "--test"):
|
||||
if not given.get(name):
|
||||
return Failure(f"{name} is missing")
|
||||
if given.setdefault(TASKS, "bugs") not in KINDS:
|
||||
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {given[TASKS]}")
|
||||
kind = KINDS[given[TASKS]]
|
||||
tasks = given.get(TASKS, "bugs")
|
||||
if tasks not in KINDS:
|
||||
return Failure(f"{TASKS} takes {', '.join(list(KINDS)[:-1])} or {list(KINDS)[-1]}, not {tasks}")
|
||||
kind = KINDS[tasks]
|
||||
for name, only in ONLY_FOR.items():
|
||||
if only is not kind and name in given:
|
||||
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {given[TASKS]}")
|
||||
return counts_failure(given, kind) or (given if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
|
||||
return Failure(f"{name} is for a bench of {only.noun}s, so it doesn't go with {TASKS} {tasks}")
|
||||
filled = {TASKS: tasks, **count_defaults(kind), **given}
|
||||
return counts_failure(filled) or (filled if env.get(TOKEN) else Failure(f"{TOKEN} holds no token"))
|
||||
|
||||
|
||||
def counts_failure(given: dict[str, str], kind: Kind) -> Failure | None:
|
||||
"""Fills in the default of each count a bench of kind takes; a Failure where one given is no whole number from 1."""
|
||||
for name, default in COUNTS.items():
|
||||
if ONLY_FOR.get(name, kind) is not kind:
|
||||
continue
|
||||
if not given.setdefault(name, default).isdecimal() or int(given[name]) < 1:
|
||||
return Failure(f"{name} takes a whole number from 1, not {given[name]}")
|
||||
def count_defaults(kind: Kind) -> dict[str, str]:
|
||||
"""The default of each count a bench of kind takes."""
|
||||
return {name: default for name, default in COUNTS.items() if ONLY_FOR.get(name, kind) is kind}
|
||||
|
||||
|
||||
def counts_failure(filled: dict[str, str]) -> Failure | None:
|
||||
"""A Failure where a count filled holds is no whole number from 1."""
|
||||
for name in COUNTS:
|
||||
if name in filled and (not filled[name].isdecimal() or int(filled[name]) < 1):
|
||||
return Failure(f"{name} takes a whole number from 1, not {filled[name]}")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -457,6 +457,12 @@ class MainTest(unittest.TestCase):
|
||||
self.assertEqual(self.run_main("--test", "go test ./...")[1].partition(";")[0], "--image is missing")
|
||||
self.assertEqual(self.run_main("--image", "golang:1.27.4")[1].partition(";")[0], "--test is missing")
|
||||
|
||||
def test_fills_in_each_default_of_the_kind_and_leaves_what_it_was_given_as_it_was(self):
|
||||
given = {"--image": "i", "--test": "t", "--runs": "7"}
|
||||
filled = main.checked(given, {"CLAUDE_CODE_OAUTH_TOKEN": "t"})
|
||||
self.assertEqual(given, {"--image": "i", "--test": "t", "--runs": "7"})
|
||||
self.assertEqual(filled, {"--image": "i", "--test": "t", "--tasks": "bugs", "--runs": "7", "--bugs": "5", "--seed": "1"})
|
||||
|
||||
def test_refuses_a_count_that_is_no_whole_number_from_1(self):
|
||||
for name, value in (("--bugs", "0"), ("--runs", "-1"), ("--seed", "x")):
|
||||
self.assertEqual(self.run_main("--image", "i", "--test", "t", name, value)[1].partition(";")[0], f"{name} takes a whole number from 1, not {value}")
|
||||
|
||||
@@ -9,7 +9,8 @@ cd "$(dirname "$0")"
|
||||
socket=/var/run/docker.sock
|
||||
# An untagged image, which docker image prune removes, since a cancelled run skips any cleanup.
|
||||
image=$(printf 'FROM docker:29.1.3-cli AS docker\nFROM python:3.14.8\nCOPY --from=docker /usr/local/bin/docker /usr/local/bin/docker\n' | docker build --quiet --memory 1g --memory-swap 1g -)
|
||||
git bundle create - HEAD | docker run --rm -i --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
|
||||
# deploy-release names the container in CI_CONTAINER, to remove it where it stops a run that hangs: stopping this script and its docker client leaves the container running. CI gives no name.
|
||||
git bundle create - HEAD | docker run --rm -i ${CI_CONTAINER:+--name "$CI_CONTAINER"} --memory 4g --memory-swap 4g --user "$(id -u):$(id -g)" --group-add "$(stat -c %g "$socket")" -v "$socket:$socket" -e HOME=/tmp "$image" sh -euc '
|
||||
cat >/tmp/head.bundle
|
||||
git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle /tmp/repo
|
||||
cd /tmp/repo
|
||||
|
||||
Reference in New Issue
Block a user