diff --git a/src/tbhbdev/alpha/agent/driver.py b/src/tbhbdev/alpha/agent/driver.py index 8503052..267b712 100644 --- a/src/tbhbdev/alpha/agent/driver.py +++ b/src/tbhbdev/alpha/agent/driver.py @@ -172,6 +172,58 @@ def prepare(settings: Settings, args: argparse.Namespace) -> Run: return result +def past_time_limit(settings: Settings, run: Run) -> bool: + """Whether RUN started longer ago than the longest it may run.""" + limits = [run.request.timeout] + if settings.max_run_minutes is not None: + limits.append(settings.max_run_minutes * 60) + seconds = min((n for n in limits if n is not None), default=None) + if seconds is None: + return False + age = datetime.now(UTC) - datetime.fromisoformat(run.started) + return age.total_seconds() > seconds + + +def refuse_live_duplicate(settings: Settings, run: Run) -> None: + """Refuse a review of a commit that another run of the profile is reviewing. + + A recorded run counts as live until the host reports its exit status, so + an unreachable host or a run with no status also refuses. A run older than + its time limit no longer counts, because the host stops it by then. A + record with no time limit stays live until `agent kill` or `agent clean`. + + Raises: + Invalid: A recorded run has the same repo, commit and profile and no + exit status yet. + """ + for path in sorted(directory().glob("*.json")): + try: + other = load(settings, path.stem) + except Invalid, ValueError: + continue + same = ( + other.request.repo == run.request.repo + and other.request.commit == run.request.commit + and other.request.profile is run.request.profile + ) + if not same or past_time_limit(settings, other): + continue + try: + ended = ( + transport.read(settings, other.host, (other.name, other.owner)).rc + is not None + ) + except transport.TransportError: + ended = False + if not ended: + message = ( + f"{run.name}: run {other.name} already reviews " + f"{run.request.repo}@{run.request.commit} with the " + f"{run.request.profile.value} profile and hasn't ended" + ) + raise Invalid(message) + + def check_limits( settings: Settings, host: Host, @@ -305,6 +357,7 @@ def execute(settings: Settings, args: argparse.Namespace) -> int: rules.same_version(version.line(), host_version) if run.request.profile is Profile.REVIEW: run.request = replace(run.request, commit=rules.resolve_ref(ref, refs)) + refuse_live_duplicate(settings, run) save(run) try: transport.stream( diff --git a/tests/test_alpha_agent_driver.py b/tests/test_alpha_agent_driver.py index f7b237c..fa528eb 100644 --- a/tests/test_alpha_agent_driver.py +++ b/tests/test_alpha_agent_driver.py @@ -12,7 +12,7 @@ import tarfile from pathlib import PurePosixPath from types import SimpleNamespace -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, NoReturn import pytest from agent_driver_example import ( @@ -30,7 +30,7 @@ from tbhbdev.alpha.agent import driver, model, render, taint_store, transport from tbhbdev.alpha.agent.decisions import remote as remote_commands from tbhbdev.alpha.agent.decisions import repo, request, runfiles_names, taint -from tbhbdev.alpha.agent.model import Invalid, RunKind +from tbhbdev.alpha.agent.model import Invalid, Profile, RunKind if TYPE_CHECKING: from pathlib import Path @@ -353,6 +353,106 @@ def test_review_without_ref_starts_nothing( assert remote.records("ssh") == [] +OTHER_COMMIT = "fedcba9876543210fedcba9876543210fedcba98" + + +def recorded_review(remote: Remote) -> driver.Run: + """Launch `sample`, then return a copy named `second` to check against it.""" + assert launch(remote, "--profile", "review", "--ref", COMMIT) == 0 + second = driver.load(CONFIG, "sample") + second.name = "second" + return second + + +def test_a_second_live_review_of_the_same_commit_is_refused(remote: Remote) -> None: + second = recorded_review(remote) + with pytest.raises(Invalid) as info: + driver.refuse_live_duplicate(CONFIG, second) + assert str(info.value) == ( + f"second: run sample already reviews example-org/example-repo@{COMMIT} " + "with the review profile and hasn't ended" + ) + + +def test_a_review_may_start_when_the_first_has_ended(remote: Remote) -> None: + second = recorded_review(remote) + remote.file(".phase", "finished\n") + remote.file(".rc", "0\n") + driver.refuse_live_duplicate(CONFIG, second) + + +def test_an_unreachable_host_still_counts_the_first_run_as_live( + remote: Remote, monkeypatch: pytest.MonkeyPatch +) -> None: + second = recorded_review(remote) + + def unreachable(*_args: object, **_kwargs: object) -> transport.Reading: + message = "example-linux: transport failed" + raise transport.TransportError(message) + + monkeypatch.setattr(transport, "read", unreachable) + with pytest.raises(Invalid, match="hasn't ended"): + driver.refuse_live_duplicate(CONFIG, second) + + +def age_first_run(**request: object) -> None: + """Rewrite the recorded `sample` run as started in 2020.""" + path = driver.metadata_path("sample") + record = json.loads(path.read_text()) + record["started"] = "2020-01-01T00:00:00+00:00" + record.update(request) + path.write_text(json.dumps(record)) + + +def test_a_first_run_past_its_time_limit_no_longer_blocks( + remote: Remote, monkeypatch: pytest.MonkeyPatch +) -> None: + second = recorded_review(remote) + age_first_run(timeout=60) + + def no_read(*_args: object, **_kwargs: object) -> NoReturn: + pytest.fail("past the limit, no read") + + monkeypatch.setattr(transport, "read", no_read) + driver.refuse_live_duplicate(CONFIG, second) + + +def test_a_first_run_past_the_host_run_cap_no_longer_blocks( + remote: Remote, monkeypatch: pytest.MonkeyPatch +) -> None: + second = recorded_review(remote) + age_first_run() + config = dataclasses.replace(CONFIG, max_run_minutes=1) + + def no_read(*_args: object, **_kwargs: object) -> NoReturn: + pytest.fail("past the cap, no read") + + monkeypatch.setattr(transport, "read", no_read) + driver.refuse_live_duplicate(config, second) + + +def test_a_first_run_with_no_time_limit_stays_live(remote: Remote) -> None: + second = recorded_review(remote) + age_first_run() + config = dataclasses.replace(CONFIG, max_run_minutes=None) + with pytest.raises(Invalid, match="hasn't ended"): + driver.refuse_live_duplicate(config, second) + + +@pytest.mark.parametrize("change", ["commit", "profile"]) +def test_another_commit_or_profile_does_not_count_as_a_duplicate( + remote: Remote, change: str +) -> None: + second = recorded_review(remote) + (driver.directory() / "broken.json").write_text("{") + second.request = ( + dataclasses.replace(second.request, commit=OTHER_COMMIT) + if change == "commit" + else dataclasses.replace(second.request, profile=Profile.BUILD) + ) + driver.refuse_live_duplicate(CONFIG, second) + + @pytest.mark.parametrize("ref", ["topic", "refs/pull/2/head", COMMIT]) def test_review_ref(remote: Remote, ref: str) -> None: remote.configure(refs=f"{COMMIT}\t{ref}\n")