Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/tbhbdev/alpha/agent/admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,26 @@ def _active(directory: int, profile: Profile) -> set[str]:


@contextmanager
def reserve(root: Path, host: Host, profile: Profile) -> Generator[None]:
"""Check both slot counts and claim capacity under one shared lock."""
def reserve(
root: Path, host: Host, profile: Profile, limit: int | None
) -> Generator[None]:
"""Check both slot counts and claim capacity under one shared lock.

LIMIT is the launcher's ``max_concurrent_runs`` for the host. The run
host's own account config can lack the host, so its default must never
decide the cap.

Raises:
Invalid: LIMIT is None, or no slot is free.
"""
if limit is None:
message = f"{host.name}: the request carries no max_concurrent_runs"
raise Invalid(message)
with ExitStack() as slot, _directory(root) as directory:
with _slot(directory, "admission.lock", create=True) as guard:
fcntl.flock(guard, fcntl.LOCK_EX)
builds = _active(directory, Profile.BUILD)
reviews = _active(directory, Profile.REVIEW)
limit = host.max_concurrent_runs
if len(builds) + len(reviews) >= limit:
message = (
f"{host.name}: no agent slot available "
Expand Down
9 changes: 7 additions & 2 deletions src/tbhbdev/alpha/agent/decisions/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@
"authorized_by",
"startup_deadline_seconds",
"fetch_refs",
"max_concurrent_runs",
}
)

# Requests saved before --fetch-ref lack this key and still load.
_REQUIRED_FIELDS = _FIELDS - {"fetch_refs"}
_REQUIRED_FIELDS = _FIELDS - {"fetch_refs", "max_concurrent_runs"}


def _fail(field: str, why: str) -> NoReturn:
Expand Down Expand Up @@ -159,6 +160,8 @@ def validate(
)
if request.timeout is not None and request.timeout <= 0:
_fail("timeout", "must be a positive number of seconds")
if request.max_concurrent_runs is not None and request.max_concurrent_runs < 0:
_fail("max_concurrent_runs", "must not be negative")
if request.startup_deadline_seconds <= 0:
_fail("startup_deadline_seconds", "must be a positive number of seconds")
_check_commit(request)
Expand Down Expand Up @@ -189,6 +192,7 @@ def to_dict(request: RunRequest) -> dict[str, object]:
"authorized_by": request.authorized_by,
"startup_deadline_seconds": request.startup_deadline_seconds,
"fetch_refs": list(request.fetch_refs),
"max_concurrent_runs": request.max_concurrent_runs,
}


Expand All @@ -211,7 +215,7 @@ def _number(data: dict[str, object], key: str) -> int:


def _maybe_number(data: dict[str, object], key: str) -> int | None:
return None if data[key] is None else _number(data, key)
return None if data.get(key) is None else _number(data, key)


