Skip to content

: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.

feat(tasks): signals harness prerequisites (1/7) (#57755)

Andrew Maguiree53a3a1a858a
diff --git a/products/tasks/backend/services/agentsh.py b/products/tasks/backend/services/agentsh.py
index fa157b3bb1fb..020853f1d271 100644
--- a/products/tasks/backend/services/agentsh.py
+++ b/products/tasks/backend/services/agentsh.py
@@ -18,28 +18,76 @@ INFRASTRUCTURE_DOMAINS = [
]
+# Any failure parsing a `SANDBOX_*_URL` value (malformed scheme, non-string,
+# bad port like `http://host:abc` / `:99999`) should degrade silently to "no
+# host/port added" rather than crash `generate_policy_yaml` and block sandbox
+# boot. A typo in `.env` shouldn't be a hard failure.
def _hostname_from_url(url: str | None) -> str | None:
if not url:
return None
- parsed = urlparse(url)
- return parsed.hostname
-
+ try:
+ return urlparse(url).hostname
+ except (ValueError, AttributeError):
+ return None
-def _get_infrastructure_domains() -> list[str]:
- domains = list(INFRASTRUCTURE_DOMAINS)
- for candidate in [
- getattr(settings, "SANDBOX_API_URL", None),
- getattr(settings, "SANDBOX_LLM_GATEWAY_URL", None),
- ]:
- hostname = _hostname_from_url(candidate)
+def _port_from_url(url: str | None) -> int | None:
+ if not url:
+ return None
+ try:
+ parsed = urlparse(url)
+ port = parsed.port
+ except (ValueError, AttributeError):
+ return None
+ if port is not None:
+ return port
+ if parsed.scheme == "https":
+ return 443
+ if parsed.scheme == "http":
+ return 80
+ return None
+
+
+# Sandbox-host URLs in `.env` for local dev. Their hostnames and (non-standard)
+# ports feed the DEBUG-only network rule below — e.g. llm-gateway on 3308, MCP
+# wrangler on 8787 — so locally-hosted services pass the agentsh syscall-layer
+# firewall. These settings are only read into the DEBUG rule; in prod they have
+# no effect even if defined.
+_DEBUG_SANDBOX_URL_SETTINGS = (
+ "SANDBOX_API_URL",
+ "SANDBOX_LLM_GATEWAY_URL",
+ "SANDBOX_MCP_URL",
+)
+
+
+def _get_debug_only_domains() -> list[str]:
+ """Hostnames added ONLY when DEBUG is on: dev loopback aliases plus any
+ sandbox URL hosts parsed from `SANDBOX_*_URL` settings. Kept separate from
+ the prod-safe `INFRASTRUCTURE_DOMAINS` set so a stray dev hostname can't
+ accidentally widen prod's allowlist.
+ """
+ domains: list[str] = ["localhost", "host.docker.internal"]
+ for setting_name in _DEBUG_SANDBOX_URL_SETTINGS:
+ hostname = _hostname_from_url(getattr(settings, setting_name, None))
if hostname and hostname not in domains:
domains.append(hostname)
-
return domains
-LOCAL_DEV_DOMAINS = ["localhost", "host.docker.internal"]
+def _get_debug_only_ports() -> list[int]:
+ """Ports added ONLY when DEBUG is on. The prod-safe set is
+ `[443, 80, 22]` (cloud routing only); in DEBUG we additionally expose
+ Django (8000) and Caddy (8010), plus any non-standard ports parsed from
+ `SANDBOX_*_URL` (e.g. llm-gateway 3308, MCP wrangler 8787). Without this,
+ locally-hosted services on custom ports are denied at the agentsh
+ syscall layer even when their hostname is allowed.
+ """
+ ports: list[int] = [8000, 8010]
+ for setting_name in _DEBUG_SANDBOX_URL_SETTINGS:
+ port = _port_from_url(getattr(settings, setting_name, None))
+ if port is not None and port not in ports:
+ ports.append(port)
+ return ports
def generate_env_wrapper() -> str:
@@ -142,14 +190,10 @@ def generate_policy_yaml(allowed_domains: list[str] | None = None) -> str:
is allowed (audit-only mode).
"""
if allowed_domains is not None:
- merged_domains = list(allowed_domains)
- for domain in _get_infrastructure_domains():
- if domain not in merged_domains:
- merged_domains.append(domain)
-
- allowed_ports = [443, 80, 22]
- if getattr(settings, "DEBUG", False):
- allowed_ports.extend([8000, 8010])
+ prod_domains = list(allowed_domains)
+ for domain in INFRASTRUCTURE_DOMAINS:
+ if domain not in prod_domains:
+ prod_domains.append(domain)
network_rules: list[dict] = [
{
@@ -162,31 +206,34 @@ def generate_policy_yaml(allowed_domains: list[str] | None = None) -> str:
"cidrs": ["169.254.169.254/32", "fd00:ec2::254/128"],
"decision": "deny",
},
+ # Prod-safe allow rule: only the caller-provided domains plus our
+ # baked-in infrastructure domains, and only the cloud-routing ports
+ # (443, 80, 22). This rule is identical in every environment.
+ {
+ "name": "allow-domains",
+ "domains": prod_domains,
+ "ports": [443, 80, 22],
+ "decision": "allow",
+ },
]
-
+ # DEBUG-only additions live in their own rule so a stray dev hostname
+ # or port can't widen the prod allowlist by accident. Append after the
+ # prod rule, before default-deny.
if getattr(settings, "DEBUG", False):
network_rules.append(
{
- "name": "allow-local-dev-hosts",
- "domains": LOCAL_DEV_DOMAINS,
+ "name": "allow-debug-domains",
+ "domains": _get_debug_only_domains(),
+ "ports": _get_debug_only_ports(),
"decision": "allow",
}
)
-
- network_rules.extend(
- [
- {
- "name": "allow-domains",
- "domains": merged_domains,
- "ports": allowed_ports,
- "decision": "allow",
- },
- {
- "name": "default-deny-network",
- "domains": ["*"],
- "decision": "deny",
- },
- ]
+ network_rules.append(
+ {
+ "name": "default-deny-network",
+ "domains": ["*"],
+ "decision": "deny",
+ }
)
else:
network_rules = [
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.py
index 550a2f39f1f6..d93650bcec0b 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/services/custom_prompt_internals.py
@@ -106,6 +106,10 @@ async def poll_for_turn(
last_new_lines_at = 0
# Remember assistant text, as the agent message and end_message could arrive in different poll slices
latest_assistant_text: str | None = None
+ # Cursor at start of this turn — passed to _drain_final_log so the terminal-status drain can
+ # recover an agent_message emitted earlier in *this* turn without crossing the previous turn's
+ # boundary (which would return a stale previous-turn response in multi-turn sessions).
+ original_skip_lines = skip_lines
while elapsed < MAX_POLL_SECONDS:
await asyncio.sleep(POLL_INTERVAL_SECONDS)
elapsed += POLL_INTERVAL_SECONDS
@@ -195,8 +199,8 @@ async def poll_for_turn(
task_run,
refreshed_status=refreshed.status,
error_message=refreshed.error_message,
- skip_lines=skip_lines,
printed_lines=printed_lines,
+ original_skip_lines=original_skip_lines,
verbose=verbose,
output_fn=output_fn,
)
@@ -208,18 +212,25 @@ async def _drain_final_log(
*,
refreshed_status: str,
error_message: str | None = None,
- skip_lines: int,
printed_lines: int,
+ original_skip_lines: int,
verbose: bool,
output_fn: OutputFn,
) -> tuple[str, str | None, int, int]:
"""
Drain one last S3 read after the TaskRun hit a terminal status. S3 may not have flushed the final agent_message
before Temporal marked the run done, so we retry the read. Raises RuntimeError if no message is recoverable.
+
+ Re-parses from the start-of-turn cursor (`original_skip_lines`) rather than only the slice past the *last* poll
+ cursor: when the agent emits text mid-run but never reaches `end_turn` (e.g. killed by inactivity timeout
+ mid-tool-call), the agent_message landed in an earlier poll slice and the per-poll cursor has advanced past
+ it. Scanning from start-of-turn recovers it without crossing into the previous turn (which would return a
+ stale earlier-turn response in multi-turn sessions). For single-turn callers `original_skip_lines == 0`, so
+ the scan covers the full log as before. The walk is idempotent and only runs once at terminal status.
"""
final_message = None
final_log = None
- final_lines = skip_lines
+ final_lines = 0
final_empty_end_turn = False
for attempt in range(MAX_CONSECUTIVE_STORAGE_ERRORS):
try:
@@ -227,7 +238,7 @@ async def _drain_final_log(
# thread_sensitive=False because of pure I/O (object_storage.read + JSON parsing) and doesn't touch the ORM
_check_logs,
thread_sensitive=False,
- )(task_run, skip_lines)
+ )(task_run, skip_lines=original_skip_lines)
break
except ObjectStorageError:
logger.warning(
diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.py
index 66009807cde7..30d0d62b77e2 100644
--- a/products/tasks/backend/services/docker_sandbox.py
+++ b/products/tasks/backend/services/docker_sandbox.py
@@ -660,7 +660,14 @@ class DockerSandbox(SandboxBase):
f"{create_pr_flag}{branch_flag}{mcp_servers_arg}{domains_flag}"
)
- inner = f"cd /scripts && {server_cmd} > /tmp/agent-server.log 2>&1"
+ # agentsh injects HTTP_PROXY pointing at a per-session egress proxy port; undici
+ # (Node fetch) honors it for local-host traffic unless NO_PROXY says otherwise. The
+ # per-session port can go stale and cause ECONNREFUSED on otherwise-valid local URLs,
+ # so route host.docker.internal traffic (llm-gateway, MCP) around the proxy.
+ no_proxy_export = (
+ 'export NO_PROXY="host.docker.internal,${NO_PROXY:-localhost,127.0.0.1}"; export no_proxy="$NO_PROXY"; '
+ )
+ inner = f"cd /scripts && {no_proxy_export}{server_cmd} > /tmp/agent-server.log 2>&1"
if allowed_domains is not None:
return (
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index fa3f6d3a4fa9..183c9cf535d6 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -130,31 +130,84 @@ class TestGeneratePolicyYaml(TestCase):
@override_settings(DEBUG=True)
def test_debug_mode_adds_dev_ports(self):
policy = yaml.safe_load(generate_policy_yaml([]))
- allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
- self.assertIn(8000, allow_rule["ports"])
- self.assertIn(8010, allow_rule["ports"])
+ debug_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-debug-domains")
+ self.assertIn(8000, debug_rule["ports"])
+ self.assertIn(8010, debug_rule["ports"])
@override_settings(DEBUG=True)
- def test_debug_mode_allows_local_dev_hosts_on_any_port(self):
- policy = yaml.safe_load(generate_policy_yaml(["example.com"]))
- dev_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-local-dev-hosts")
- self.assertEqual(dev_rule["decision"], "allow")
- self.assertIn("host.docker.internal", dev_rule["domains"])
- self.assertIn("localhost", dev_rule["domains"])
- self.assertNotIn("ports", dev_rule)
+ def test_debug_mode_keeps_prod_rule_restricted_to_cloud_ports(self):
+ # DEBUG additions land in `allow-debug-domains`, not `allow-domains` —
+ # the prod rule stays identical across environments so a debug-only
+ # port can't accidentally widen prod.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
+ self.assertEqual(sorted(allow_rule["ports"]), [22, 80, 443])
- @override_settings(DEBUG=True)
- def test_debug_mode_local_dev_rule_precedes_default_deny(self):
- policy = yaml.safe_load(generate_policy_yaml(["example.com"]))
- rules = policy["network_rules"]
- dev_idx = next(i for i, rule in enumerate(rules) if rule["name"] == "allow-local-dev-hosts")
- deny_idx = next(i for i, rule in enumerate(rules) if rule["name"] == "default-deny-network")
- self.assertLess(dev_idx, deny_idx)
+ @override_settings(
+ DEBUG=True,
+ SANDBOX_LLM_GATEWAY_URL="http://host.docker.internal:3308",
+ SANDBOX_MCP_URL="http://host.docker.internal:8787/mcp",
+ )
+ def test_debug_mode_adds_ports_from_sandbox_url_settings(self):
+ # Local llm-gateway (3308) and MCP wrangler (8787) listen on non-standard
+ # ports — without including them in `allow-debug-domains.ports`, agentsh
+ # denies the connect at the syscall layer even when the hostname is allowed.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ debug_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-debug-domains")
+ self.assertIn(3308, debug_rule["ports"])
+ self.assertIn(8787, debug_rule["ports"])
- def test_non_debug_mode_omits_local_dev_hosts_rule(self):
- policy = yaml.safe_load(generate_policy_yaml(["example.com"]))
- rule_names = [r["name"] for r in policy["network_rules"]]
- self.assertNotIn("allow-local-dev-hosts", rule_names)
+ @override_settings(
+ DEBUG=True,
+ SANDBOX_LLM_GATEWAY_URL="http://host.docker.internal:3308",
+ )
+ def test_debug_mode_adds_sandbox_hosts_to_debug_rule(self):
+ # Parsed sandbox hostnames belong on the DEBUG rule, not the prod rule.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ debug_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-debug-domains")
+ allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
+ self.assertIn("host.docker.internal", debug_rule["domains"])
+ self.assertNotIn("host.docker.internal", allow_rule["domains"])
+
+ @override_settings(DEBUG=False, SANDBOX_LLM_GATEWAY_URL="http://example.local:3308")
+ def test_non_debug_mode_omits_debug_rule_entirely(self):
+ # Outside DEBUG the debug rule should not exist, and the prod rule
+ # must not absorb any sandbox URL hostnames or non-cloud ports.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ rule_names = [rule["name"] for rule in policy["network_rules"]]
+ self.assertNotIn("allow-debug-domains", rule_names)
+ allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
+ self.assertEqual(sorted(allow_rule["ports"]), [22, 80, 443])
+ self.assertNotIn("example.local", allow_rule["domains"])
+
+ @override_settings(
+ DEBUG=True,
+ # Non-numeric port — `urlparse(...).port` raises ValueError on access.
+ SANDBOX_API_URL="http://host:abc",
+ # Out-of-range port (>65535) — also raises ValueError.
+ SANDBOX_LLM_GATEWAY_URL="http://host:99999",
+ )
+ def test_debug_mode_tolerates_malformed_sandbox_urls(self):
+ # A typo in `SANDBOX_*_URL` should not crash `generate_policy_yaml`.
+ # Malformed ports degrade silently to "no port added"; the base DEBUG
+ # ports (8000/8010) and prod ports (22/80/443) are preserved so the
+ # sandbox still boots with a sane allowlist.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ debug_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-debug-domains")
+ allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
+ for port in (8000, 8010):
+ self.assertIn(port, debug_rule["ports"])
+ self.assertEqual(sorted(allow_rule["ports"]), [22, 80, 443])
+
+ @override_settings(DEBUG=True, SANDBOX_LLM_GATEWAY_URL="not-a-url-at-all://")
+ def test_debug_mode_tolerates_malformed_sandbox_hostname(self):
+ # Companion to the port-side guard — `_hostname_from_url` should
+ # degrade silently rather than crash policy generation.
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ debug_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-debug-domains")
+ # Localhost + host.docker.internal are still present.
+ self.assertIn("localhost", debug_rule["domains"])
+ self.assertIn("host.docker.internal", debug_rule["domains"])
def test_allow_all_policy_when_no_domains(self):
policy = yaml.safe_load(generate_policy_yaml(None))
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 71e77b5ffa73..1b97a98b0756 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -22,6 +22,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (
FakeTaskRun,
_agent_message_line,
_end_turn_line,
+ _usage_update_line,
_user_message_line,
)
@@ -130,6 +131,90 @@ class TestPollForTurnEmptyEndTurn:
assert printed_lines == len(poll_3_lines)
+class TestPollForTurnTerminalDrain:
+ """Terminal-status drain must recover an agent_message from *this* turn only.
+
+ When the TaskRun reaches a terminal status (FAILED/CANCELLED/COMPLETED) without
+ emitting `end_turn`, `_drain_final_log` re-reads the log and walks backward for
+ the trailing agent_message. The walk must be bounded by the start-of-turn cursor
+ so it never returns a previous turn's response in a multi-turn session.
+ """
+
+ @pytest.mark.asyncio
+ async def test_terminal_status_does_not_return_previous_turn_message(self):
+ """Regression: turn 2 hits terminal status with no agent_message of its own.
+ The drain must raise RuntimeError, NOT silently return turn 1's response."""
+ turn_1 = [_agent_message_line("turn-1-response"), _end_turn_line()]
+ # Turn 2 prompt + tool churn, but the agent died before emitting any agent_message
+ # AND before emitting end_turn (so the empty_end_turn path is not what triggers drain).
+ turn_2_partial = [_user_message_line("followup question"), _usage_update_line(0)]
+
+ log = "\n".join(turn_1 + turn_2_partial)
+ skip = len(turn_1) # start-of-turn-2 cursor — what MultiTurnSession passes
+
+ # Simulate the task reaching FAILED status mid-poll
+ fake_task_run = FakeTaskRun(status="failed", error_message="sandbox killed")
+
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
+ ):
+ with pytest.raises(RuntimeError, match="terminal status"):
+ await poll_for_turn(fake_task_run, skip_lines=skip)
+
+ @pytest.mark.asyncio
+ async def test_terminal_status_recovers_mid_turn_agent_message(self):
+ """The original commit's intent must still hold: when the agent emitted an
+ agent_message earlier in *this* turn but the workflow then hit terminal status
+ without `end_turn`, the drain recovers that message. Verified with skip_lines>0
+ so we're sure the scan walks the current-turn slice, not just [0..end)."""
+ turn_1 = [_agent_message_line("turn-1-response"), _end_turn_line()]
+ # Turn 2: agent emitted text, then died before end_turn (e.g. inactivity timeout)
+ turn_2_recoverable = [
+ _user_message_line("followup question"),
+ _agent_message_line("turn-2-partial-answer"),
+ _usage_update_line(0), # cursor has advanced past the agent_message by now
+ ]
+
+ log = "\n".join(turn_1 + turn_2_recoverable)
+ skip = len(turn_1)
+ fake_task_run = FakeTaskRun(status="failed", error_message="sandbox killed")
+
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
+ ):
+ last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=skip)
+
+ assert last_message == "turn-2-partial-answer"
+
+ @pytest.mark.asyncio
+ async def test_terminal_status_first_turn_still_scans_full_log(self):
+ """First-turn case (skip_lines=0): the drain scans from 0 as before — no behavior
+ change for single-turn or initial-turn callers."""
+ turn_1 = [
+ _user_message_line("initial prompt"),
+ _agent_message_line("partial-before-death"),
+ _usage_update_line(0),
+ ]
+ log = "\n".join(turn_1)
+ fake_task_run = FakeTaskRun(status="failed", error_message="sandbox killed")
+
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 0),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake_task_run),
+ ):
+ last_message, _, _, _ = await poll_for_turn(fake_task_run, skip_lines=0)
+
+ assert last_message == "partial-before-death"
+
+
class TestMultiTurnSessionRetry:
"""send_followup must retry once on EmptyAgentTurnError and propagate if the retry
also fails, so upstream sees a typed failure rather than a timeout or parse error."""