:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add sandbox memory watchdog sidecar (#107622)
Alessandro Pogliaghi138f18f458f2
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex eb287d29b0ae..30addd8ea1ce 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -142,6 +142,12 @@ TASKS_COMPUTE_QUOTA_ENFORCEMENT_ENABLED: bool = get_from_env(type_cast=str_to_bool,)+TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED: bool = get_from_env(+ "TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED",+ True,+ type_cast=str_to_bool,+)+# Event-count threshold for the above; 0 relies on Temporal's is_continue_as_new_suggested().TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD: int = get_from_env("TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD", 4000, type_cast=intdiff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex de591ce28c4b..9a9e36a00e30 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -87,6 +87,8 @@ from products.tasks.backend.facade.temporal import (TASKS_LATENCY_HISTOGRAM_METRICS,TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS,TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS,+ TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_BUCKETS,+ TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_METRICS,TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,TASKS_RUN_TOKENS_HISTOGRAM_METRICS,TASKS_RUN_TURNS_HISTOGRAM_BUCKETS,@@ -320,6 +322,9 @@ async def create_worker()| dict(zip(TASKS_RUN_TOKENS_HISTOGRAM_METRICS, itertools.repeat(TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS)))| dict(zip(TASKS_RUN_TURNS_HISTOGRAM_METRICS, itertools.repeat(TASKS_RUN_TURNS_HISTOGRAM_BUCKETS)))+ | dict(+ zip(TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_METRICS, itertools.repeat(TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_BUCKETS))+ )| dict(zip(EVAL_REPORTS_LATENCY_HISTOGRAM_METRICS,diff --git a/products/tasks/backend/facade/temporal.py b/products/tasks/backend/facade/temporal.pyindex 34239a1bf73c..2248c51967dc 100644--- a/products/tasks/backend/facade/temporal.py+++ b/products/tasks/backend/facade/temporal.py@@ -21,6 +21,8 @@ from products.tasks.backend.temporal.metrics import (TASKS_LATENCY_HISTOGRAM_METRICS,TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS,TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS,+ TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_BUCKETS,+ TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_METRICS,TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS,TASKS_RUN_TOKENS_HISTOGRAM_METRICS,TASKS_RUN_TURNS_HISTOGRAM_BUCKETS,@@ -40,6 +42,8 @@ __all__ = ["TASKS_LATENCY_HISTOGRAM_METRICS","TASKS_LAUNCH_PREPARATION_HISTOGRAM_BUCKETS","TASKS_LAUNCH_PREPARATION_HISTOGRAM_METRICS",+ "TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_BUCKETS",+ "TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_METRICS","TASKS_RUN_TOKENS_HISTOGRAM_BUCKETS","TASKS_RUN_TOKENS_HISTOGRAM_METRICS","TASKS_RUN_TURNS_HISTOGRAM_BUCKETS",diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex 10c8fec1cbb6..78513e0157eb 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -38,6 +38,14 @@ from products.tasks.backend.logic.services.agentsh import (read_gh_guard_script,)from products.tasks.backend.logic.services.mcp_url import resolve_mcp_url+from products.tasks.backend.logic.services.memory_watchdog import (+ MEMORY_WATCHDOG_MISSING_MARKER,+ MEMORY_WATCHDOG_PATH,+ MEMORY_WATCHDOG_START_FAILED_MARKER,+ build_memory_watchdog_probe_command,+ build_memory_watchdog_start_command,+ read_memory_watchdog_script,+)from products.tasks.backend.logic.services.sandbox import (CLAUDE_CREDENTIAL_UNAVAILABLE_MESSAGE,CODEX_CREDENTIAL_UNAVAILABLE_MESSAGE,@@ -203,12 +211,15 @@ def _start_and_wait_command(command: str, max_attempts: int = AGENT_SERVER_HEALTclass AgentServerPreflight:reused: boolcapabilities: frozenset[str]+ memory_watchdog_missing: bool = Falsedef supports(self, capability: str) -> bool:return capability in self.capabilities-def build_agent_server_preflight_script(*, probe_health: bool, executable_paths: tuple[str, ...]) -> str:+def build_agent_server_preflight_script(+ *, probe_health: bool, executable_paths: tuple[str, ...], probe_memory_watchdog: bool = False+) -> str:lines = [f"if ! ( {build_bundled_skills_clear_command()} ); then exit {AGENT_SERVER_PREFLIGHT_SKILLS_EXIT_CODE}; fi"]@@ -216,6 +227,8 @@ def build_agent_server_preflight_script(*, probe_health: bool, executable_paths:f"if ! chmod +x {shlex.quote(path)}; then exit {AGENT_SERVER_PREFLIGHT_CHMOD_EXIT_CODE}; fi"for path in executable_paths)+ if probe_memory_watchdog:+ lines.append(build_memory_watchdog_probe_command())lines.extend(f"if {build_agent_server_capability_probe(capability)}; then "f"echo {shlex.quote(AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX + capability)}; fi"@@ -324,11 +337,13 @@ class AgentServerLaunchMixin(SandboxBase):claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token_file: str | None = None,+ sandbox_runtime: str | None = None,) -> str:env_prefix = build_agent_runtime_env_prefix(interaction_origin=interaction_origin,agent_runtime=agent_runtime,sandbox_id=self.id,+ sandbox_runtime=sandbox_runtime,runtime_adapter=runtime_adapter,provider=provider,model=model,@@ -400,6 +415,9 @@ class AgentServerLaunchMixin(SandboxBase):f"(nohup {server_cmd} > /tmp/agent-server.log 2>&1 & echo $! > /tmp/agent-server.pid)")+ def _sandbox_runtime(self) -> str | None:+ return None+def _stage_codex_run_token(self, codex_run_token: str) -> None:self._write_required_file(CODEX_RUN_TOKEN_FILE, codex_run_token.encode())# Best effort: a child process must not read the token out of the agent-server's memory.@@ -515,6 +533,19 @@ class AgentServerLaunchMixin(SandboxBase):cause=RuntimeError(f"chmod {mode} {path} exited {result.exit_code}"),)+ def _install_memory_watchdog(self, preflight: AgentServerPreflight) -> bool:+ if not settings.TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED:+ return False+ if not preflight.memory_watchdog_missing:+ return True+ try:+ self._write_required_file(MEMORY_WATCHDOG_PATH, read_memory_watchdog_script())+ self._chmod_required(MEMORY_WATCHDOG_PATH, "+x")+ except Exception as error:+ logger.warning(f"Failed to install the memory watchdog in sandbox {self.id}: {error}")+ return False+ return True+def _validate_agent_server_launch(self) -> None:if not self.is_running():raise RuntimeError("Sandbox not in running state.")@@ -529,7 +560,9 @@ class AgentServerLaunchMixin(SandboxBase):executable_paths = self._install_agent_server_launch_files()result = self.execute(build_agent_server_preflight_script(- probe_health=self._agent_server_reuse_enabled(), executable_paths=executable_paths+ probe_health=self._agent_server_reuse_enabled(),+ executable_paths=executable_paths,+ probe_memory_watchdog=settings.TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED,),timeout_seconds=AGENT_SERVER_PREFLIGHT_TIMEOUT_SECONDS,)@@ -567,7 +600,11 @@ class AgentServerLaunchMixin(SandboxBase):self._on_agent_server_reused()return AgentServerPreflight(reused=True, capabilities=capabilities)self._free_agent_server_port()- return AgentServerPreflight(reused=False, capabilities=capabilities)+ return AgentServerPreflight(+ reused=False,+ capabilities=capabilities,+ memory_watchdog_missing=MEMORY_WATCHDOG_MISSING_MARKER in lines,+ )def _launch_prepared_agent_server(self,@@ -617,6 +654,8 @@ class AgentServerLaunchMixin(SandboxBase):{"sandbox_id": self.id, "stderr": launch_result.stderr, "exit_code": str(launch_result.exit_code)},cause=RuntimeError(launch_result.stderr or "launch command returned non-zero exit"),)+ if MEMORY_WATCHDOG_START_FAILED_MARKER in launch_result.stdout:+ logger.warning(f"Failed to start the memory watchdog in sandbox {self.id}")if wait_for_health:if allowed_domains is not None and not self._agentsh_daemon_is_healthy():@@ -663,6 +702,7 @@ class AgentServerLaunchMixin(SandboxBase):claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token: str | None = None,+ sandbox_runtime: str | None = None,) -> int | None:"""Start the agent-server HTTP server in the sandbox.@@ -684,6 +724,7 @@ class AgentServerLaunchMixin(SandboxBase):repo_path = f"/tmp/workspace/repos/{org}/{repo}"self._prepare_agent_server_launch(allowed_domains)+ memory_watchdog_ready = self._install_memory_watchdog(preflight)codex_run_token_file = CODEX_RUN_TOKEN_FILE if codex_run_token else None@@ -715,7 +756,7 @@ class AgentServerLaunchMixin(SandboxBase):# The launch shell deletes the token file, so every launch attempt needs its own copy.if codex_run_token:self._stage_codex_run_token(codex_run_token)- return self._build_agent_server_command(+ command = self._build_agent_server_command(repo_path,task_id,run_id,@@ -748,7 +789,11 @@ class AgentServerLaunchMixin(SandboxBase):claude_model_access=claude_model_access,codex_model_access=codex_model_access,codex_run_token_file=codex_run_token_file,+ sandbox_runtime=sandbox_runtime or self._sandbox_runtime(),)+ if memory_watchdog_ready:+ return f"{build_memory_watchdog_start_command()}; {command}"+ return commandlogger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")return self._launch_prepared_agent_server(diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex b8a23646cd5c..04483691d112 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -983,6 +983,7 @@ class DockerSandbox(AgentServerLaunchMixin):claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token_file: str | None = None,+ sandbox_runtime: str | None = None,) -> str:# The host proxy URL (e.g. localhost:8003) is unreachable from inside the container;# rewrite it the same way POSTHOG_API_URL is for Docker sandboxes.@@ -992,6 +993,7 @@ class DockerSandbox(AgentServerLaunchMixin):interaction_origin=interaction_origin,agent_runtime=agent_runtime,sandbox_id=self.id,+ sandbox_runtime=sandbox_runtime,runtime_adapter=runtime_adapter,provider=provider,model=model,@@ -1086,6 +1088,9 @@ class DockerSandbox(AgentServerLaunchMixin):def _agent_server_reuse_enabled(self) -> bool:return False+ def _sandbox_runtime(self) -> str | None:+ return "docker"+def _install_agent_server_launch_files(self) -> tuple[str, ...]:return ()diff --git a/products/tasks/backend/logic/services/hogland_sandbox.py b/products/tasks/backend/logic/services/hogland_sandbox.pyindex a8cf5cffd98e..edee6268f47e 100644--- a/products/tasks/backend/logic/services/hogland_sandbox.py+++ b/products/tasks/backend/logic/services/hogland_sandbox.py@@ -232,6 +232,9 @@ class HoglandSandbox(AgentServerLaunchMixin):def sandbox_url(self) -> str | None:return self._sandbox_url+ def _sandbox_runtime(self) -> str | None:+ return "hogland"+@classmethoddef create(cls, config: SandboxConfig) -> HoglandSandbox:snapshot_alias = TEMPLATE_TO_SNAPSHOT_ALIAS.get(config.template)diff --git a/products/tasks/backend/logic/services/memory_watchdog.py b/products/tasks/backend/logic/services/memory_watchdog.pynew file mode 100644index 000000000000..1a8edaacb992--- /dev/null+++ b/products/tasks/backend/logic/services/memory_watchdog.py@@ -0,0 +1,183 @@+from __future__ import annotations++import json+import shlex+import hashlib+from functools import cache+from pathlib import Path+from typing import Literal++from posthog.dataclasses import frozen++MEMORY_WATCHDOG_PATH = "/usr/local/bin/posthog-memory-watchdog"+MEMORY_WATCHDOG_STATE_PATH = "/tmp/posthog-memory-watchdog.json"+MEMORY_WATCHDOG_EVENTS_PATH = "/tmp/posthog-memory-watchdog.jsonl"+MEMORY_WATCHDOG_LOG_PATH = "/tmp/posthog-memory-watchdog.log"+MEMORY_WATCHDOG_CLI_PID_FILE = "/tmp/agent-cli.pid"+MEMORY_WATCHDOG_HEARTBEAT_STALE_SECONDS = 10.0+MEMORY_WATCHDOG_STATE_MAX_BYTES = 4096+MEMORY_WATCHDOG_EVENTS_MAX_BYTES = 256 * 1024+MEMORY_WATCHDOG_MISSING_MARKER = "__posthog_memory_watchdog_missing=1"+MEMORY_WATCHDOG_START_FAILED_MARKER = "__posthog_memory_watchdog_start_failed=1"+MEMORY_WATCHDOG_NOW_PREFIX = "__posthog_memory_watchdog_now="+MEMORY_WATCHDOG_STATE_SEPARATOR = "__posthog_memory_watchdog_state__"+MEMORY_WATCHDOG_EVENTS_SEPARATOR = "__posthog_memory_watchdog_events__"+MEMORY_WATCHDOG_ENV_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"++_MEMORY_WATCHDOG_SOURCE_PATH = Path(__file__).resolve().parents[2] / "sandbox" / "images" / "memory_watchdog.py"++MemoryWatchdogStatus = Literal["alive", "stale", "missing"]+++def read_memory_watchdog_script() -> bytes:+ return _MEMORY_WATCHDOG_SOURCE_PATH.read_bytes()+++@cache+def memory_watchdog_script_sha256() -> str:+ return hashlib.sha256(read_memory_watchdog_script()).hexdigest()+++def build_memory_watchdog_probe_command() -> str:+ path = shlex.quote(MEMORY_WATCHDOG_PATH)+ return (+ f"{{ [ -x {path} ] && [ \"$(sha256sum {path} 2>/dev/null | cut -d' ' -f1)\" = {memory_watchdog_script_sha256()} ]; }} "+ f"|| echo {shlex.quote(MEMORY_WATCHDOG_MISSING_MARKER)}"+ )+++def build_memory_watchdog_source_check() -> str:+ return (+ "{ { [ -r /sys/fs/cgroup/memory/memory.usage_in_bytes ] && [ -r /sys/fs/cgroup/memory/memory.limit_in_bytes ]; } "+ "|| { [ -r /sys/fs/cgroup/memory.current ] && [ -r /sys/fs/cgroup/memory.max ]; } "+ "|| [ -r /proc/meminfo ]; }"+ )+++def build_memory_watchdog_start_command() -> str:+ return (+ f"{{ {build_memory_watchdog_source_check()} && [ -x {shlex.quote(MEMORY_WATCHDOG_PATH)} ] && "+ f"{{ /usr/bin/env -i PATH={MEMORY_WATCHDOG_ENV_PATH} /usr/bin/setsid /usr/bin/nohup {shlex.quote(MEMORY_WATCHDOG_PATH)} "+ f">{shlex.quote(MEMORY_WATCHDOG_LOG_PATH)} 2>&1 </dev/null & }}; }} "+ f"|| echo {shlex.quote(MEMORY_WATCHDOG_START_FAILED_MARKER)}"+ )+++def build_memory_watchdog_read_command() -> str:+ return (+ f'echo "{MEMORY_WATCHDOG_NOW_PREFIX}$(date +%s)"; '+ f"echo {MEMORY_WATCHDOG_STATE_SEPARATOR}; "+ f"head -c {MEMORY_WATCHDOG_STATE_MAX_BYTES} {shlex.quote(MEMORY_WATCHDOG_STATE_PATH)} 2>/dev/null; echo; "+ f"echo {MEMORY_WATCHDOG_EVENTS_SEPARATOR}; "+ f"tail -c {MEMORY_WATCHDOG_EVENTS_MAX_BYTES} {shlex.quote(MEMORY_WATCHDOG_EVENTS_PATH)} 2>/dev/null; true"+ )+++@frozen+class MemoryWatchdogKill:+ pid: int | None+ comm: str+ top_comm: str | None+ tree_rss: int+ current: int+ limit: int+ signal: str+++@frozen+class MemoryWatchdogSummary:+ status: MemoryWatchdogStatus+ source: str | None+ kills: tuple[MemoryWatchdogKill, ...]+ kill_count: int+ no_target: int+ pressure_episodes: int+ peak_ratio: float | None++ @property+ def alive(self) -> bool:+ return self.status == "alive"+++def _as_int(value: object) -> int | None:+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ return int(value)+++def _parse_json_object(text: str) -> dict[str, object] | None:+ try:+ parsed = json.loads(text)+ except ValueError:+ return None+ return parsed if isinstance(parsed, dict) else None+++def summarize_memory_watchdog(state_json: str, events_jsonl: str, now: float) -> MemoryWatchdogSummary:+ state = _parse_json_object(state_json.strip()) if state_json.strip() else None+ events = [event for line in events_jsonl.splitlines() if (event := _parse_json_object(line)) is not None]++ kills = tuple(+ MemoryWatchdogKill(+ pid=_as_int(event.get("pid")),+ comm=str(event.get("comm") or "unknown"),+ top_comm=str(event["top_comm"]) if event.get("top_comm") else None,+ tree_rss=_as_int(event.get("tree_rss")) or 0,+ current=_as_int(event.get("current")) or 0,+ limit=_as_int(event.get("limit")) or 0,+ signal=str(event.get("signal") or "unknown"),+ )+ for event in events+ if event.get("event") == "kill"+ )++ kill_count = len(kills)+ no_target = sum(1 for event in events if event.get("event") == "no_target")+ pressure_episodes = sum(1 for event in events if event.get("event") == "pressure")++ status: MemoryWatchdogStatus = "missing"+ source: str | None = None+ peak_ratio: float | None = None+ if state is not None:+ state_kills = state.get("kills")+ state_no_target = state.get("no_target_episodes")+ state_pressure = state.get("pressure_episodes")+ if isinstance(state_kills, int) and not isinstance(state_kills, bool):+ kill_count = state_kills+ if isinstance(state_no_target, int) and not isinstance(state_no_target, bool):+ no_target = state_no_target+ if isinstance(state_pressure, int) and not isinstance(state_pressure, bool):+ pressure_episodes = state_pressure+ heartbeat = state.get("ts")+ is_fresh = (+ isinstance(heartbeat, int | float) and now - float(heartbeat) <= MEMORY_WATCHDOG_HEARTBEAT_STALE_SECONDS+ )+ status = "alive" if is_fresh else "stale"+ source = str(state["source"]) if state.get("source") is not None else None+ peak_current = _as_int(state.get("peak_current"))+ limit = _as_int(state.get("limit"))+ if peak_current is not None and limit:+ peak_ratio = min(1.0, max(0.0, peak_current / limit))++ return MemoryWatchdogSummary(+ status=status,+ source=source,+ kills=kills,+ kill_count=kill_count,+ no_target=no_target,+ pressure_episodes=pressure_episodes,+ peak_ratio=peak_ratio,+ )+++def parse_memory_watchdog_read_output(stdout: str, fallback_now: float) -> MemoryWatchdogSummary:+ head, _, rest = stdout.partition(MEMORY_WATCHDOG_STATE_SEPARATOR)+ state_json, _, events_jsonl = rest.partition(MEMORY_WATCHDOG_EVENTS_SEPARATOR)+ now = fallback_now+ for line in head.splitlines():+ if line.startswith(MEMORY_WATCHDOG_NOW_PREFIX):+ try:+ now = float(line.removeprefix(MEMORY_WATCHDOG_NOW_PREFIX))+ except ValueError:+ pass+ return summarize_memory_watchdog(state_json, events_jsonl, now)diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 8876138fb7c4..b1ef851634be 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -356,6 +356,7 @@ LOCAL_MODAL_HOGLI_SHIM_SCRIPT = Path("products/tasks/backend/sandbox/images/hoglLOCAL_MODAL_NOTEBOOK_KERNEL_MODULE = Path("products/notebooks/backend/kernel_package.py")LOCAL_MODAL_NOTEBOOK_KERNEL_DIR = Path("products/notebooks/backend/sandbox/kernel")LOCAL_MODAL_CPU_BILLING_SAMPLER = Path("products/tasks/backend/sandbox/images/cpu_billing_sampler.py")+LOCAL_MODAL_MEMORY_WATCHDOG = Path("products/tasks/backend/sandbox/images/memory_watchdog.py")# The base image builds the agent-shadow observer from source in its first stage.LOCAL_MODAL_AGENT_SHADOW_DIR = Path("packages/agent/agent-shadow")@@ -742,6 +743,7 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,destination_sampler_path = context_dir / LOCAL_MODAL_CPU_BILLING_SAMPLERdestination_sampler_path.parent.mkdir(parents=True, exist_ok=True)shutil.copy2(base_dir / LOCAL_MODAL_CPU_BILLING_SAMPLER, destination_sampler_path)+ shutil.copy2(base_dir / LOCAL_MODAL_MEMORY_WATCHDOG, context_dir / LOCAL_MODAL_MEMORY_WATCHDOG)if template == SandboxTemplate.DEFAULT_BASE:destination_hogli_shim_path = context_dir / LOCAL_MODAL_HOGLI_SHIM_SCRIPT@@ -815,6 +817,9 @@ class ModalSandbox(AgentServerLaunchMixin):def _install_agent_server_launch_files(self) -> tuple[str, ...]:return ()+ def _sandbox_runtime(self) -> str | None:+ return "vm" if self.config.is_vm else "gvisor"+def _on_agent_server_reused(self) -> None:# A restored snapshot can carry a healthy agent-server with a stale bash-env# or gh shim from the snapshot's epoch. Refresh both before accepting reuse;diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 8093106662d8..f1b31f41c953 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -359,6 +359,7 @@ def build_agent_runtime_env_prefix(interaction_origin: str | None = None,agent_runtime: str | None = None,sandbox_id: str | None = None,+ sandbox_runtime: str | None = None,runtime_adapter: str | None = None,provider: str | None = None,model: str | None = None,@@ -380,6 +381,7 @@ def build_agent_runtime_env_prefix("POSTHOG_CODE_INTERACTION_ORIGIN": interaction_origin,"POSTHOG_AGENT_RUNTIME": agent_runtime,"POSTHOG_SANDBOX_ID": sandbox_id,+ "POSTHOG_SANDBOX_RUNTIME": sandbox_runtime,"POSTHOG_CODE_RUNTIME_ADAPTER": runtime_adapter,"POSTHOG_CODE_PROVIDER": provider,"POSTHOG_CODE_MODEL": model,@@ -678,6 +680,7 @@ class SandboxBase(ABC):claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token: str | None = None,+ sandbox_runtime: str | None = None,) -> int | None:"""Start the agent-server HTTP server in the sandbox.diff --git a/products/tasks/backend/logic/services/tests/test_memory_watchdog.py b/products/tasks/backend/logic/services/tests/test_memory_watchdog.pynew file mode 100644index 000000000000..44a6a996e874--- /dev/null+++ b/products/tasks/backend/logic/services/tests/test_memory_watchdog.py@@ -0,0 +1,408 @@+import json+import subprocess+from pathlib import Path++import pytest++from products.tasks.backend.logic.services.memory_watchdog import (+ MEMORY_WATCHDOG_EVENTS_PATH,+ MEMORY_WATCHDOG_EVENTS_SEPARATOR,+ MEMORY_WATCHDOG_MISSING_MARKER,+ MEMORY_WATCHDOG_NOW_PREFIX,+ MEMORY_WATCHDOG_PATH,+ MEMORY_WATCHDOG_STATE_PATH,+ MEMORY_WATCHDOG_STATE_SEPARATOR,+ MemoryWatchdogKill,+ build_memory_watchdog_probe_command,+ build_memory_watchdog_read_command,+ build_memory_watchdog_start_command,+ parse_memory_watchdog_read_output,+ read_memory_watchdog_script,+ summarize_memory_watchdog,+)+from products.tasks.backend.sandbox.images import memory_watchdog as sidecar+from products.tasks.backend.sandbox.images.memory_watchdog import Process, choose_victim, read_memory, should_trigger++GIB = 1024**3+LAUNCH_ENV = "env -u A BASH_ENV=/tmp/bash-env.sh " + " ".join(f"POSTHOG_VAR_{i}=value-{i}" for i in range(20))+AGENT_SERVER = Process(+ pid=10, ppid=1, comm="MainThread", rss=GIB, cmdline="node ./node_modules/.bin/agent-server --port 8000"+)+CLI = Process(pid=20, ppid=10, comm="claude", rss=GIB, cmdline="claude")+MCP_SERVER = Process(pid=21, ppid=20, comm="node", rss=6 * GIB, cmdline="mcp-server")+SMALL_SHELL = Process(pid=30, ppid=20, comm="bash", rss=10, cmdline="bash -c ls")+BIG_SHELL = Process(pid=40, ppid=20, comm="bash", rss=10, cmdline="bash -c pnpm test")+BIG_SHELL_CHILD = Process(pid=41, ppid=40, comm="node", rss=2 * GIB, cmdline="node vitest")+BIG_SHELL_GRANDCHILD = Process(pid=42, ppid=41, comm="node", rss=3 * GIB, cmdline="node worker")+PREVIEW_SHELL = Process(pid=50, ppid=1, comm="sh", rss=8 * GIB, cmdline="sh start-preview")+WATCHDOG = Process(pid=60, ppid=1, comm="python3", rss=10, cmdline="posthog-memory-watchdog")+SANDBOX_PROCESSES = [+ AGENT_SERVER,+ CLI,+ MCP_SERVER,+ SMALL_SHELL,+ BIG_SHELL,+ BIG_SHELL_CHILD,+ BIG_SHELL_GRANDCHILD,+ PREVIEW_SHELL,+ WATCHDOG,+]+AGENTSH = Process(+ pid=5,+ ppid=1,+ comm="agentsh",+ rss=10,+ cmdline=f"agentsh exec -- /tmp/env-wrapper.sh bash -c cd /scripts && {LAUNCH_ENV} ./node_modules/.bin/agent-server",+)+ENV_WRAPPER = Process(+ pid=7,+ ppid=5,+ comm="sh",+ rss=10,+ cmdline=f"sh /tmp/env-wrapper.sh bash -c cd /scripts && {LAUNCH_ENV} ./node_modules/.bin/agent-server",+)+LAUNCH_SHELL = Process(+ pid=6, ppid=7, comm="bash", rss=10, cmdline=f"bash -c cd /scripts && {LAUNCH_ENV} ./node_modules/.bin/agent-server"+)+MARKED_SHELL = Process(+ pid=45, ppid=20, comm="bash", rss=7 * GIB, cmdline="bash -c pnpm vitest run agent-server.test.ts"+)+AGENTSH_PROCESSES = [+ AGENTSH,+ ENV_WRAPPER,+ LAUNCH_SHELL,+ AGENT_SERVER._replace(ppid=6),+ *(p for p in SANDBOX_PROCESSES if p.pid != AGENT_SERVER.pid),+]+SECOND_CLI = Process(pid=25, ppid=10, comm="claude", rss=GIB, cmdline="claude side-question")+SECOND_CLI_SHELL = Process(pid=35, ppid=25, comm="bash", rss=6 * GIB, cmdline="bash -c pnpm build")+++ "current, limit, expected",+ [+ (int(0.84 * GIB), GIB, False),+ (int(0.85 * GIB) + 1, GIB, True),+ (GIB, GIB, True),+ (GIB, 0, False),+ ],+)+def test_should_trigger(current: int, limit: int, expected: bool) -> None:+ assert should_trigger(current, limit, 0.85) is expected+++ "processes, cli_pids, agent_server_pid, protected_pids, current, expected_root, expected_top, expected_pids, expected_count",+ [+ (SANDBOX_PROCESSES, (20,), 10, {60, 1}, 14 * GIB, 40, 42, (42, 41, 40), 2),+ (+ [p for p in SANDBOX_PROCESSES if p.pid not in (30, 40, 41, 42)],+ (20,),+ 10,+ {60, 1},+ 14 * GIB,+ None,+ None,+ (),+ 0,+ ),+ ([p for p in SANDBOX_PROCESSES if p.pid != 20], (20,), 10, {60, 1}, 14 * GIB, None, None, (), 0),+ (+ [*SANDBOX_PROCESSES, Process(pid=70, ppid=21, comm="sh", rss=9 * GIB, cmdline="sh -c mcp")],+ (),+ 10,+ {60, 1},+ 14 * GIB,+ 70,+ 70,+ (70,),+ 3,+ ),+ (SANDBOX_PROCESSES, (99,), 10, {60, 1}, 14 * GIB, 40, 42, (42, 41, 40), 2),+ (+ [p._replace(rss=512 * 1024 * 1024) if p.pid == SMALL_SHELL.pid else p for p in SANDBOX_PROCESSES],+ (20,),+ 10,+ {60, 1, 41},+ 14 * GIB,+ 30,+ 30,+ (30,),+ 1,+ ),+ (SANDBOX_PROCESSES, (), None, {60, 1}, 14 * GIB, None, None, (), 0),+ (AGENTSH_PROCESSES, (), 5, {60, 1}, 14 * GIB, 40, 42, (42, 41, 40), 2),+ ([*AGENTSH_PROCESSES, MARKED_SHELL], (), 5, {60, 1}, 14 * GIB, 45, 45, (45,), 3),+ (SANDBOX_PROCESSES, (99, 20), 10, {60, 1}, 14 * GIB, 40, 42, (42, 41, 40), 2),+ (+ [*SANDBOX_PROCESSES, SECOND_CLI, SECOND_CLI_SHELL],+ (20, 25),+ 10,+ {60, 1},+ 14 * GIB,+ 35,+ 35,+ (35,),+ 3,+ ),+ ([AGENT_SERVER, CLI, SMALL_SHELL], (20,), 10, {60, 1}, 14 * GIB, None, None, (), 0),+ (+ [AGENT_SERVER, CLI, SMALL_SHELL._replace(rss=GIB // 2)],+ (20,),+ 10,+ {60, 1},+ int(0.90 * 16 * GIB),+ None,+ None,+ (),+ 0,+ ),+ (+ [AGENT_SERVER, CLI, SMALL_SHELL._replace(rss=GIB // 2)],+ (20,),+ 10,+ {60, 1},+ int(0.95 * 16 * GIB),+ 30,+ 30,+ (30,),+ 1,+ ),+ ],+ ids=[+ "largest_shell_tree_under_cli_deepest_first",+ "mcp_server_and_detached_preview_are_never_candidates",+ "cli_pid_file_present_but_process_gone_without_agent_server_shells",+ "fallback_to_shells_under_agent_server_without_cli_pid",+ "stale_cli_pid_falls_back_to_agent_server",+ "tree_holding_a_protected_pid_is_skipped",+ "no_pids_known",+ "fallback_skips_the_launch_shell_under_agentsh",+ "fallback_still_stops_a_tool_shell_that_names_the_agent_server",+ "second_cli_pid_is_used_when_the_first_is_dead",+ "shells_under_every_live_cli_pid_are_candidates",+ "negligible_tree_is_not_a_victim",+ "tree_smaller_than_the_needed_release_is_not_a_victim",+ "any_meaningful_tree_is_a_victim_above_the_danger_line",+ ],+)+def test_choose_victim(+ processes: list[Process],+ cli_pids: tuple[int, ...],+ agent_server_pid: int | None,+ protected_pids: set[int],+ current: int,+ expected_root: int | None,+ expected_top: int | None,+ expected_pids: tuple[int, ...],+ expected_count: int,+) -> None:+ victim = choose_victim(processes, cli_pids, agent_server_pid, protected_pids, current, 16 * GIB)++ if expected_root is None:+ assert victim is None+ return+ assert victim is not None+ assert victim.tree.root.pid == expected_root+ assert victim.tree.top.pid == expected_top+ assert victim.tree.pids == expected_pids+ assert victim.candidate_count == expected_count+++ "stat_content, expected_current",+ [+ (None, 10 * GIB),+ ("active_file 1\ninactive_file 3221225472\n", 7 * GIB),+ ("inactive_file 12884901888\n", 10 * GIB),+ ],+ ids=["stat_file_absent", "inactive_file_is_subtracted", "inactive_file_above_usage_is_ignored"],+)+def test_read_memory_leaves_out_reclaimable_cache(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stat_content: str | None, expected_current: int+) -> None:+ (tmp_path / "memory.current").write_text(f"{10 * GIB}\n")+ (tmp_path / "memory.max").write_text(f"{16 * GIB}\n")+ if stat_content is not None:+ (tmp_path / "memory.stat").write_text(stat_content)+ monkeypatch.setattr(sidecar, "CGROUP_V1_USAGE_PATH", tmp_path / "v1-missing")+ monkeypatch.setattr(sidecar, "CGROUP_V2_CURRENT_PATH", tmp_path / "memory.current")+ monkeypatch.setattr(sidecar, "CGROUP_V2_MAX_PATH", tmp_path / "memory.max")+ monkeypatch.setattr(sidecar, "CGROUP_V2_STAT_PATH", tmp_path / "memory.stat")++ reading = read_memory()++ assert reading is not None+ assert reading.current == expected_current+ assert reading.source == "cgroup_v2"+++def _jsonl(*records: dict[str, object]) -> str:+ return "\n".join(json.dumps(record) for record in records)+++KILL_RECORD = {+ "event": "kill",+ "ts": 100.0,+ "current": 14 * GIB,+ "limit": 16 * GIB,+ "pid": 40,+ "comm": "bash",+ "top_comm": "vitest",+ "tree_rss": 5 * GIB,+ "signal": "SIGTERM",+}+++ "state, events, now, expected_status, expected_kills, expected_kill_count, expected_no_target, expected_pressure, expected_peak",+ [+ (+ json.dumps({"ts": 100.0, "source": "cgroup_v1", "peak_current": 12 * GIB, "limit": 16 * GIB}),+ _jsonl({"event": "pressure"}, KILL_RECORD, {"event": "no_target"}),+ 105.0,+ "alive",+ 1,+ 1,+ 1,+ 1,+ 0.75,+ ),+ (+ json.dumps({"ts": 100.0, "source": "meminfo", "peak_current": 1, "limit": 2}),+ "",+ 500.0,+ "stale",+ 0,+ 0,+ 0,+ 0,+ 0.5,+ ),+ ("", "", 100.0, "missing", 0, 0, 0, 0, None),+ ("{truncated", '{"event": "kill"\n' + json.dumps(KILL_RECORD), 100.0, "missing", 1, 1, 0, 0, None),+ (+ json.dumps(+ {+ "ts": 100.0,+ "source": "cgroup_v2",+ "peak_current": 15 * GIB,+ "limit": 16 * GIB,+ "kills": 7,+ "no_target_episodes": 4,+ "pressure_episodes": 9,+ }+ ),+ _jsonl({"event": "pressure"}, KILL_RECORD),+ 105.0,+ "alive",+ 1,+ 7,+ 4,+ 9,+ 0.9375,+ ),+ ],+ ids=[+ "alive_with_events",+ "stale_heartbeat",+ "missing_files",+ "malformed_lines_are_skipped",+ "state_counters_cover_events_lost_from_the_tail",+ ],+)+def test_summarize_memory_watchdog(+ state: str,+ events: str,+ now: float,+ expected_status: str,+ expected_kills: int,+ expected_kill_count: int,+ expected_no_target: int,+ expected_pressure: int,+ expected_peak: float | None,+) -> None:+ summary = summarize_memory_watchdog(state, events, now)++ assert summary.status == expected_status+ assert len(summary.kills) == expected_kills+ assert summary.kill_count == expected_kill_count+ assert summary.no_target == expected_no_target+ assert summary.pressure_episodes == expected_pressure+ assert summary.peak_ratio == expected_peak+++def test_parse_read_output_uses_sandbox_clock_and_splits_sections() -> None:+ stdout = (+ f"{MEMORY_WATCHDOG_NOW_PREFIX}1000\n"+ f"{MEMORY_WATCHDOG_STATE_SEPARATOR}\n"+ f"{json.dumps({'ts': 995.0, 'source': 'cgroup_v1', 'peak_current': 1, 'limit': 4})}\n"+ f"{MEMORY_WATCHDOG_EVENTS_SEPARATOR}\n"+ f"{json.dumps(KILL_RECORD)}\n"+ )++ summary = parse_memory_watchdog_read_output(stdout, fallback_now=5_000.0)++ assert summary.status == "alive"+ assert summary.source == "cgroup_v1"+ assert summary.kills == (+ MemoryWatchdogKill(+ pid=40,+ comm="bash",+ top_comm="vitest",+ tree_rss=5 * GIB,+ current=14 * GIB,+ limit=16 * GIB,+ signal="SIGTERM",+ ),+ )+++ "content, expected_missing",+ [(read_memory_watchdog_script(), False), (b"print('tampered')\n", True), (None, True)],+ ids=["current_script", "different_content", "absent"],+)+def test_probe_reports_missing_unless_the_file_matches_the_backend_script(+ tmp_path: Path, content: bytes | None, expected_missing: bool+) -> None:+ path = tmp_path / "posthog-memory-watchdog"+ if content is not None:+ path.write_bytes(content)+ path.chmod(0o755)+ command = build_memory_watchdog_probe_command().replace(MEMORY_WATCHDOG_PATH, str(path))++ stdout = subprocess.run(["bash", "-c", command], capture_output=True, text=True, check=False).stdout++ assert (MEMORY_WATCHDOG_MISSING_MARKER in stdout) is expected_missing+++def test_start_command_uses_a_fixed_environment_and_absolute_helpers() -> None:+ command = build_memory_watchdog_start_command()++ assert command.startswith("{ { { [ -r /sys/fs/cgroup/memory/memory.usage_in_bytes ]")+ assert "|| [ -r /proc/meminfo ]; } && [ -x " in command++ assert (+ "/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /usr/bin/setsid /usr/bin/nohup"+ in command+ )+ assert " setsid " not in command.replace("/usr/bin/setsid", "")+++def test_read_command_caps_what_it_pulls_out_of_the_sandbox(tmp_path: Path) -> None:+ state = tmp_path / "state.json"+ events = tmp_path / "events.jsonl"+ state.symlink_to("/dev/zero")+ events.write_text("".join(f'{{"event": "kill", "pid": {pid}}}\n' for pid in range(20_000)))+ command = (+ build_memory_watchdog_read_command()+ .replace(MEMORY_WATCHDOG_EVENTS_PATH, str(events))+ .replace(MEMORY_WATCHDOG_STATE_PATH, str(state))+ )++ result = subprocess.run(["bash", "-c", command], capture_output=True, check=False, timeout=10)++ assert result.returncode == 0+ assert len(result.stdout) < 300 * 1024+ assert result.stdout.rstrip().endswith(b'{"event": "kill", "pid": 19999}')diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex d3659580f8e5..07bc9780f839 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -54,6 +54,11 @@ from products.tasks.backend.logic.services.agent_server_launcher import ()from products.tasks.backend.logic.services.local_packages import LocalPackagefrom products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS+from products.tasks.backend.logic.services.memory_watchdog import (+ MEMORY_WATCHDOG_MISSING_MARKER,+ MEMORY_WATCHDOG_PATH,+ build_memory_watchdog_start_command,+)from products.tasks.backend.logic.services.modal_provision_diagnostics import (MAX_PROVISION_LOG_EXCERPT_LINES,summarize_modal_output,@@ -790,6 +795,56 @@ class TestModalSandboxAgentServer:assert "POSTHOG_TASK_RUN_EVENT_INGEST_URL=https://agent-proxy.example.com" in commandassert "POSTHOG_RTK=1" in command+ @pytest.mark.parametrize(+ "vm_runtime, sandbox_runtime, expected_env",+ [+ (True, None, "POSTHOG_SANDBOX_RUNTIME=vm"),+ (False, None, "POSTHOG_SANDBOX_RUNTIME=gvisor"),+ (False, "vm", "POSTHOG_SANDBOX_RUNTIME=vm"),+ ],+ ids=["vm_config", "gvisor_config", "explicit_runtime_wins_over_config"],+ )+ def test_start_agent_server_sandbox_runtime_env(+ self, mock_sandbox: Any, vm_runtime: bool, sandbox_runtime: str | None, expected_env: str+ ):+ mock_sandbox.config = SandboxConfig(name="test-sandbox", vm_runtime=vm_runtime)+ mock_sandbox.execute = MagicMock(+ return_value=ExecutionResult(stdout=_preflight_stdout(), stderr="", exit_code=0, error=None),+ )++ mock_sandbox.start_agent_server(+ repository=None, task_id="task-123", run_id="run-456", sandbox_runtime=sandbox_runtime+ )++ assert expected_env in _agent_server_launch_command(mock_sandbox.execute)++ @pytest.mark.parametrize(+ "enabled, preflight_extra, expect_install, expect_start",+ [+ (True, "", False, True),+ (True, MEMORY_WATCHDOG_MISSING_MARKER, True, True),+ (False, MEMORY_WATCHDOG_MISSING_MARKER, False, False),+ ],+ )+ def test_start_agent_server_memory_watchdog(+ self, mock_sandbox: Any, enabled: bool, preflight_extra: str, expect_install: bool, expect_start: bool+ ):+ mock_sandbox.execute = MagicMock(+ return_value=ExecutionResult(+ stdout=f"{_preflight_stdout()}\n{preflight_extra}", stderr="", exit_code=0, error=None+ ),+ )+ mock_sandbox.write_file = MagicMock(return_value=ExecutionResult(stdout="", stderr="", exit_code=0))++ with override_settings(TASKS_SANDBOX_MEMORY_WATCHDOG_ENABLED=enabled):+ mock_sandbox.start_agent_server(repository=None, task_id="task-123", run_id="run-456")++ written_paths = [call.args[0] for call in mock_sandbox.write_file.call_args_list]+ assert (MEMORY_WATCHDOG_PATH in written_paths) is expect_install+ assert (+ build_memory_watchdog_start_command() in _agent_server_launch_command(mock_sandbox.execute)+ ) is expect_start+@pytest.mark.parametrize("fast_mode, expected_env",[diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-baseindex 450a7476b7fe..719981cc76b9 100644--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base@@ -202,6 +202,8 @@ COPY products/tasks/backend/sandbox/images/hogli-shim.sh /opt/posthog/bin/hogliRUN chmod +x /opt/posthog/bin/hogliCOPY products/tasks/backend/sandbox/images/cpu_billing_sampler.py /usr/local/bin/posthog-cpu-billing-samplerRUN chmod +x /usr/local/bin/posthog-cpu-billing-sampler+COPY products/tasks/backend/sandbox/images/memory_watchdog.py /usr/local/bin/posthog-memory-watchdog+RUN chmod +x /usr/local/bin/posthog-memory-watchdogCOPY --from=agent-shadow-builder /agent-shadow /usr/local/bin/agent-shadowENV PATH="/opt/posthog/bin:${PATH}"diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vmindex d88c1456352a..bede0d2fd845 100644--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm@@ -23,6 +23,8 @@ RUN mkdir -p /etc/docker && \COPY products/tasks/backend/sandbox/images/cpu_billing_sampler.py /usr/local/bin/posthog-cpu-billing-samplerRUN chmod +x /usr/local/bin/posthog-cpu-billing-sampler+COPY products/tasks/backend/sandbox/images/memory_watchdog.py /usr/local/bin/posthog-memory-watchdog+RUN chmod +x /usr/local/bin/posthog-memory-watchdog# There is no init system in the sandbox, so dockerd is launched on demand by# this idempotent helper rather than by systemd. dockerd is detached with setsiddiff --git a/products/tasks/backend/sandbox/images/memory_watchdog.py b/products/tasks/backend/sandbox/images/memory_watchdog.pynew file mode 100644index 000000000000..32fd264af64b--- /dev/null+++ b/products/tasks/backend/sandbox/images/memory_watchdog.py@@ -0,0 +1,503 @@+#!/usr/bin/env python3++from __future__ import annotations++import os+import sys+import json+import time+import fcntl+import signal+from collections.abc import Iterable+from pathlib import Path+from typing import NamedTuple++CGROUP_V1_USAGE_PATH = Path("/sys/fs/cgroup/memory/memory.usage_in_bytes")+CGROUP_V1_LIMIT_PATH = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")+CGROUP_V2_CURRENT_PATH = Path("/sys/fs/cgroup/memory.current")+CGROUP_V2_MAX_PATH = Path("/sys/fs/cgroup/memory.max")+CGROUP_V1_STAT_PATH = Path("/sys/fs/cgroup/memory/memory.stat")+CGROUP_V2_STAT_PATH = Path("/sys/fs/cgroup/memory.stat")+MEMINFO_PATH = Path("/proc/meminfo")+PROC_PATH = Path("/proc")+AGENT_SERVER_PID_FILE = Path("/tmp/agent-server.pid")+CLI_PID_FILE = Path("/tmp/agent-cli.pid")+STATE_PATH = Path("/tmp/posthog-memory-watchdog.json")+EVENTS_PATH = Path("/tmp/posthog-memory-watchdog.jsonl")+LOCK_PATH = Path("/tmp/posthog-memory-watchdog.lock")++TRIGGER_RATIO = 0.85+PRESSURE_RATIO = 0.80+RECOVERED_RATIO = 0.70+MIN_VICTIM_RATIO = 0.01+DANGER_RATIO = 0.92+POLL_SECONDS = 0.25+TERM_GRACE_SECONDS = 2.0+QUIET_SECONDS = 10.0+NO_TARGET_INTERVAL_SECONDS = 60.0+UNLIMITED_BYTES = 1 << 60+CMDLINE_MAX_CHARS = 200+TOP_COUNT = 3+SHELL_COMMS = frozenset({"sh", "bash", "zsh", "dash"})+AGENT_SERVER_MARKER = "agent-server"+++class MemoryReading(NamedTuple):+ current: int+ limit: int+ source: str+++class ProcessStatus(NamedTuple):+ comm: str+ ppid: int+ rss: int+++class Process(NamedTuple):+ pid: int+ ppid: int+ comm: str+ rss: int+ cmdline: str+++class ProcessTree(NamedTuple):+ root: Process+ top: Process+ pids: tuple[int, ...]+ rss: int+++class Victim(NamedTuple):+ tree: ProcessTree+ candidate_count: int+++def should_trigger(current: int, limit: int, trigger_ratio: float) -> bool:+ return limit > 0 and current >= limit * trigger_ratio+++def _subtree(root: Process, children: dict[int, list[Process]]) -> list[Process]:+ members = [root]+ seen = {root.pid}+ index = 0+ while index < len(members):+ for child in children.get(members[index].pid, []):+ if child.pid not in seen:+ seen.add(child.pid)+ members.append(child)+ index += 1+ return members+++def _topmost_shells(root_pid: int, children: dict[int, list[Process]], protected: set[int]) -> list[Process]:+ shells: list[Process] = []+ pending = list(children.get(root_pid, []))+ seen: set[int] = {root_pid}+ while pending:+ process = pending.pop()+ if process.pid in seen:+ continue+ seen.add(process.pid)+ if process.comm in SHELL_COMMS and not any(member.pid in protected for member in _subtree(process, children)):+ shells.append(process)+ else:+ pending.extend(children.get(process.pid, []))+ return shells+++def _launch_chain(root: Process, children: dict[int, list[Process]]) -> set[int]:+ chain: set[int] = set()+ pending = [root]+ while pending:+ process = pending.pop()+ if process.pid in chain or AGENT_SERVER_MARKER not in process.cmdline:+ continue+ chain.add(process.pid)+ pending.extend(children.get(process.pid, []))+ return chain+++def candidate_trees(+ processes: Iterable[Process], cli_pids: Iterable[int], agent_server_pid: int | None, protected_pids: Iterable[int]+) -> list[ProcessTree]:+ by_pid = {process.pid: process for process in processes}+ children: dict[int, list[Process]] = {}+ for process in by_pid.values():+ children.setdefault(process.ppid, []).append(process)+ live_cli_pids = list(dict.fromkeys(pid for pid in cli_pids if pid in by_pid))+ protected = {pid for pid in (*protected_pids, *live_cli_pids, agent_server_pid) if pid is not None}+ if live_cli_pids:+ roots = [child for pid in live_cli_pids for child in children.get(pid, []) if child.comm in SHELL_COMMS]+ elif agent_server_pid is not None and agent_server_pid in by_pid:+ protected.update(_launch_chain(by_pid[agent_server_pid], children))+ roots = _topmost_shells(agent_server_pid, children, protected)+ else:+ roots = []+ trees: list[ProcessTree] = []+ for root in roots:+ members = _subtree(root, children)+ if any(member.pid in protected for member in members):+ continue+ trees.append(+ ProcessTree(+ root=root,+ top=max(members, key=lambda member: member.rss),+ pids=tuple(member.pid for member in reversed(members)),+ rss=sum(member.rss for member in members),+ )+ )+ trees.sort(key=lambda tree: tree.rss, reverse=True)+ return trees+++def choose_victim(+ processes: Iterable[Process],+ cli_pids: Iterable[int],+ agent_server_pid: int | None,+ protected_pids: Iterable[int],+ current: int,+ limit: int,+) -> Victim | None:+ trees = candidate_trees(processes, cli_pids, agent_server_pid, protected_pids)+ if not trees:+ return None+ needed = 0.0 if current >= limit * DANGER_RATIO else current - limit * TRIGGER_RATIO+ if trees[0].rss < max(limit * MIN_VICTIM_RATIO, needed):+ return None+ return Victim(tree=trees[0], candidate_count=len(trees))+++def _read_int(path: Path) -> int | None:+ try:+ return int(path.read_text().strip())+ except (OSError, ValueError):+ return None+++def _read_meminfo() -> MemoryReading | None:+ values: dict[str, int] = {}+ try:+ for line in MEMINFO_PATH.read_text().splitlines():+ key, _, rest = line.partition(":")+ parts = rest.split()+ if key in ("MemTotal", "MemAvailable") and parts:+ values[key] = int(parts[0]) * 1024+ except (OSError, ValueError):+ return None+ total = values.get("MemTotal")+ available = values.get("MemAvailable")+ if not total or available is None:+ return None+ return MemoryReading(current=total - available, limit=total, source="meminfo")+++def _read_stat_value(path: Path, key: str) -> int | None:+ try:+ lines = path.read_text().splitlines()+ except OSError:+ return None+ for line in lines:+ parts = line.split()+ if len(parts) == 2 and parts[0] == key:+ try:+ return int(parts[1])+ except ValueError:+ return None+ return None+++def read_memory() -> MemoryReading | None:+ for current_path, limit_path, stat_path, stat_key, source in (+ (CGROUP_V1_USAGE_PATH, CGROUP_V1_LIMIT_PATH, CGROUP_V1_STAT_PATH, "total_inactive_file", "cgroup_v1"),+ (CGROUP_V2_CURRENT_PATH, CGROUP_V2_MAX_PATH, CGROUP_V2_STAT_PATH, "inactive_file", "cgroup_v2"),+ ):+ current = _read_int(current_path)+ limit = _read_int(limit_path)+ if current is not None and limit is not None and 0 < limit < UNLIMITED_BYTES:+ inactive_file = _read_stat_value(stat_path, stat_key)+ if inactive_file is not None and 0 <= inactive_file < current:+ current -= inactive_file+ return MemoryReading(current=current, limit=limit, source=source)+ return _read_meminfo()+++def _status_fields(pid: int) -> ProcessStatus | None:+ comm = ""+ ppid = -1+ rss = 0+ try:+ for line in (PROC_PATH / str(pid) / "status").read_text().splitlines():+ key, _, value = line.partition(":")+ if key == "Name":+ comm = value.strip()+ elif key == "PPid":+ ppid = int(value)+ elif key == "VmRSS":+ rss = int(value.split()[0]) * 1024+ except (OSError, ValueError, IndexError):+ return None+ return ProcessStatus(comm=comm, ppid=ppid, rss=rss)+++def _read_cmdline(pid: int) -> str:+ try:+ raw = (PROC_PATH / str(pid) / "cmdline").read_bytes()+ except OSError:+ return ""+ return raw.replace(b"\0", b" ").decode(errors="replace").strip()+++def list_processes() -> list[Process]:+ processes: list[Process] = []+ for entry in os.listdir(PROC_PATH):+ if not entry.isdigit():+ continue+ pid = int(entry)+ fields = _status_fields(pid)+ if fields is None:+ continue+ processes.append(+ Process(pid=pid, ppid=fields.ppid, comm=fields.comm, rss=fields.rss, cmdline=_read_cmdline(pid))+ )+ return processes+++def read_pid(path: Path) -> int | None:+ pid = _read_int(path)+ return pid if pid is not None and pid > 0 else None+++def read_pids(path: Path) -> tuple[int, ...]:+ try:+ lines = path.read_text().splitlines()+ except OSError:+ return ()+ pids: list[int] = []+ for line in lines:+ try:+ pid = int(line.strip())+ except ValueError:+ continue+ if pid > 0:+ pids.append(pid)+ return tuple(pids)+++def self_rss() -> int:+ fields = _status_fields(os.getpid())+ return fields.rss if fields else 0+++def signal_pids(pids: Iterable[int], sig: signal.Signals) -> None:+ for pid in pids:+ try:+ os.kill(pid, sig)+ except OSError:+ pass+++def _is_running(pid: int) -> bool:+ try:+ stat = (PROC_PATH / str(pid) / "stat").read_text()+ except OSError:+ return False+ state = stat.rpartition(")")[2].split()+ return bool(state) and state[0] not in ("Z", "X")+++def _start_time(pid: int) -> int | None:+ try:+ stat = (PROC_PATH / str(pid) / "stat").read_text()+ except OSError:+ return None+ fields = stat.rpartition(")")[2].split()+ try:+ return int(fields[19])+ except (IndexError, ValueError):+ return None+++def _alive_matching(identities: dict[int, int]) -> tuple[int, ...]:+ return tuple(pid for pid, start in identities.items() if _is_running(pid) and _start_time(pid) == start)+++def _tree_summary(tree: ProcessTree) -> dict[str, object]:+ return {"pid": tree.root.pid, "comm": tree.root.comm, "top_comm": tree.top.comm, "rss": tree.rss}+++class Watchdog:+ def __init__(self, reading: MemoryReading) -> None:+ self.reading = reading+ self.peak_current = reading.current+ self.kills = 0+ self.no_target_episodes = 0+ self.pressure_episodes = 0+ self.episode_started_at: float | None = None+ self.quiet_until = 0.0+ self.last_no_target_at = 0.0+ self.protected_pids = frozenset({os.getpid(), 1})++ def emit(self, event: str, **fields: object) -> None:+ record = {+ "event": event,+ "ts": time.time(),+ "current": self.reading.current,+ "limit": self.reading.limit,+ **fields,+ }+ with EVENTS_PATH.open("a") as events:+ events.write(json.dumps(record) + "\n")++ def write_state(self) -> None:+ state = {+ "ts": time.time(),+ "current": self.reading.current,+ "limit": self.reading.limit,+ "source": self.reading.source,+ "peak_current": self.peak_current,+ "kills": self.kills,+ "no_target_episodes": self.no_target_episodes,+ "pressure_episodes": self.pressure_episodes,+ "pid": os.getpid(),+ "self_rss": self_rss(),+ }+ temporary_path = STATE_PATH.with_suffix(".tmp")+ temporary_path.write_text(json.dumps(state))+ os.replace(temporary_path, STATE_PATH)++ def started(self) -> None:+ self.emit(+ "watchdog_started",+ source=self.reading.source,+ trigger_ratio=TRIGGER_RATIO,+ pressure_ratio=PRESSURE_RATIO,+ recovered_ratio=RECOVERED_RATIO,+ agent_server_pid=read_pid(AGENT_SERVER_PID_FILE),+ cli_pid_file_found=CLI_PID_FILE.exists(),+ )++ def update_episode(self, now: float) -> None:+ ratio = self.reading.current / self.reading.limit+ if self.episode_started_at is None and ratio >= PRESSURE_RATIO:+ self.episode_started_at = now+ self.pressure_episodes += 1+ trees = candidate_trees(+ list_processes(), read_pids(CLI_PID_FILE), read_pid(AGENT_SERVER_PID_FILE), self.protected_pids+ )+ self.emit("pressure", candidates=[_tree_summary(tree) for tree in trees[:TOP_COUNT]])+ elif self.episode_started_at is not None and ratio < RECOVERED_RATIO:+ self.emit("recovered", duration_seconds=round(now - self.episode_started_at, 3))+ self.episode_started_at = None++ def observe(self) -> MemoryReading | None:+ reading = read_memory()+ if reading is not None:+ self.peak_current = max(self.peak_current, reading.current)+ return reading++ def wait_for_release(self, identities: dict[int, int]) -> None:+ deadline = time.monotonic() + TERM_GRACE_SECONDS+ while time.monotonic() < deadline and _alive_matching(identities):+ time.sleep(POLL_SECONDS)+ reading = self.observe()+ if reading is not None and not should_trigger(reading.current, reading.limit, TRIGGER_RATIO):+ return++ def wait_below_trigger(self) -> bool:+ deadline = time.monotonic() + TERM_GRACE_SECONDS+ while True:+ reading = self.observe()+ if reading is not None and not should_trigger(reading.current, reading.limit, TRIGGER_RATIO):+ return True+ if time.monotonic() >= deadline:+ return False+ time.sleep(POLL_SECONDS)++ def enforce(self, now: float) -> None:+ processes = list_processes()+ victim = choose_victim(+ processes,+ read_pids(CLI_PID_FILE),+ read_pid(AGENT_SERVER_PID_FILE),+ self.protected_pids,+ self.reading.current,+ self.reading.limit,+ )+ if victim is None:+ if now - self.last_no_target_at >= NO_TARGET_INTERVAL_SECONDS:+ self.last_no_target_at = now+ self.no_target_episodes += 1+ top = sorted(processes, key=lambda process: process.rss, reverse=True)[:TOP_COUNT]+ self.emit("no_target", top=[{"pid": p.pid, "comm": p.comm, "rss": p.rss} for p in top])+ return+ triggered = self.reading+ tree = victim.tree+ identities = {pid: start for pid in tree.pids if (start := _start_time(pid)) is not None}+ signal_pids(identities, signal.SIGTERM)+ final_signal = signal.SIGTERM+ self.wait_for_release(identities)+ reading = self.observe()+ remaining = _alive_matching(identities)+ if reading is not None and should_trigger(reading.current, reading.limit, TRIGGER_RATIO) and remaining:+ signal_pids(remaining, signal.SIGKILL)+ final_signal = signal.SIGKILL+ released = self.wait_below_trigger()+ self.kills += 1+ if released:+ self.quiet_until = time.monotonic() + QUIET_SECONDS+ self.reading = triggered+ self.emit(+ "kill",+ pid=tree.root.pid,+ comm=tree.root.comm,+ top_comm=tree.top.comm,+ top_pid=tree.top.pid,+ cmdline=tree.root.cmdline[:CMDLINE_MAX_CHARS],+ tree_rss=tree.rss,+ signal=final_signal.name,+ candidate_count=victim.candidate_count,+ released=released,+ )++ def tick(self) -> None:+ reading = read_memory()+ if reading is None:+ return+ self.reading = reading+ self.peak_current = max(self.peak_current, reading.current)+ now = time.time()+ self.update_episode(now)+ if time.monotonic() >= self.quiet_until and should_trigger(reading.current, reading.limit, TRIGGER_RATIO):+ self.enforce(now)+ self.write_state()++ def run(self) -> None:+ self.started()+ while True:+ try:+ self.tick()+ except OSError:+ pass+ time.sleep(POLL_SECONDS)+++def main() -> int:+ lock = LOCK_PATH.open("w")+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError:+ return 0+ reading = read_memory()+ if reading is None:+ sys.stderr.write("no readable memory source: cgroup v1, cgroup v2 and /proc/meminfo all unavailable\n")+ return 1+ STATE_PATH.unlink(missing_ok=True)+ EVENTS_PATH.unlink(missing_ok=True)+ Watchdog(reading).run()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.pyindex 4083ffed8df0..af0d82062d9b 100644--- a/products/tasks/backend/temporal/metrics.py+++ b/products/tasks/backend/temporal/metrics.py@@ -121,6 +121,9 @@ TASKS_RUN_TURNS_HISTOGRAM_BUCKETS = [256.0,]+TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_METRICS = ("tasks_sandbox_memory_peak_ratio",)+TASKS_MEMORY_PEAK_RATIO_HISTOGRAM_BUCKETS = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0]+_RUN_TOKEN_KINDS = {"input": "input_tokens","output": "output_tokens",@@ -345,6 +348,38 @@ def increment_sandbox_wedge_probe(verdict: str, write_stage: str) -> None:pass+def increment_memory_watchdog_events(event: str, count: int) -> None:+ if count <= 0:+ return+ try:+ _metric_meter({"event": event}).create_counter(+ "tasks_sandbox_memory_watchdog_events",+ "Sandbox memory watchdog events read at teardown",+ ).add(count)+ except Exception:+ pass+++def increment_memory_watchdog_teardown(status: str) -> None:+ try:+ _metric_meter({"status": status}).create_counter(+ "tasks_sandbox_memory_watchdog_teardown",+ "Sandbox memory watchdog heartbeat status at teardown",+ ).add(1)+ except Exception:+ pass+++def record_memory_peak_ratio(ratio: float) -> None:+ try:+ _metric_meter().create_histogram_float(+ "tasks_sandbox_memory_peak_ratio",+ "Peak sandbox memory use as a fraction of the limit, read at teardown",+ ).record(ratio)+ except Exception:+ pass++def increment_tool_call_only_heartbeat() -> None:try:_metric_meter().create_counter(diff --git a/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py b/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.pyindex 1af43873efd1..9bc88b61c5d5 100644--- a/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py+++ b/products/tasks/backend/temporal/process_task/activities/read_sandbox_logs.py@@ -1,4 +1,5 @@import json+import timeimport loggingfrom dataclasses import dataclass@@ -7,7 +8,16 @@ from temporalio import activityfrom posthog.temporal.common.utils import asyncifyfrom products.tasks.backend.exceptions import SandboxNotRunningError-from products.tasks.backend.logic.services.sandbox import get_sandbox_class_for_sandbox_id+from products.tasks.backend.logic.services.memory_watchdog import (+ build_memory_watchdog_read_command,+ parse_memory_watchdog_read_output,+)+from products.tasks.backend.logic.services.sandbox import SandboxBase, get_sandbox_class_for_sandbox_id+from products.tasks.backend.temporal.metrics import (+ increment_memory_watchdog_events,+ increment_memory_watchdog_teardown,+ record_memory_peak_ratio,+)from products.tasks.backend.temporal.observability import log_activity_executionlogger = logging.getLogger(__name__)@@ -24,6 +34,22 @@ class ReadSandboxLogsInput:SANDBOX_TERMINATED_MESSAGE = "Sandbox terminated before logs could be captured; no agent-server logs available."+def _report_memory_watchdog(sandbox: SandboxBase, sandbox_id: str, run_id: str | None) -> None:+ result = sandbox.execute(build_memory_watchdog_read_command(), timeout_seconds=10)+ summary = parse_memory_watchdog_read_output(result.stdout, time.time())+ logger.info(+ f"Sandbox memory watchdog summary run_id={run_id} sandbox_id={sandbox_id} kills={summary.kill_count} "+ f"no_target={summary.no_target} pressure_episodes={summary.pressure_episodes} "+ f"peak_ratio={summary.peak_ratio} alive={summary.alive} source={summary.source}"+ )+ increment_memory_watchdog_teardown(summary.status)+ increment_memory_watchdog_events("kill", summary.kill_count)+ increment_memory_watchdog_events("no_target", summary.no_target)+ increment_memory_watchdog_events("pressure", summary.pressure_episodes)+ if summary.peak_ratio is not None:+ record_memory_peak_ratio(summary.peak_ratio)++@activity.defn@asyncifydef read_sandbox_logs(input: ReadSandboxLogsInput) -> str:@@ -81,6 +107,11 @@ def read_sandbox_logs(input: ReadSandboxLogsInput) -> str:except Exception:logger.debug("agentsh audit query failed for sandbox %s", input.sandbox_id, exc_info=True)+ try:+ _report_memory_watchdog(sandbox, input.sandbox_id, input.run_id)+ except Exception:+ logger.warning("Memory watchdog summary failed for sandbox %s", input.sandbox_id, exc_info=True)+return logsexcept SandboxNotRunningError:logger.info(f"Sandbox {input.sandbox_id} terminated mid-capture; no logs available")diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.pyindex 5095f9d48fc8..bc724ff3865d 100644--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py@@ -28,11 +28,11 @@ from .get_task_processing_context import TaskProcessingContextlogger = get_logger(__name__)_SANDBOX_WEDGE_PROBE_COMMAND = """-printf 'memory_current='; cat /sys/fs/cgroup/memory.current 2>/dev/null || printf 'unavailable\n'-printf 'memory_max='; cat /sys/fs/cgroup/memory.max 2>/dev/null || printf 'unavailable\n'-printf 'oom_kill='; awk '$1 == "oom_kill" { print $2 }' /sys/fs/cgroup/memory.events 2>/dev/null || printf 'unavailable\n'-printf 'pids_current='; cat /sys/fs/cgroup/pids.current 2>/dev/null || printf 'unavailable\n'-printf 'pids_max='; cat /sys/fs/cgroup/pids.max 2>/dev/null || printf 'unavailable\n'+printf 'memory_current='; cat /sys/fs/cgroup/memory.current 2>/dev/null || cat /sys/fs/cgroup/memory/memory.usage_in_bytes 2>/dev/null || printf 'unavailable\n'+printf 'memory_max='; cat /sys/fs/cgroup/memory.max 2>/dev/null || cat /sys/fs/cgroup/memory/memory.limit_in_bytes 2>/dev/null || printf 'unavailable\n'+printf 'oom_kill='; awk '$1 == "oom_kill" { print $2 }' /sys/fs/cgroup/memory.events 2>/dev/null || awk '$1 == "oom_kill" { print $2 }' /sys/fs/cgroup/memory/memory.oom_control 2>/dev/null || printf 'unavailable\n'+printf 'pids_current='; cat /sys/fs/cgroup/pids.current 2>/dev/null || cat /sys/fs/cgroup/pids/pids.current 2>/dev/null || printf 'unavailable\n'+printf 'pids_max='; cat /sys/fs/cgroup/pids.max 2>/dev/null || cat /sys/fs/cgroup/pids/pids.max 2>/dev/null || printf 'unavailable\n'printf 'tmp_available_kb='; df -Pk /tmp 2>/dev/null | awk 'NR == 2 { print $4 }'""".strip()diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 3802d2da6087..937b5db95ad8 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -36,6 +36,7 @@ from products.tasks.backend.logic.services.connection_token import (create_sandbox_event_ingest_token,)from products.tasks.backend.logic.services.launch_preparation_metrics import launch_preparation_metric_context+from products.tasks.backend.logic.services.modal_sandbox import ModalSandboxfrom products.tasks.backend.logic.services.sandbox import (REPO_READY_FILE,SNAPSHOT_KIND_DIRECTORY,@@ -634,6 +635,9 @@ def _invoke_start_agent_server(claude_model_access=ctx.model_access.access_for("claude"),codex_model_access=ctx.model_access.access_for("codex"),codex_run_token=params.codex_run_token,+ sandbox_runtime=sandbox_runtime_label(ctx.use_modal_vm_sandbox)+ if isinstance(sandbox, ModalSandbox)+ else None,)return health_duration_ms if isinstance(health_duration_ms, int) else Nonediff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.pyindex 6426e0a457c6..c0be06fcca57 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py@@ -1,5 +1,7 @@import uuid+import subprocessimport dataclasses+from pathlib import Pathimport pytestfrom unittest.mock import MagicMock, patch@@ -20,6 +22,7 @@ from products.tasks.backend.logic.services.modal_sandbox import ModalSandboxfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, SandboxConfigfrom products.tasks.backend.models import TASK_OWNERSHIP_VERSION_STATE_KEY, Task, TaskRunfrom products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials import (+ _SANDBOX_WEDGE_PROBE_COMMAND,RefreshSandboxCredentialsInput,_sandbox_wedge_verdict,refresh_sandbox_credentials,@@ -500,3 +503,54 @@ class TestRefreshSandboxCredentialsActivity:)def test_sandbox_wedge_verdict(probe, expected):assert _sandbox_wedge_verdict(probe) == expected+++ "files,expected",+ [+ (+ {+ "memory/memory.usage_in_bytes": "1024",+ "memory/memory.limit_in_bytes": "4096",+ "memory/memory.oom_control": "oom_kill_disable 0\nunder_oom 0\noom_kill 3",+ "pids/pids.current": "7",+ "pids/pids.max": "100",+ },+ {"memory_current": "1024", "memory_max": "4096", "oom_kill": "3", "pids_current": "7", "pids_max": "100"},+ ),+ (+ {+ "memory.current": "2048",+ "memory.max": "8192",+ "memory.events": "oom 1\noom_kill 2",+ "pids.current": "5",+ "pids.max": "50",+ "memory/memory.usage_in_bytes": "1",+ },+ {"memory_current": "2048", "memory_max": "8192", "oom_kill": "2", "pids_current": "5", "pids_max": "50"},+ ),+ (+ {},+ {+ "memory_current": "unavailable",+ "memory_max": "unavailable",+ "oom_kill": "unavailable",+ "pids_current": "unavailable",+ "pids_max": "unavailable",+ },+ ),+ ],+ ids=["cgroup_v1", "cgroup_v2_wins", "no_cgroup_files"],+)+def test_sandbox_wedge_probe_reads_cgroup_v1_when_v2_is_absent(+ tmp_path: Path, files: dict[str, str], expected: dict[str, str]+) -> None:+ for relative_path, content in files.items():+ (tmp_path / relative_path).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / relative_path).write_text(f"{content}\n")+ command = _SANDBOX_WEDGE_PROBE_COMMAND.replace("/sys/fs/cgroup", str(tmp_path))++ stdout = subprocess.run(["bash", "-c", command], capture_output=True, text=True, check=False).stdout++ probe = dict(line.split("=", 1) for line in stdout.splitlines() if "=" in line)+ assert {key: probe[key] for key in expected} == expecteddiff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex b0a0af3c1ce5..bcdb66235f3b 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -16,6 +16,7 @@ from products.tasks.backend.exceptions import (SandboxTimeoutError,)from products.tasks.backend.logic.services.launch_preparation_metrics import record_launch_preparation_ms+from products.tasks.backend.logic.services.modal_sandbox import ModalSandboxfrom products.tasks.backend.logic.services.sandbox import ExecutionResult, sandbox_repo_pathfrom products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContextfrom products.tasks.backend.temporal.process_task.activities.start_agent_server import (@@ -307,6 +308,27 @@ def test_invoke_start_agent_server_skips_log_tails_when_rate_limited(mocker) ->emit_agent_server.assert_not_called()+ "is_modal, use_modal_vm_sandbox, expected_runtime",+ [(True, True, "vm"), (True, False, "gvisor"), (False, True, None)],+ ids=["modal_vm", "modal_gvisor", "non_modal"],+)+def test_invoke_start_agent_server_forwards_sandbox_runtime(+ mocker, is_modal: bool, use_modal_vm_sandbox: bool, expected_runtime: str | None+) -> None:+ sandbox = mocker.Mock(spec=ModalSandbox, id="sandbox-id") if is_modal else mocker.Mock(id="sandbox-id")+ sandbox.start_agent_server.return_value = None++ _invoke_start_agent_server(+ sandbox,+ _context(use_modal_vm_sandbox=use_modal_vm_sandbox),+ mocker.Mock(agentsh_domains=None),+ repo_ready_file=None,+ )++ assert sandbox.start_agent_server.call_args.kwargs["sandbox_runtime"] == expected_runtime++@pytest.mark.parametrize(("error", "expected_statuses"),[diff --git a/products/tasks/backend/temporal/process_task/tests/test_read_sandbox_logs.py b/products/tasks/backend/temporal/process_task/tests/test_read_sandbox_logs.pyindex 1e6cde2bc011..bbd0133ace79 100644--- a/products/tasks/backend/temporal/process_task/tests/test_read_sandbox_logs.py+++ b/products/tasks/backend/temporal/process_task/tests/test_read_sandbox_logs.py@@ -1,6 +1,14 @@+import json+from unittest.mock import MagicMock, patchfrom products.tasks.backend.exceptions import SandboxNotRunningError+from products.tasks.backend.logic.services.memory_watchdog import (+ MEMORY_WATCHDOG_EVENTS_SEPARATOR,+ MEMORY_WATCHDOG_NOW_PREFIX,+ MEMORY_WATCHDOG_STATE_SEPARATOR,+ build_memory_watchdog_read_command,+)from products.tasks.backend.temporal.process_task.activities.read_sandbox_logs import (SANDBOX_TERMINATED_MESSAGE,ReadSandboxLogsInput,@@ -50,3 +58,30 @@ def test_returns_terminated_message_on_mid_capture_termination():result = _run("sb-race")assert result == SANDBOX_TERMINATED_MESSAGE+++def test_reports_memory_watchdog_kills_to_metrics():+ gib = 1024**3+ watchdog_output = (+ f"{MEMORY_WATCHDOG_NOW_PREFIX}100\n{MEMORY_WATCHDOG_STATE_SEPARATOR}\n"+ f"{json.dumps({'ts': 99.0, 'source': 'cgroup_v1', 'peak_current': 15 * gib, 'limit': 16 * gib, 'kills': 3})}\n"+ f"{MEMORY_WATCHDOG_EVENTS_SEPARATOR}\n"+ f"{json.dumps({'event': 'kill', 'comm': 'bash', 'top_comm': 'vitest', 'tree_rss': 13 * gib, 'current': 14 * gib, 'limit': 16 * gib, 'signal': 'SIGTERM'})}\n"+ )+ sandbox = MagicMock()+ sandbox.is_running.return_value = True+ sandbox.execute.side_effect = lambda command, **_: MagicMock(+ stdout=watchdog_output if command == build_memory_watchdog_read_command() else ""+ )+ module = "products.tasks.backend.temporal.process_task.activities.read_sandbox_logs"++ with (+ patch(_SANDBOX_PATH) as mock_sandbox_cls,+ patch(f"{module}.increment_memory_watchdog_teardown") as increment_teardown,+ patch(f"{module}.increment_memory_watchdog_events") as increment_events,+ ):+ mock_sandbox_cls.return_value.get_by_id.return_value = sandbox+ _run("sb-running", run_id="run-1")++ increment_teardown.assert_called_once_with("alive")+ increment_events.assert_any_call("kill", 3)