def _flag(data: dict[str, object], key: str) -> bool:
Expand Down Expand Up @@ -288,6 +292,7 @@ def parse(data: dict[str, object], *, host_allows_unsandboxed: bool) -> RunReque
authorized_by=_maybe_text(data, "authorized_by"),
startup_deadline_seconds=_number(data, "startup_deadline_seconds"),
fetch_refs=_fetch_refs(data.get("fetch_refs", [])),
max_concurrent_runs=_maybe_number(data, "max_concurrent_runs"),
)
validate(request, host_allows_unsandboxed=host_allows_unsandboxed)
return request
1 change: 1 addition & 0 deletions src/tbhbdev/alpha/agent/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ def prepare(settings: Settings, args: argparse.Namespace) -> Run:
authorized_by=args.unsandboxed,
startup_deadline_seconds=settings.launch_wait_seconds,
fetch_refs=tuple(args.fetch_ref),
max_concurrent_runs=host.max_concurrent_runs,
)
run = rules.check(
run, settings, host, ref=args.ref, exists=metadata_path(args.name).exists()
Expand Down
1 change: 1 addition & 0 deletions src/tbhbdev/alpha/agent/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,4 @@ class RunRequest:
startup_deadline_seconds: int
tainted_host: bool
fetch_refs: tuple[str, ...] = ()
max_concurrent_runs: int | None = None
7 changes: 6 additions & 1 deletion src/tbhbdev/alpha/agent/run_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,12 @@ def execute(
with host_tools.configured(run.settings, run.host.os), ExitStack() as stack:
if not preflight_only:
stack.enter_context(
admission.reserve(admission.ROOT, run.host, run.request.profile)
admission.reserve(
admission.ROOT,
run.host,
run.request.profile,
run.request.max_concurrent_runs,
)
)
return _execute(run, text, stack, push_token, preflight_only=preflight_only)

Expand Down
2 changes: 1 addition & 1 deletion tests/agent_host_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def unusual_git_metadata(tmp_path: Path, entry: str, kind: str) -> Path:

def run_request(**changes: object) -> model.RunRequest:
return request.parse(
BUILD | {"repo": "tbhb-dev/example-repo"} | changes,
BUILD | {"repo": "tbhb-dev/example-repo", "max_concurrent_runs": 3} | changes,
host_allows_unsandboxed=True,
)

Expand Down
58 changes: 43 additions & 15 deletions tests/test_alpha_agent_admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,37 @@ def test_builds_leave_one_slot_for_reviews(tmp_path: Path) -> None:
root = tmp_path / "admission"
with ExitStack() as slots:
for _ in range(2):
slots.enter_context(admission.reserve(root, host, Profile.BUILD))
slots.enter_context(
admission.reserve(root, host, Profile.BUILD, host.max_concurrent_runs)
)
with (
pytest.raises(Invalid, match="reserved for reviews"),
admission.reserve(root, host, Profile.BUILD),
admission.reserve(root, host, Profile.BUILD, host.max_concurrent_runs),
):
pytest.fail("build claimed the review slot")
with (
admission.reserve(root, alternate_account, Profile.REVIEW),
admission.reserve(
root,
alternate_account,
Profile.REVIEW,
alternate_account.max_concurrent_runs,
),
pytest.raises(Invalid, match="max_concurrent_runs=3"),
admission.reserve(root, host, Profile.REVIEW),
admission.reserve(root, host, Profile.REVIEW, host.max_concurrent_runs),
):
pytest.fail("review exceeded the host limit")
with admission.reserve(root, host, Profile.REVIEW):
with admission.reserve(root, host, Profile.REVIEW, host.max_concurrent_runs):
assert not (root / "review-1").exists()
with admission.reserve(root, host, Profile.BUILD):
with admission.reserve(root, host, Profile.BUILD, host.max_concurrent_runs):
assert not (root / "build-2").exists()


def test_reviews_can_use_shared_capacity(tmp_path: Path) -> None:
host = replace(LINUX, max_concurrent_runs=2)
root = tmp_path / "admission"
with (
admission.reserve(root, host, Profile.REVIEW),
admission.reserve(root, host, Profile.REVIEW),
admission.reserve(root, host, Profile.REVIEW, host.max_concurrent_runs),
admission.reserve(root, host, Profile.REVIEW, host.max_concurrent_runs),
):
assert (root / "review-1").exists()

Expand All @@ -57,7 +64,9 @@ def test_zero_slots_disables_every_profile(tmp_path: Path, profile: Profile) ->
host = replace(LINUX, max_concurrent_runs=0)
with (
pytest.raises(Invalid, match="max_concurrent_runs=0"),
admission.reserve(tmp_path / "admission", host, profile),
admission.reserve(
tmp_path / "admission", host, profile, host.max_concurrent_runs
),
):
pytest.fail("disabled host admitted a run")

Expand All @@ -66,17 +75,17 @@ def test_a_sole_slot_admits_a_build_then_refuses(tmp_path: Path) -> None:
host = replace(LINUX, max_concurrent_runs=1)
root = tmp_path / "admission"
with (
admission.reserve(root, host, Profile.BUILD),
admission.reserve(root, host, Profile.BUILD, host.max_concurrent_runs),
pytest.raises(Invalid, match="max_concurrent_runs=1"),
admission.reserve(root, host, Profile.REVIEW),
admission.reserve(root, host, Profile.REVIEW, host.max_concurrent_runs),
):
pytest.fail("a second run took the only slot")


def test_widens_a_directory_this_account_owns(tmp_path: Path) -> None:
root = tmp_path / "admission"
root.mkdir(mode=0o755)
with admission.reserve(root, LINUX, Profile.REVIEW):
with admission.reserve(root, LINUX, Profile.REVIEW, LINUX.max_concurrent_runs):
assert stat.S_IMODE(root.stat().st_mode) == 0o1777


Expand All @@ -87,17 +96,36 @@ def test_refuses_a_directory_with_the_wrong_mode(
monkeypatch.setattr(admission.os, "getuid", lambda: other)
with (
pytest.raises(Invalid, match="directory must have mode 1777"),
admission.reserve(tmp_path, LINUX, Profile.REVIEW),
admission.reserve(tmp_path, LINUX, Profile.REVIEW, LINUX.max_concurrent_runs),
):
pytest.fail("admitted a run in a directory with the wrong mode")


def test_refuses_a_slot_that_is_not_regular(tmp_path: Path) -> None:
root = tmp_path / "admission"
with admission.reserve(root, LINUX, Profile.REVIEW):
with admission.reserve(root, LINUX, Profile.REVIEW, LINUX.max_concurrent_runs):
(root / "review-1").mkdir()
with (
pytest.raises(Invalid, match="slot must be a regular file"),
admission.reserve(root, LINUX, Profile.REVIEW),
admission.reserve(root, LINUX, Profile.REVIEW, LINUX.max_concurrent_runs),
):
pytest.fail("admitted a run with an invalid slot")


def test_a_request_without_a_cap_is_refused(tmp_path: Path) -> None:
with (
pytest.raises(Invalid, match="carries no max_concurrent_runs"),
admission.reserve(tmp_path / "admission", LINUX, Profile.REVIEW, None),
):
pytest.fail("no slot may be claimed")


def test_the_request_cap_overrides_the_host_default(tmp_path: Path) -> None:
root = tmp_path / "admission"
host = replace(LINUX, max_concurrent_runs=3)
with (
admission.reserve(root, host, Profile.REVIEW, 1),
pytest.raises(Invalid, match="max_concurrent_runs=1"),
admission.reserve(root, host, Profile.REVIEW, 1),
):
pytest.fail("the second slot must be refused")
11 changes: 10 additions & 1 deletion tests/test_alpha_agent_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"authorized_by": None,
"startup_deadline_seconds": 120,
"fetch_refs": [],
"max_concurrent_runs": None,
}
REVIEW: Data = {**BUILD, "profile": "review", "commit": COMMIT}
CLAUDE: Data = {
Expand Down Expand Up @@ -154,7 +155,9 @@ def test_missing_fields_are_named() -> None:
)


@pytest.mark.parametrize("key", [k for k in BUILD if k not in {"v", "fetch_refs"}])
@pytest.mark.parametrize(
"key", [k for k in BUILD if k not in {"v", "fetch_refs", "max_concurrent_runs"}]
)
def test_each_field_is_required(key: str) -> None:
assert refused(made(BUILD, **{key: MISSING})) == f"request is missing fields: {key}"

Expand Down Expand Up @@ -543,3 +546,9 @@ def test_tainted_host_must_be_a_boolean(bad: object) -> None:
assert refused(made(BUILD, tainted_host=bad)) == (
"request tainted_host must be true or false"
)


def test_a_negative_launcher_cap_is_refused() -> None:
assert refused(made(BUILD, max_concurrent_runs=-1)) == (
"request max_concurrent_runs must not be negative"
)
9 changes: 5 additions & 4 deletions tests/test_alpha_agent_run_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,13 +992,14 @@ def execute(


def test_run_host_refuses_when_host_has_zero_slots(config_file: Path) -> None:
config_file.write_text(
EXAMPLE.replace("[[agent.host]]", "[[agent.host]]\nmax_concurrent_runs = 0")
)
config_file.write_text(EXAMPLE)
files = runfiles.RunFiles(
runfiles.state_home(Path.home()) / "tbhbdev" / "agent-runs", "example"
)
files.write("request.json", json.dumps(request.to_dict(run_request())))
files.write(
"request.json",
json.dumps(request.to_dict(run_request(max_concurrent_runs=0))),
)
files.write("prompt", "example")
assert run_host.main(["example", "--host", "example-linux"], "run-host") == 1
assert files.path("rc").read_text() == "1\n"
Expand Down