-
Notifications
You must be signed in to change notification settings - Fork 400
feat(agent): enforce per-sandbox cgroup v2 memory limits #3142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
daryllimyt
wants to merge
15
commits into
main
Choose a base branch
from
feat/agent-sandbox-cgroup-limits
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
94fa42c
feat(agent): enforce per-sandbox cgroup v2 memory limits
daryllimyt 842e26f
fix(agent): clear stale readiness sentinel on startup
daryllimyt 886454a
fix(config): treat blank agent executor ready-file env as unset
daryllimyt 72679fb
fix(agent): derive cgroup root and enforce sandbox memory budget
daryllimyt 7a037f5
fix(agent): honor ready-file override in compose healthchecks
daryllimyt ed5ce8b
fix(agent): clear stale readiness sentinel before startup validation
daryllimyt ffbe671
feat(agent): delegate cgroup subtree to apiuser in sandbox overlay
daryllimyt 17012bb
fix(agent): set apiuser identity env when dropping privileges
daryllimyt 080c889
Merge origin/main: move cgroup delegation to dedicated entrypoint
daryllimyt f544e7e
fix(agent): harden cgroup detection edge cases
daryllimyt 17c69a9
fix(agent): honor cgroup-enabled flag in delegation entrypoint
daryllimyt ab6c868
fix(agent): honor ancestor cgroup limits in memory budget
daryllimyt 7276d2f
fix(agent): enforce sandbox cgroup limits
daryllimyt cb99c56
fix(agent): use sandbox overlay for compose nsjail
daryllimyt 594c9c5
fix(agent): gate root cgroup delegation on nsjail being enabled
daryllimyt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,252 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import errno | ||
| from datetime import UTC, datetime | ||
| from pathlib import Path | ||
| from unittest.mock import AsyncMock, Mock | ||
|
|
||
| import pytest | ||
|
|
||
| from tracecat.agent.sandbox.cgroup import ( | ||
| AgentExecutorMemoryBudgetError, | ||
| CgroupAvailability, | ||
| PreparedCgroup, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_agent_executor_readiness_sentinel_exists_only_while_running( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tmp_path: Path, | ||
| ) -> None: | ||
| from tracecat.agent import executor_worker | ||
|
|
||
| ready_file = tmp_path / "run" / "agent-executor-ready" | ||
| shutdown_event = asyncio.Event() | ||
| observed_contents: list[str] = [] | ||
|
|
||
| class _FakeWorker: | ||
| def __init__(self, *args: object, **kwargs: object) -> None: | ||
| del args, kwargs | ||
|
|
||
| async def __aenter__(self) -> _FakeWorker: | ||
| return self | ||
|
|
||
| async def __aexit__( | ||
| self, | ||
| exc_type: object, | ||
| exc: object, | ||
| tb: object, | ||
| ) -> None: | ||
| del exc_type, exc, tb | ||
|
|
||
| def keep_concurrency( | ||
| max_concurrent: int, | ||
| prepared_cgroup: PreparedCgroup, | ||
| *, | ||
| reserve_mb: int, | ||
| sandbox_memory_mb: int, | ||
| ) -> int: | ||
| del prepared_cgroup, reserve_mb, sandbox_memory_mb | ||
| return max_concurrent | ||
|
|
||
| async def observe_readiness() -> None: | ||
| try: | ||
| for _ in range(1000): | ||
| if ready_file.exists(): | ||
| observed_contents.append(ready_file.read_text().strip()) | ||
| return | ||
| await asyncio.sleep(0) | ||
| pytest.fail("readiness sentinel was not created") | ||
| finally: | ||
| shutdown_event.set() | ||
|
|
||
| monkeypatch.setenv("TRACECAT__AGENT_EXECUTOR_MAX_CONCURRENT_ACTIVITIES", "2") | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "prepare_agent_sandbox_cgroup", | ||
| lambda: PreparedCgroup(CgroupAvailability.DISABLED, None), | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "clamp_agent_executor_concurrency", | ||
| keep_concurrency, | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "_start_runtime_services", | ||
| AsyncMock(return_value=object()), | ||
| ) | ||
| monkeypatch.setattr(executor_worker, "_stop_runtime_services", AsyncMock()) | ||
| monkeypatch.setattr(executor_worker, "close_storage_client_cache", AsyncMock()) | ||
| monkeypatch.setattr(executor_worker, "Worker", _FakeWorker) | ||
| monkeypatch.setattr(executor_worker, "new_sandbox_runner", lambda: object()) | ||
| monkeypatch.setattr( | ||
| executor_worker.config, | ||
| "TRACECAT__AGENT_EXECUTOR_READY_FILE", | ||
| str(ready_file), | ||
| ) | ||
|
|
||
| observer = asyncio.create_task(observe_readiness()) | ||
| await asyncio.wait_for( | ||
| executor_worker.main(shutdown_event=shutdown_event), | ||
| timeout=2, | ||
| ) | ||
| await observer | ||
|
|
||
| assert not ready_file.exists() | ||
| assert len(observed_contents) == 1 | ||
| started_at = datetime.fromisoformat(observed_contents[0]) | ||
| assert started_at.tzinfo is UTC | ||
|
|
||
|
|
||
| def test_agent_executor_readiness_sentinel_is_best_effort_on_read_only_fs( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tmp_path: Path, | ||
| ) -> None: | ||
| from tracecat.agent import executor_worker | ||
|
|
||
| mock_logger = Mock() | ||
| monkeypatch.setattr(executor_worker, "logger", mock_logger) | ||
|
|
||
| def deny_mkdir( | ||
| self: Path, | ||
| mode: int = 0o777, | ||
| parents: bool = False, | ||
| exist_ok: bool = False, | ||
| ) -> None: | ||
| del self, mode, parents, exist_ok | ||
| raise PermissionError(errno.EROFS, "read-only filesystem") | ||
|
|
||
| monkeypatch.setattr(Path, "mkdir", deny_mkdir) | ||
|
|
||
| created = executor_worker._write_readiness_file( | ||
| tmp_path / "run" / "agent-executor-ready", | ||
| datetime(2026, 7, 27, tzinfo=UTC), | ||
| ) | ||
|
|
||
| assert created is False | ||
| mock_logger.warning.assert_called_once() | ||
| assert mock_logger.warning.call_args.kwargs["errno"] == errno.EROFS | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_agent_executor_removes_stale_readiness_sentinel_on_startup( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tmp_path: Path, | ||
| ) -> None: | ||
| from tracecat.agent import executor_worker | ||
|
|
||
| ready_file = tmp_path / "run" / "agent-executor-ready" | ||
| ready_file.parent.mkdir(parents=True) | ||
| ready_file.write_text("stale\n") | ||
|
|
||
| def keep_concurrency( | ||
| max_concurrent: int, | ||
| prepared_cgroup: PreparedCgroup, | ||
| *, | ||
| reserve_mb: int, | ||
| sandbox_memory_mb: int, | ||
| ) -> int: | ||
| del prepared_cgroup, reserve_mb, sandbox_memory_mb | ||
| return max_concurrent | ||
|
|
||
| monkeypatch.setenv("TRACECAT__AGENT_EXECUTOR_MAX_CONCURRENT_ACTIVITIES", "1") | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "prepare_agent_sandbox_cgroup", | ||
| lambda: PreparedCgroup(CgroupAvailability.DISABLED, None), | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "clamp_agent_executor_concurrency", | ||
| keep_concurrency, | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "_start_runtime_services", | ||
| AsyncMock(side_effect=RuntimeError("startup failed")), | ||
| ) | ||
| monkeypatch.setattr(executor_worker, "_stop_runtime_services", AsyncMock()) | ||
| monkeypatch.setattr(executor_worker, "close_storage_client_cache", AsyncMock()) | ||
| monkeypatch.setattr( | ||
| executor_worker.config, | ||
| "TRACECAT__AGENT_EXECUTOR_READY_FILE", | ||
| str(ready_file), | ||
| ) | ||
|
|
||
| with pytest.raises(RuntimeError, match="startup failed"): | ||
| await executor_worker.main(shutdown_event=asyncio.Event()) | ||
|
|
||
| assert not ready_file.exists() | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| async def test_agent_executor_memory_budget_error_propagates_from_main( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tmp_path: Path, | ||
| ) -> None: | ||
| from tracecat.agent import executor_worker | ||
|
|
||
| cgroup_root = tmp_path / "cgroup" | ||
| cgroup_root.mkdir() | ||
| (cgroup_root / "memory.max").write_text(f"{4096 * 1024 * 1024}\n") | ||
| start_runtime_services = AsyncMock() | ||
| monkeypatch.setenv("TRACECAT__AGENT_EXECUTOR_MAX_CONCURRENT_ACTIVITIES", "1") | ||
| monkeypatch.setattr( | ||
| executor_worker.config, | ||
| "TRACECAT__AGENT_EXECUTOR_MEMORY_RESERVE_MB", | ||
| 4096, | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker.config, | ||
| "TRACECAT__AGENT_SANDBOX_MEMORY_MB", | ||
| 4096, | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "prepare_agent_sandbox_cgroup", | ||
| lambda: PreparedCgroup(CgroupAvailability.UNAVAILABLE, cgroup_root), | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "_start_runtime_services", | ||
| start_runtime_services, | ||
| ) | ||
|
|
||
| with pytest.raises( | ||
| AgentExecutorMemoryBudgetError, | ||
| match="container_limit_mb=4096", | ||
| ): | ||
| await executor_worker.main(shutdown_event=asyncio.Event()) | ||
|
|
||
| start_runtime_services.assert_not_awaited() | ||
|
|
||
|
|
||
| @pytest.mark.anyio | ||
| @pytest.mark.parametrize("max_concurrent", ["0", "-1"]) | ||
| async def test_agent_executor_rejects_nonpositive_concurrency( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| max_concurrent: str, | ||
| ) -> None: | ||
| from tracecat.agent import executor_worker | ||
|
|
||
| prepare_cgroup = Mock() | ||
| monkeypatch.setenv( | ||
| "TRACECAT__AGENT_EXECUTOR_MAX_CONCURRENT_ACTIVITIES", | ||
| max_concurrent, | ||
| ) | ||
| monkeypatch.setattr( | ||
| executor_worker, | ||
| "prepare_agent_sandbox_cgroup", | ||
| prepare_cgroup, | ||
| ) | ||
|
|
||
| with pytest.raises( | ||
| ValueError, | ||
| match="TRACECAT__AGENT_EXECUTOR_MAX_CONCURRENT_ACTIVITIES", | ||
| ): | ||
| await executor_worker.main(shutdown_event=asyncio.Event()) | ||
|
|
||
| prepare_cgroup.assert_not_called() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.