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.

fix(tasks): survive a sandbox reaching its deadline (#86676)

Alessandro Pogliaghi1fb06eaa798b
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.test.ts b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
index 66b55790c627..3e1369e417eb 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.test.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
@@ -25,6 +25,14 @@ describe("classifyAgentError", () => {
["API Error: Request timed out.", "upstream_timeout"],
["API Error: 429 rate limited", "upstream_provider_failure"],
["API Error: 529 overloaded", "upstream_provider_failure"],
+ [
+ "[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ "turn_ended_without_response",
+ ],
+ [
+ "[ede_diagnostic] result_type=assistant last_content_type=text stop_reason=null",
+ "agent_error",
+ ],
["API Error: 400 invalid request", "agent_error"],
// 413 is a hard client rejection, never a transient upstream failure.
["API Error: 413 Payload Too Large", "agent_error"],
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.ts b/products/desktop/packages/agent/src/adapters/error-classification.ts
index ca3b12ed0ec3..f063069a8005 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.ts
@@ -5,9 +5,12 @@ export type AgentErrorClassification =
| "upstream_connection_error"
| "upstream_timeout"
| "upstream_provider_failure"
+ | "turn_ended_without_response"
| "agent_error";
const UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = /API Error:\s*(?:429|5\d\d)\b/i;
+const TURN_ENDED_WITHOUT_RESPONSE_PATTERN =
+ /\[ede_diagnostic\]\s+result_type=user\b/i;
/**
* Classify error strings surfaced by agent adapters. Transient upstream
@@ -50,6 +53,9 @@ export function classifyAgentError(
if (UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.test(text)) {
return "upstream_provider_failure";
}
+ if (TURN_ENDED_WITHOUT_RESPONSE_PATTERN.test(text)) {
+ return "turn_ended_without_response";
+ }
return "agent_error";
}
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 6d3b48098917..989725d16c38 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -3626,6 +3626,86 @@ describe("AgentServer HTTP Mode", () => {
});
});
+ describe("idle handoff resume", () => {
+ const idlePayload: JwtPayload = {
+ task_id: "test-task-id",
+ run_id: "test-run-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive",
+ };
+
+ const setupIdleResume = async (
+ state: Record<string, unknown>,
+ ): Promise<{
+ prompt: ReturnType<typeof vi.fn>;
+ turnCompleteEvents: () => unknown[];
+ sendInitialTaskMessage: () => Promise<void>;
+ }> => {
+ const s = createServer();
+ await s.start();
+
+ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));
+ const broadcastEvent = vi.fn();
+ const internals = s as unknown as {
+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };
+ session: { clientConnection: { prompt: typeof prompt } };
+ nativeResume: { sessionId: string; warm: boolean } | null;
+ broadcastEvent: typeof broadcastEvent;
+ sendInitialTaskMessage(
+ payload: JwtPayload,
+ taskRun: TaskRun | null,
+ ): Promise<void>;
+ };
+ internals.session.clientConnection.prompt = prompt;
+ internals.nativeResume = { sessionId: "prior-session", warm: true };
+ internals.broadcastEvent = broadcastEvent;
+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(
+ createTaskRun({ id: "test-run-id", task: "test-task-id", state }),
+ );
+ process.env.POSTHOG_RESUME_IDLE = "1";
+
+ return {
+ prompt,
+ turnCompleteEvents: () =>
+ broadcastEvent.mock.calls.filter(
+ ([event]) =>
+ (event as { notification?: { method?: string } }).notification
+ ?.method === POSTHOG_NOTIFICATIONS.TURN_COMPLETE,
+ ),
+ sendInitialTaskMessage: () =>
+ internals.sendInitialTaskMessage(idlePayload, null),
+ };
+ };
+
+ afterEach(() => {
+ delete process.env.POSTHOG_RESUME_IDLE;
+ });
+
+ it("does not prompt the resumed session", async () => {
+ const { prompt, turnCompleteEvents, sendInitialTaskMessage } =
+ await setupIdleResume({});
+
+ await sendInitialTaskMessage();
+
+ expect(prompt).not.toHaveBeenCalled();
+ expect(turnCompleteEvents()).toHaveLength(1);
+ });
+
+ it("still delivers a message that landed during the swap", async () => {
+ const { prompt, sendInitialTaskMessage } = await setupIdleResume({
+ pending_user_message: "landed mid-swap",
+ });
+
+ await sendInitialTaskMessage();
+
+ expect(prompt.mock.calls[0]?.[0]).toMatchObject({
+ prompt: [{ type: "text", text: "landed mid-swap" }],
+ });
+ });
+ });
+
it("refetches the run before choosing a native resume prompt", async () => {
const s = createServer();
await s.start();
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index f0c9a16fa84b..607d883b5814 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -135,6 +135,7 @@ const agentErrorClassificationSchema = z.enum([
"upstream_connection_error",
"upstream_timeout",
"upstream_provider_failure",
+ "turn_ended_without_response",
"agent_error",
]) satisfies z.ZodType<AgentErrorClassification>;
@@ -2381,6 +2382,7 @@ export class AgentServer {
}
if (this.nativeResume) {
+ if (await this.settleIdleResume(payload, taskRun)) return;
await this.sendResumeContinuation(payload, taskRun);
return;
}
@@ -2574,6 +2576,35 @@ export class AgentServer {
});
}
+ private async settleIdleResume(
+ payload: JwtPayload,
+ taskRun: TaskRun | null,
+ ): Promise<boolean> {
+ if (!this.session || process.env.POSTHOG_RESUME_IDLE !== "1") return false;
+
+ const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
+ if (pendingUserPrompt?.prompt.length) return false;
+
+ const checkpointApplied = this.nativeResume?.warm
+ ? false
+ : await this.applyResumeGitCheckpoint(payload);
+
+ this.logger.debug("Idle resume settled without a turn", {
+ taskId: payload.task_id,
+ runId: payload.run_id,
+ sessionId: this.nativeResume?.sessionId,
+ warm: this.nativeResume?.warm,
+ checkpointApplied,
+ });
+
+ this.resumeState = null;
+ this.nativeResume = null;
+
+ this.broadcastTurnComplete("end_turn");
+ await this.session.logWriter.flushAll();
+ return true;
+ }
+
private async sendResumeContinuation(
payload: JwtPayload,
taskRun: TaskRun | null,
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index a8746133fcbc..30400ff3e24f 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -175,6 +175,7 @@ RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"
# Gates whether long-running process_task runs continue-as-new to bound history/replay cost.
CONTINUE_AS_NEW_FEATURE_FLAG = "tasks-cloud-run-continue-as-new"
PR_BABYSIT_SNAPSHOT_FEATURE_FLAG = "tasks-pr-babysit-snapshot"
+SANDBOX_ROTATION_FEATURE_FLAG = "tasks-cloud-run-sandbox-rotation"
SnapshotKind = Literal["filesystem", "directory"]
SNAPSHOT_KIND_FILESYSTEM: SnapshotKind = "filesystem"
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.py
index 157c6eb7a350..4adadb2eec18 100644
--- a/products/tasks/backend/logic/services/agent_command.py
+++ b/products/tasks/backend/logic/services/agent_command.py
@@ -41,14 +41,15 @@ BLOCKED_IP_RANGES = [
NO_ACTIVE_SESSION_ERROR = "No active session for this run"
CONTENT_BLOCK_STREAM_ERROR = "API Error: Content block not found"
CONTENT_BLOCK_STREAM_USER_ERROR = "The model response could not be completed. Please retry the task."
+TURN_ENDED_WITHOUT_RESPONSE_ERROR = "[ede_diagnostic] result_type=user"
def is_retryable_agent_rpc_error(error: str) -> bool:
- return CONTENT_BLOCK_STREAM_ERROR in error
+ return CONTENT_BLOCK_STREAM_ERROR in error or TURN_ENDED_WITHOUT_RESPONSE_ERROR in error
def user_facing_agent_error(error: str | None) -> str:
- if error and is_retryable_agent_rpc_error(error):
+ if error and CONTENT_BLOCK_STREAM_ERROR in error:
return CONTENT_BLOCK_STREAM_USER_ERROR
return error or "Failed to send message to sandbox"
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index d3778c071584..6fe0f7800eb2 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -222,6 +222,40 @@ TASK_RUN_FOLLOWUP_DELIVERY_FAILED_TOTAL = Counter(
labelnames=["origin_product", "retryable"],
)
+SANDBOX_DEADLINE_BUCKETS = [5.0, 15.0, 30.0, 60.0, 120.0, 180.0, 300.0, 600.0]
+
+SANDBOX_DEADLINE_TOTAL = Counter(
+ "posthog_tasks_sandbox_deadline_total",
+ "Interactive cloud runs that reached the pre-deadline lead time on their sandbox, "
+ "by what the run ended up on. rotated moved onto a replacement sandbox; snapshot_only "
+ "kept the sandbox it had and saved the session; snapshot_failed kept it with nothing "
+ "saved; routing_lost backed out of a rotation and could not repoint the run, so it can "
+ "take no more messages.",
+ labelnames=["outcome", "reason", "origin_product"],
+)
+
+SANDBOX_ROTATION_DURATION_SECONDS = Histogram(
+ "posthog_tasks_sandbox_rotation_duration_seconds",
+ "Wall time a run spent handling its sandbox deadline. The run answers no messages for "
+ "this long, so it is the user-visible cost of a rotation.",
+ labelnames=["outcome"],
+ buckets=SANDBOX_DEADLINE_BUCKETS,
+)
+
+FOLLOWUP_SANDBOX_STOPPED_TOTAL = Counter(
+ "posthog_tasks_followup_sandbox_stopped_total",
+ "Follow-up deliveries rejected because the control plane reports the run's sandbox "
+ "stopped, by where the check caught it",
+ labelnames=["origin_product", "detected_by"],
+)
+
+FOLLOWUP_DENIED_PERMISSION_STOP_TOTAL = Counter(
+ "posthog_tasks_followup_denied_permission_stop_total",
+ "Follow-up deliveries dropped instead of retried because the turn ended on a permission "
+ "the actor denied. A retry would re-ask the refused question.",
+ labelnames=["origin_product"],
+)
+
TASK_RUN_WIZARD_UNBOUND_TOTAL = Counter(
"posthog_tasks_wizard_run_unbound_total",
"Wizard cloud runs that reached a terminal status without an output.pr_url binding",
@@ -523,6 +557,43 @@ def observe_followup_delivery_failed(task_run: "TaskRun", *, retryable: bool) ->
).inc()
+_SANDBOX_DEADLINE_OUTCOMES = {"rotated", "snapshot_only", "snapshot_failed", "routing_lost"}
+_SANDBOX_DEADLINE_REASONS = {
+ "none",
+ "no_sandbox",
+ "flag_disabled",
+ "agent_active",
+ "followup_in_flight",
+ "run_completed",
+ "snapshot_missing",
+ "provision_failed",
+ "snapshot_unused",
+}
+
+
+def observe_sandbox_deadline(properties: dict[str, object]) -> None:
+ outcome = _bounded_metric_label(properties.get("outcome"), _SANDBOX_DEADLINE_OUTCOMES)
+ SANDBOX_DEADLINE_TOTAL.labels(
+ outcome=outcome,
+ reason=_bounded_metric_label(properties.get("reason"), _SANDBOX_DEADLINE_REASONS),
+ origin_product=_metric_label(properties.get("origin_product")),
+ ).inc()
+ duration = properties.get("duration_seconds")
+ if isinstance(duration, int | float) and not isinstance(duration, bool):
+ SANDBOX_ROTATION_DURATION_SECONDS.labels(outcome=outcome).observe(float(duration))
+
+
+def observe_followup_sandbox_stopped(task_run: "TaskRun | None", *, detected_by: str) -> None:
+ FOLLOWUP_SANDBOX_STOPPED_TOTAL.labels(
+ origin_product=origin_product_label(task_run),
+ detected_by=detected_by,
+ ).inc()
+
+
+def observe_followup_denied_permission_stop(task_run: "TaskRun | None") -> None:
+ FOLLOWUP_DENIED_PERMISSION_STOP_TOTAL.labels(origin_product=origin_product_label(task_run)).inc()
+
+
def observe_loop_fire(*, reason: str) -> None:
LOOP_FIRE_TOTAL.labels(reason=reason).inc()
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 3430617f47fa..d2b113778083 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -40,6 +40,7 @@ from .process_task.activities import (
relay_agent_design_signals,
relay_sandbox_events,
relay_sandbox_events_deferred_completion,
+ restore_sandbox_connection_state,
run_wizard,
send_followup_to_sandbox,
send_permission_denial_guidance,
@@ -76,6 +77,7 @@ ACTIVITIES = [
prepare_sandbox_for_repository,
create_sandbox_for_repository,
inject_fresh_tokens_on_resume,
+ restore_sandbox_connection_state,
invalidate_resume_snapshot,
refresh_sandbox_credentials,
clone_repository_in_sandbox,
diff --git a/products/tasks/backend/temporal/constants.py b/products/tasks/backend/temporal/constants.py
index 9ca8e198cdcc..83221b608025 100644
--- a/products/tasks/backend/temporal/constants.py
+++ b/products/tasks/backend/temporal/constants.py
@@ -110,6 +110,8 @@ def resolve_max_run_duration() -> timedelta | None:
WARM_IDLE_TIMEOUT = timedelta(minutes=10)
+SANDBOX_TTL_SNAPSHOT_LEAD = timedelta(minutes=10)
+
# CI follow-up cadence after the agent has been idle.
CI_FOLLOW_UP_DELAY = timedelta(minutes=15)
diff --git a/products/tasks/backend/temporal/process_task/activities/__init__.py b/products/tasks/backend/temporal/process_task/activities/__init__.py
index b3d1d5dca396..fac2b797e007 100644
--- a/products/tasks/backend/temporal/process_task/activities/__init__.py
+++ b/products/tasks/backend/temporal/process_task/activities/__init__.py
@@ -33,6 +33,7 @@ from .provision_sandbox import (
inject_fresh_tokens_on_resume,
invalidate_resume_snapshot,
prepare_sandbox_for_repository,
+ restore_sandbox_connection_state,
)
from .read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs
from .record_peer_message_outcome import (
@@ -133,6 +134,7 @@ __all__ = [
"get_sandbox_for_repository",
"get_task_processing_context",
"inject_fresh_tokens_on_resume",
+ "restore_sandbox_connection_state",
"invalidate_resume_snapshot",
"post_slack_update",
"prepare_sandbox_for_repository",
diff --git a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
index e34abc9c51c5..1eca8443c4d8 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py
@@ -7,6 +7,7 @@ from django.utils import timezone
from temporalio import activity
+from posthog.dataclasses import frozen
from posthog.models.user_integration import ReauthorizationRequired
from posthog.temporal.common.utils import asyncify
@@ -152,13 +153,14 @@ class GetSandboxForRepositoryInput:
context: TaskProcessingContext
-@dataclass
+@frozen
class GetSandboxForRepositoryOutput:
sandbox_id: str
sandbox_url: str
connect_token: str | None
used_snapshot: bool
should_create_snapshot: bool
+ jwt_kid: str | None = None
agent_server_launched: bool = False
boot_path: str = "classic"
image_source: str | None = None
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 5be99a605e1d..6807f377fd60 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -22,6 +22,7 @@ from products.tasks.backend.constants import (
PR_BABYSIT_SNAPSHOT_FEATURE_FLAG,
RTK_DISABLED_FEATURE_FLAG,
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
+ SANDBOX_ROTATION_FEATURE_FLAG,
get_vm_sandbox_flag_payload,
vm_sandbox_allowed_origin_products,
vm_sandbox_default_base_origin_products,
@@ -108,6 +109,7 @@ class TaskProcessingContext:
# Captured at workflow start so the sandbox event transport branch is
# deterministic for the full run.
sandbox_event_ingest_enabled: bool = False
+ sandbox_rotation_enabled: bool = False
# Captured at workflow start so telemetry env injection (and the run-log mirror,
# which reads the same state stamp) is deterministic for the full run.
agent_otel_telemetry_enabled: bool = False
@@ -783,6 +785,31 @@ def _is_pr_babysit_snapshot_enabled(
return enabled
+def _is_sandbox_rotation_enabled(
+ *,
+ distinct_id: str,
+ organization_id: str,
+ run_id: str,
+) -> bool:
+ try:
+ enabled = bool(
+ posthoganalytics.feature_enabled(
+ SANDBOX_ROTATION_FEATURE_FLAG,
+ distinct_id=distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ log_with_activity_context("sandbox_rotation_flag_check_failed", run_id=run_id, error=str(e))
+ return False
+
+ log_with_activity_context("sandbox_rotation_flag_checked", run_id=run_id, sandbox_rotation_enabled=enabled)
+ return enabled
+
+
def _is_continue_as_new_enabled(
*,
distinct_id: str,
@@ -1181,6 +1208,11 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
use_modal_resume_snapshots=True,
use_modal_directory_resume_snapshots=True,
sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,
+ sandbox_rotation_enabled=_is_sandbox_rotation_enabled(
+ distinct_id=distinct_id,
+ organization_id=organization_id,
+ run_id=run_id,
+ ),
agent_otel_telemetry_enabled=agent_otel_telemetry_enabled,
use_modal_vm_sandbox=use_modal_vm_sandbox,
use_modal_network_allowlist=use_modal_network_allowlist,
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index b26c2fee09fa..80a11df3c1a6 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -3,6 +3,7 @@ import asyncio
import logging
import threading
from dataclasses import dataclass
+from datetime import timedelta
from typing import Any
from django.conf import settings
@@ -12,6 +13,7 @@ import posthoganalytics
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.models.user_integration import ReauthorizationRequired
from posthog.temporal.common.utils import asyncify
@@ -143,13 +145,15 @@ class CreateSandboxForRepositoryInput:
prepared: PrepareSandboxForRepositoryOutput
-@dataclass
+@frozen
class CreateSandboxForRepositoryOutput:
sandbox_id: str
sandbox_url: str
connect_token: str | None
used_snapshot: bool | None = None
create_ms: int | None = None
+ jwt_kid: str | None = None
+ ttl_expires_at: str | None = None
@dataclass
@@ -219,6 +223,15 @@ class InjectFreshTokensOnResumeInput:
repository: str | None
+@frozen
+class RestoreSandboxConnectionStateInput:
+ run_id: str
+ sandbox_id: str
+ sandbox_url: str
+ connect_token: str | None
+ jwt_kid: str | None = None
+
+
@dataclass
class InvalidateResumeSnapshotInput:
run_id: str
@@ -498,6 +511,8 @@ def _build_environment_variables(
environment_variables["POSTHOG_RESUME_RUN_ID"] = run_state.resume_from_run_id
elif run_state.handoff_resumed:
environment_variables["POSTHOG_RESUME_RUN_ID"] = str(ctx.run_id)
+ if run_state.handoff_resume_idle:
+ environment_variables["POSTHOG_RESUME_IDLE"] = "1"
# Cloud wizard runs get a SEPARATE token, minted under the wizard's own OAuth app with the
# wizard's scopes, so the wizard's access stays independent of the agent's sandbox token above.
@@ -648,6 +663,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P
"effective_snapshot_kind": snapshot_kind,
"effective_snapshot_mount_path": snapshot_mount_path,
"handoff_resumed": run_state.handoff_resumed,
+ "handoff_resume_idle": run_state.handoff_resume_idle,
"resume_from_run_id": run_state.resume_from_run_id,
"posthog_resume_run_id_set": "POSTHOG_RESUME_RUN_ID" in environment_variables,
"used_snapshot": used_snapshot,
@@ -658,6 +674,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> P
ctx.run_id,
"debug",
f"Resume mode: handoff_resumed={run_state.handoff_resumed}, "
+ f"resume_idle={run_state.handoff_resume_idle}, "
f"resume_from_run_id={run_state.resume_from_run_id}, "
f"using_modal_snapshot={resume_snapshot_external_id is not None}",
)
@@ -822,10 +839,11 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
credentials = sandbox.get_connect_credentials()
try:
+ jwt_kid = get_primary_sandbox_jwt_kid()
sandbox_state = {
"sandbox_id": sandbox.id,
"sandbox_url": credentials.url,
- SANDBOX_JWT_STATE_KID_KEY: get_primary_sandbox_jwt_kid(),
+ SANDBOX_JWT_STATE_KID_KEY: jwt_kid,
}
if credentials.token:
sandbox_state["sandbox_connect_token"] = credentials.token
@@ -858,6 +876,8 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr
connect_token=credentials.token,
used_snapshot=actual_used_snapshot,
create_ms=create_ms,
+ ttl_expires_at=(sandbox_created_at + timedelta(seconds=sandbox.config.ttl_seconds)).isoformat(),
+ jwt_kid=jwt_kid,
)
@@ -1075,6 +1095,36 @@ def checkout_branch_in_sandbox(input: CheckoutBranchInSandboxInput) -> CheckoutB
return CheckoutBranchInSandboxOutput(checkout_ms=checkout_timer.elapsed_ms)
+@asyncify
+def restore_sandbox_connection_state(input: RestoreSandboxConnectionStateInput) -> None:
+ """Point the run's persisted connection state back at a sandbox it already had.
+
+ Creating a replacement sandbox publishes its connection details immediately, so an
+ abandoned replacement would otherwise leave every later follow-up addressing a sandbox
+ that no longer exists while the original is still serving the run.
+ """
+ updates: dict[str, Any] = {
+ "sandbox_id": input.sandbox_id,
+ "sandbox_url": input.sandbox_url,
+ }
+ remove_keys = [] if input.connect_token else ["sandbox_connect_token"]
+ if input.connect_token:
+ updates["sandbox_connect_token"] = input.connect_token
+ # The signing key id belongs to the same set as the handle it authenticates —
+ # clear_sandbox_connection_state_atomic drops all four together. Leaving the
+ # replacement's behind would sign tokens the restored sandbox does not trust.
+ if input.jwt_kid:
+ updates[SANDBOX_JWT_STATE_KID_KEY] = input.jwt_kid
+ else:
+ remove_keys.append(SANDBOX_JWT_STATE_KID_KEY)
+ TaskRun.update_state_atomic(input.run_id, updates=updates, remove_keys=remove_keys)
+ activity.logger.info(
+ "restored sandbox connection state",
+ extra={"run_id": input.run_id, "sandbox_id": input.sandbox_id},
+ )
+
+
@activity.defn
@asyncify
def inject_fresh_tokens_on_resume(input: InjectFreshTokensOnResumeInput) -> None:
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index 883b1ae3db4e..07eba0d9a77c 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -10,6 +10,7 @@ import structlog
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.models.integration import Integration
from posthog.models.user_integration import ReauthorizationRequired, UserIntegration
from posthog.temporal.common.utils import close_db_connections
@@ -19,6 +20,7 @@ from products.tasks.backend.exceptions import CredentialUnavailableError
from products.tasks.backend.logic.services.agent_command import (
FOLLOWUP_TIMEOUT_SECONDS,
REFRESH_TIMEOUT_SECONDS,
+ TURN_ENDED_WITHOUT_RESPONSE_ERROR,
CommandResult,
send_refresh_session,
send_user_message,
@@ -29,6 +31,7 @@ from products.tasks.backend.logic.services.peer_messages import mark_peer_messag
from products.tasks.backend.logic.services.run_actor import slack_actor_state_updates, user_has_current_team_access
from products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id
from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_key
+from products.tasks.backend.metrics import observe_followup_denied_permission_stop, observe_followup_sandbox_stopped
from products.tasks.backend.models import AgentPeerMessage, TaskRun
from products.tasks.backend.redis import get_tasks_stream_redis_sync, run_uses_dedicated_stream
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
@@ -69,6 +72,7 @@ class SandboxRebindFailure(StrEnum):
NO_CONFIGS_ON_TRANSITION = "no_configs_on_transition"
REFRESH_SESSION_FAILED = "refresh_session_failed"
NO_SANDBOX_HANDLE = "no_sandbox_handle"
+ SANDBOX_NOT_RUNNING = "sandbox_not_running"
CREDENTIAL_LOCK_UNAVAILABLE = "credential_lock_unavailable"
LOGOUT_ERRORED = "logout_errored"
LOGOUT_UNCONFIRMED = "logout_unconfirmed"
@@ -76,6 +80,16 @@ class SandboxRebindFailure(StrEnum):
REFRESH_RETRY_DELAY_SECONDS = 0.5
+SANDBOX_STOPPED_MESSAGE = (
+ "This run's sandbox has stopped, so your message wasn't delivered. Start a new run to continue."
+)
+PEER_SANDBOX_STOPPED_MESSAGE = "The recipient run's sandbox has stopped"
+DENIED_PERMISSION_STOP_MESSAGE = (
+ "Stopped after the denied action. Send a new message to continue with a different approach."
+)
+SLACK_PERMISSION_REJECTED_REQUEST_ID_KEY = "slack_permission_rejected_request_id"
+DENIAL_BRAKE_CONSUMED_REQUEST_ID_KEY = "followup_denial_brake_request_id"
+
# Retries exist for attempt-level deaths (worker restart kills the in-flight
# attempt, detected via heartbeat timeout) and for delivery-unknown failures.
# Application failures that write an error sentinel raise non-retryable.
@@ -154,6 +168,92 @@ def _fail_rebind_closed(
raise RuntimeError(f"send_followup failed: {message} ({reason})")
+def _fail_when_sandbox_stopped(
+ run_id: str,
+ state: dict[str, Any] | None,
+ actor_user: Any,
+ *,
+ task_run: TaskRun | None = None,
+ peer_message_id: str | None = None,
+) -> None:
+ """Stop a delivery the control plane says can never land, before anything else reports it.
+
+ Both credential gates reach the sandbox over its saved URL, so a stopped sandbox fails
+ whichever runs first and the run gets that gate's wording. Asking the control plane up
+ front is what makes the reply name the sandbox, and it covers the runs neither gate would
+ have reported: a bot-authored run skips the GitHub gate entirely.
+ """
+ if not (state or {}).get("sandbox_id"):
+ return
+ if not _resolve_live_sandbox(state).stopped:
+ return
+ observe_followup_sandbox_stopped(task_run, detected_by="preflight")
+ logger.warning(
+ "send_followup_sandbox_stopped",
+ run_id=run_id,
+ actor_user_id=actor_user.id if actor_user is not None else None,
+ sandbox_id=(state or {}).get("sandbox_id"),
+ )
+ if peer_message_id is not None:
+ _mark_peer_delivery_outcome(
+ peer_message_id,
+ AgentPeerMessage.Outcome.DELIVERY_FAILED,
+ "sandbox_stopped",
+ PEER_SANDBOX_STOPPED_MESSAGE,
+ )
+ raise ApplicationError(f"peer message delivery failed: {PEER_SANDBOX_STOPPED_MESSAGE}", non_retryable=True)
+ raise ApplicationError(SANDBOX_STOPPED_MESSAGE, non_retryable=True)
+
+
+def _is_denied_permission_stop(run_id: str, error: str | None, *, steer: bool = False) -> bool:
+ """Whether the turn ended on a user message because the actor denied a permission
+ request, rather than the steer race the same diagnostic also reports.
+
+ Both end the turn identically, so the run's recorded denial is what tells them apart.
+ A denied turn must not be redelivered: the retry would re-ask the question the actor
+ just refused. Slack keys on the same pairing (see post_slack_update.py).
+
+ Two things make that pairing unreliable on its own. The denial is recorded by another
+ activity while this one is blocked inside the turn it ends, so the state read before
+ delivery predates it — hence the fresh read here. And the run-level flag is never
+ cleared, so on its own it would brake every later steer race for the rest of the run
+ and drop those messages. Braking once per rejected request keeps both cases right.
+
+ A steer joins the live turn that the denial ends, so a base delivery and a steer
+ routinely fail together on this same diagnostic. Only the base delivery can re-ask the
+ refused permission, so a steer never brakes: leaving both eligible lets row-lock order
+ decide which of the two is dropped. Claiming stays one locked read-modify-write so that
+ deliveries arriving on the same denial brake once per rejected request.
+ """
+ if steer or not error or TURN_ENDED_WITHOUT_RESPONSE_ERROR not in error:
+ return False
+
+ claimed = False
+
+ def claim_denial(state: dict[str, Any]) -> None:
+ nonlocal claimed
+ if not state.get("slack_permission_rejected"):
+ return
+ request_id = state.get(SLACK_PERMISSION_REJECTED_REQUEST_ID_KEY)
+ if request_id is None:
+ # A denial recorded before the request id was tracked carries nothing to claim, so
+ # it brakes every racer. Re-asking a question the actor refused is worse than a
+ # message they are told was not delivered.
+ claimed = True
+ return
+ if state.get(DENIAL_BRAKE_CONSUMED_REQUEST_ID_KEY) == request_id:
+ return
+ state[DENIAL_BRAKE_CONSUMED_REQUEST_ID_KEY] = request_id
+ claimed = True
+
+ try:
+ TaskRun.mutate_state_atomic(run_id, claim_denial)
+ except Exception:
+ logger.warning("send_followup_denial_state_read_failed", run_id=run_id, exc_info=True)
+ return False
+ return claimed
+
+
def _is_duplicate_delivery(result_data: dict[str, Any] | None) -> bool:
if not isinstance(result_data, dict):
return False
@@ -254,6 +354,8 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
task_run, user_id=actor_user.id, distinct_id=get_actor_distinct_id(actor_user)
)
+ _fail_when_sandbox_stopped(input.run_id, state, actor_user, task_run=task_run)
+
# Rebind the sandbox's MCP session to this actor before the turn. On an
# actor transition this must rebind or clear the prior session; if it can't,
# fail closed rather than run the turn under the previous actor's creds.
@@ -280,6 +382,15 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
# access, otherwise log out so the previous actor's identity can't be used.
# Fail closed only if we can't even clear the prior credentials.
github_failure = _refresh_sandbox_github(task_run, actor_user, state)
+ if github_failure == SandboxRebindFailure.SANDBOX_NOT_RUNNING:
+ observe_followup_sandbox_stopped(task_run, detected_by="github_rebind")
+ logger.warning(
+ "send_followup_sandbox_stopped",
+ run_id=input.run_id,
+ actor_user_id=actor_user.id if actor_user is not None else None,
+ sandbox_id=(state or {}).get("sandbox_id"),
+ )
+ raise ApplicationError(SANDBOX_STOPPED_MESSAGE, non_retryable=True)
if github_failure is not None:
_fail_rebind_closed(
input.run_id,
@@ -347,6 +458,17 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
timeout_seconds=FOLLOWUP_TIMEOUT_SECONDS,
)
elif result.retryable and input.message_id:
+ if _is_denied_permission_stop(input.run_id, result.error, steer=input.steer):
+ observe_followup_denied_permission_stop(task_run)
+ logger.warning(
+ "send_followup_denied_permission_stop",
+ run_id=input.run_id,
+ error=result.error,
+ )
+ _write_error_and_complete(
+ input.run_id, DENIED_PERMISSION_STOP_MESSAGE, run_uses_dedicated_stream(task_run.state)
+ )
+ raise ApplicationError(f"send_followup failed: {result.error}", non_retryable=True)
# Retry transport failures and known transient agent errors. message_id
# prevents duplicate turns when delivery is uncertain, and the agent-server
# releases the id when a delivered turn fails before completion.
@@ -445,6 +567,7 @@ def _deliver_peer_message(input: SendFollowupToSandboxInput, task_run: TaskRun,
auth_token = create_sandbox_connection_token(
task_run, user_id=actor_user.id, distinct_id=get_actor_distinct_id(actor_user)
)
+ _fail_when_sandbox_stopped(input.run_id, state, actor_user, task_run=task_run, peer_message_id=peer_message_id)
mcp_failure = _refresh_sandbox_mcp(
task_run, input.posthog_mcp_scopes, auth_token, actor_user=actor_user, state=state
)
@@ -456,7 +579,11 @@ def _deliver_peer_message(input: SendFollowupToSandboxInput, task_run: TaskRun,
raise ApplicationError(f"peer message delivery failed: {error_msg}", non_retryable=True)
github_failure = _refresh_sandbox_github(task_run, actor_user, state)
if github_failure is not None:
- error_msg = "Could not refresh sandbox GitHub credentials via the bound identity"
+ error_msg = (
+ "The recipient run's sandbox has stopped"
+ if github_failure == SandboxRebindFailure.SANDBOX_NOT_RUNNING
+ else "Could not refresh sandbox GitHub credentials via the bound identity"
+ )
_mark_peer_delivery_outcome(
peer_message_id, AgentPeerMessage.Outcome.DELIVERY_FAILED, "credential_refresh", error_msg
)
@@ -671,29 +798,41 @@ def _refresh_sandbox_mcp(
) # rebind never confirmed → fail closed (unknown binding may hide a live session)
-def _resolve_live_sandbox(state: dict[str, Any] | None) -> Any:
- """The running Sandbox handle for a run's state, or None when unavailable.
+@frozen
+class LiveSandboxLookup:
+ """The running Sandbox handle for a run, or why there isn't one.
+
+ ``stopped`` separates "the control plane says this sandbox is gone" from "we could
+ not find out" (no id recorded yet, or the lookup itself failed). Both block the turn,
+ but only the first is terminal, and the two need different replies.
+ """
+
+ sandbox: Any = None
+ stopped: bool = False
+
+
+def _resolve_live_sandbox(state: dict[str, Any] | None) -> LiveSandboxLookup:
+ """Look up the run's sandbox handle.
GitHub credentials are written into the sandbox directly (git remote + env
- file), so the gate needs the handle. Absent/dead sandbox → None; the
- periodic credential-refresh loop reconciles identity in that case.
+ file), so the gate needs the handle. When there is none, the periodic
+ credential-refresh loop reconciles identity instead.
"""
sandbox_id = (state or {}).get("sandbox_id")
if not sandbox_id:
- return None
+ return LiveSandboxLookup()
from products.tasks.backend.logic.services.sandbox import (
Sandbox, # noqa: PLC0415 — keep the sandbox service off the import path
)
try:
sandbox = Sandbox.get_by_id(sandbox_id)
- return sandbox if sandbox.is_running() else None
+ if sandbox.is_running():
+ return LiveSandboxLookup(sandbox=sandbox)
except Exception:
- # This None drives a fail-closed follow-up rejection, so keep the cause: it
- # distinguishes a genuinely dead sandbox from a transient control-plane lookup
- # error, which have different remediation.
logger.warning("resolve_live_sandbox_failed", sandbox_id=sandbox_id, exc_info=True)
- return None
+ return LiveSandboxLookup()
+ return LiveSandboxLookup(stopped=True)
def _refresh_sandbox_github(
@@ -738,20 +877,19 @@ def _refresh_sandbox_github(
# Re-established every turn rather than skipped when the actor is unchanged: they can connect
# or disconnect their GitHub between any two messages, and the sandbox can lose its token to a
# resume or snapshot restore. Apply the token whenever one resolves, clear it when none does.
- sandbox = _resolve_live_sandbox(state)
- if sandbox is None:
- # We are past the same-actor fast path, so this is an unconfirmed transition. The
- # follow-up can still reach a live agent through the saved sandbox URL, so proceeding
- # would run it under the prior actor's retained credentials. A missing handle (dead
- # sandbox, or a transient control-plane lookup failure) is not proof the sandbox is
- # safe, so fail closed rather than deliver without a confirmed rebind or clear.
+ lookup = _resolve_live_sandbox(state)
+ if lookup.sandbox is None:
+ reason = SandboxRebindFailure.SANDBOX_NOT_RUNNING if lookup.stopped else SandboxRebindFailure.NO_SANDBOX_HANDLE
logger.warning(
"refresh_github_no_sandbox_handle_fail_closed",
run_id=run_id,
user_id=actor_user.id,
sandbox_id=(state or {}).get("sandbox_id"),
+ reason=reason,
)
- return SandboxRebindFailure.NO_SANDBOX_HANDLE
+ return reason
+
+ sandbox = lookup.sandbox
repository = task.repository
token: str | None = None
diff --git a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
index f8e11c508ad2..64ae570f78f1 100644
--- a/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
+++ b/products/tasks/backend/temporal/process_task/activities/track_workflow_event.py
@@ -6,10 +6,12 @@ from temporalio import activity
from posthog.temporal.common.logger import get_logger
-from products.tasks.backend.metrics import observe_task_run_failed
+from products.tasks.backend.metrics import observe_sandbox_deadline, observe_task_run_failed
logger = get_logger(__name__)
+SANDBOX_DEADLINE_EVENT = "sandbox_deadline"
+
@dataclass
class TrackWorkflowEventInput:
@@ -31,6 +33,9 @@ def track_workflow_event(input: TrackWorkflowEventInput) -> None:
if input.event_name == "task_run_failed":
observe_task_run_failed(input.properties)
+ if input.event_name == SANDBOX_DEADLINE_EVENT:
+ observe_sandbox_deadline(input.properties)
+
if not input.capture_analytics:
return
diff --git a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
index 40e55dea0323..81070e9a476b 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_provision_sandbox.py
@@ -311,6 +311,27 @@ def test_build_environment_variables_injects_ai_gateway_pair(_api, _jwt, _git):
assert env["AI_GATEWAY_PRODUCTS"] == "signals_scout"
+@patch(f"{_PROVISION}.get_git_identity_env_vars", return_value={})
+@patch(f"{_PROVISION}.get_sandbox_jwt_public_key", return_value="pub")
+@patch(f"{_PROVISION}.get_sandbox_api_url", return_value="https://api.example")
+ "state, expected_resume_run_id, expected_idle",
+ [
+ ({}, None, None),
+ ({"handoff_resumed": True}, "run-456", None),
+ ({"handoff_resumed": True, "handoff_resume_idle": True}, "run-456", "1"),
+ ({"resume_from_run_id": "run-000", "handoff_resume_idle": True}, "run-000", None),
+ ],
+)
+def test_build_environment_variables_marks_only_an_idle_handoff_as_idle(
+ _api, _jwt, _git, state, expected_resume_run_id, expected_idle
+):
+ env = _build_environment_variables(_context(state=state), MagicMock(), "", "access-token")
+
+ assert env.get("POSTHOG_RESUME_RUN_ID") == expected_resume_run_id
+ assert env.get("POSTHOG_RESUME_IDLE") == expected_idle
+
+
@patch(f"{_PROVISION}.emit_agent_log")
@patch(f"{_PROVISION}.Sandbox.get_by_id")
@pytest.mark.parametrize(
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index 52494d9ad678..cf560019abbb 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -9,9 +9,12 @@ from posthog.models.user_integration import ReauthorizationRequired
from products.tasks.backend.logic.services.agent_command import CommandResult
from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (
+ DENIED_PERMISSION_STOP_MESSAGE,
REFRESH_RETRY_DELAY_SECONDS,
+ SANDBOX_STOPPED_MESSAGE,
SEND_FOLLOWUP_MAX_ATTEMPTS,
STEER_DECLINED_OUTCOME,
+ LiveSandboxLookup,
SandboxRebindFailure,
SendFollowupToSandboxInput,
_refresh_sandbox_github,
@@ -415,7 +418,7 @@ class TestSandboxGithubIdentityGate:
# The actor can connect or disconnect between messages, and a resume or snapshot restore
# can drop the token, so an unchanged actor is not evidence the sandbox still holds it.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = "ghu_token"
mock_apply.return_value = True
mark_sandbox_github_identity("run-1", 42)
@@ -431,7 +434,7 @@ class TestSandboxGithubIdentityGate:
# Same actor as last turn, but their install no longer mints: the cheap skip must not
# leave their token live in the sandbox until the refresh loop next runs.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = None
mock_clear.return_value = True
mark_sandbox_github_identity("run-1", 42)
@@ -447,7 +450,7 @@ class TestSandboxGithubIdentityGate:
# integration does not revoke the token GitHub already issued, so proceeding could leave it
# usable in the sandbox after the user disconnected.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = None
mock_clear.return_value = False
mark_sandbox_github_identity("run-1", 42)
@@ -462,7 +465,7 @@ class TestSandboxGithubIdentityGate:
):
# A different actor inheriting the previous one's live token is the case the gate exists for.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = None
mock_clear.return_value = False
mark_sandbox_github_identity("run-1", 99)
@@ -478,7 +481,7 @@ class TestSandboxGithubIdentityGate:
# Revoke, then reconnect. The logout leaves the sandbox marked against this actor, and the
# reconnect must still be picked up — no marker check may short-circuit the rebind.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_clear.return_value = True
mock_get_token.return_value = None
mark_sandbox_github_identity("run-1", 42)
@@ -510,7 +513,7 @@ class TestSandboxGithubIdentityGate:
self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = "ghu_newtoken"
mock_apply.return_value = True
mark_sandbox_github_identity("run-1", 99)
@@ -525,7 +528,7 @@ class TestSandboxGithubIdentityGate:
self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.side_effect = ReauthorizationRequired("no repo access")
mock_clear.return_value = True
mark_sandbox_github_identity("run-1", 99)
@@ -541,7 +544,7 @@ class TestSandboxGithubIdentityGate:
self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
):
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = "ghu_newtoken"
mock_apply.side_effect = RuntimeError("write failed")
mock_clear.return_value = True
@@ -558,7 +561,7 @@ class TestSandboxGithubIdentityGate:
# rebind: the prior actor's token may still be live in the other location, so log out
# rather than record the new actor.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.return_value = "ghu_newtoken"
mock_apply.return_value = False
mock_clear.return_value = True
@@ -571,20 +574,29 @@ class TestSandboxGithubIdentityGate:
# run owner, and must not inject the owner's token into this actor's session.
assert get_sandbox_github_identity_user("run-1") == 42 # logout confirmed, bound to new actor
+ @pytest.mark.parametrize(
+ "lookup,expected_reason",
+ [
+ (LiveSandboxLookup(), SandboxRebindFailure.NO_SANDBOX_HANDLE),
+ (LiveSandboxLookup(stopped=True), SandboxRebindFailure.SANDBOX_NOT_RUNNING),
+ ],
+ )
def test_no_sandbox_handle_fails_closed(
- self, mock_authorship, mock_resolve, mock_get_token, mock_apply, mock_clear, mock_upgrade
+ self,
+ mock_authorship,
+ mock_resolve,
+ mock_get_token,
+ mock_apply,
+ mock_clear,
+ mock_upgrade,
+ lookup,
+ expected_reason,
):
- # The handle can't be resolved (dead sandbox or transient lookup failure), but a follow-up
- # can still reach a live agent via the saved URL. Fail closed rather than run under the
- # prior actor's retained creds.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = None
+ mock_resolve.return_value = lookup
mark_sandbox_github_identity("run-1", 99)
- assert (
- _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None)
- == SandboxRebindFailure.NO_SANDBOX_HANDLE
- )
+ assert _refresh_sandbox_github(_make_task_run_mock(), MagicMock(id=42), None) == expected_reason
mock_get_token.assert_not_called()
mock_apply.assert_not_called()
mock_clear.assert_not_called()
@@ -596,7 +608,7 @@ class TestSandboxGithubIdentityGate:
# New actor has no access and the sandbox can't even be cleared — the
# previous actor's creds may still be live, so fail closed.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.side_effect = ReauthorizationRequired("no repo access")
mock_clear.return_value = False
mark_sandbox_github_identity("run-1", 99)
@@ -613,7 +625,7 @@ class TestSandboxGithubIdentityGate:
# The clear itself raising (sandbox stopped/timed out between is_running and here) must
# fail closed, not escape uncontrolled.
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.side_effect = ReauthorizationRequired("no repo access")
mock_clear.side_effect = RuntimeError("sandbox stopped")
mark_sandbox_github_identity("run-1", 99)
@@ -632,7 +644,7 @@ class TestSandboxGithubIdentityGate:
from products.tasks.backend.exceptions import CredentialUnavailableError
mock_authorship.return_value = PrAuthorshipMode.USER
- mock_resolve.return_value = MagicMock()
+ mock_resolve.return_value = LiveSandboxLookup(sandbox=MagicMock())
mock_get_token.side_effect = CredentialUnavailableError("integration disconnected", {})
mock_clear.return_value = True
mark_sandbox_github_identity("run-1", 99)
@@ -723,6 +735,34 @@ class TestSendFollowupActivityRefreshOrdering:
_patches["user_msg"].assert_not_called()
+ def test_a_stopped_sandbox_is_named_before_either_credential_gate_runs(self, _patches):
+ _patches["task_run"].state = {"sandbox_id": "sb-1"}
+ _patches["refresh"].return_value = SandboxRebindFailure.REFRESH_SESSION_FAILED
+
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._resolve_live_sandbox",
+ return_value=LiveSandboxLookup(stopped=True),
+ ),
+ pytest.raises(ApplicationError) as excinfo,
+ ):
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))
+
+ assert str(excinfo.value) == SANDBOX_STOPPED_MESSAGE
+ assert excinfo.value.non_retryable
+ _patches["refresh"].assert_not_called()
+ _patches["user_msg"].assert_not_called()
+
+ def test_stopped_sandbox_says_so_once_instead_of_retrying(self, _patches):
+ _patches["refresh_github"].return_value = SandboxRebindFailure.SANDBOX_NOT_RUNNING
+
+ with pytest.raises(ApplicationError) as excinfo:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))
+
+ assert str(excinfo.value) == SANDBOX_STOPPED_MESSAGE
+ assert excinfo.value.non_retryable
+ _patches["user_msg"].assert_not_called()
+
def test_scopes_flow_from_input_to_refresh(self, _patches):
_patches["user_msg"].return_value = CommandResult(success=True, status_code=200)
@@ -837,10 +877,19 @@ class TestSendFollowupTurnTimeout:
task_run = _make_task_run_mock()
task_run.task.created_by = MagicMock(id=42, distinct_id="u42")
mock_task_run_cls.objects.select_related.return_value.get.return_value = task_run
+ denial_state: dict[str, object] = {}
+
+ def mutate_state(_run_id, mutator):
+ mutator(denial_state)
+ return denial_state
+
+ mock_task_run_cls.mutate_state_atomic.side_effect = mutate_state
mock_conn_token.return_value = "jwt"
yield {
"task_run": task_run,
+ "task_run_cls": mock_task_run_cls,
+ "denial_state": denial_state,
"user_msg": mock_user_msg,
"turn_complete": mock_turn_complete,
"error": mock_error,
@@ -914,6 +963,133 @@ class TestSendFollowupTurnTimeout:
)
_patches["turn_complete"].assert_not_called()
+ def test_turn_that_ended_without_a_response_is_redelivered(self, _patches):
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+
+ with pytest.raises(ApplicationError, match="retryable failure") as exc_info:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))
+
+ assert exc_info.value.non_retryable is False
+ _patches["error"].assert_not_called()
+
+ def test_a_later_steer_race_is_still_redelivered_after_an_earlier_denial(self, _patches):
+ _patches["task_run"].state = {}
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+ _patches["denial_state"].update(
+ {
+ "slack_permission_rejected": True,
+ "slack_permission_rejected_request_id": "req-1",
+ "followup_denial_brake_request_id": "req-1",
+ }
+ )
+
+ with pytest.raises(ApplicationError, match="retryable failure") as exc_info:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))
+
+ assert exc_info.value.non_retryable is False
+ _patches["error"].assert_not_called()
+
+ def test_a_denial_recorded_during_the_turn_is_not_redelivered(self, _patches):
+ _patches["task_run"].state = {}
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+ _patches["denial_state"].update(
+ {"slack_permission_rejected": True, "slack_permission_rejected_request_id": "req-1"}
+ )
+
+ with pytest.raises(ApplicationError) as exc_info:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))
+
+ assert exc_info.value.non_retryable is True
+ _patches["error"].assert_called_once()
+ assert _patches["denial_state"]["followup_denial_brake_request_id"] == "req-1"
+
+ def test_a_denied_turn_tells_the_user_why_it_stopped(self, _patches):
+ _patches["task_run"].state = {}
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+ _patches["denial_state"].update(
+ {"slack_permission_rejected": True, "slack_permission_rejected_request_id": "req-1"}
+ )
+
+ with pytest.raises(ApplicationError, match="ede_diagnostic") as exc_info:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))
+
+ assert exc_info.value.non_retryable is True
+ _patches["error"].assert_called_once_with("run-1", DENIED_PERMISSION_STOP_MESSAGE, False)
+
+ def test_a_steer_never_claims_the_denial_that_ended_its_turn(self, _patches):
+ _patches["denial_state"].update(
+ {"slack_permission_rejected": True, "slack_permission_rejected_request_id": "req-1"}
+ )
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+
+ with (
+ patch(
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_sandbox_mcp_session_user",
+ return_value=42,
+ ),
+ pytest.raises(ApplicationError, match="retryable failure") as steer_failure,
+ ):
+ send_followup_to_sandbox(
+ SendFollowupToSandboxInput(
+ run_id="run-1", message="wait", message_id="m-steer", actor_user_id=42, steer=True
+ )
+ )
+ with pytest.raises(ApplicationError) as base_failure:
+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-base"))
+
+ assert steer_failure.value.non_retryable is False
+ assert base_failure.value.non_retryable is True
+ assert _patches["denial_state"]["followup_denial_brake_request_id"] == "req-1"
+
+ def test_two_deliveries_failing_on_one_denial_only_brake_once(self, _patches):
+ # A steer joins the turn the denial ends, so the base delivery and the steer come back
+ # on the same diagnostic. Only the racer that claims the denial may brake; the other
+ # has to stay retryable or its message is the one that disappears.
+ _patches["denial_state"].update(
+ {"slack_permission_rejected": True, "slack_permission_rejected_request_id": "req-1"}
+ )
+ _patches["user_msg"].return_value = CommandResult(
+ success=False,
+ status_code=200,
+ error="Internal error: [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
+ retryable=True,
+ )
+
+ verdicts = []
+ for message_id in ("m-1", "m-2"):
+ with pytest.raises(ApplicationError) as exc_info:
+ send_followup_to_sandbox(
+ SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id=message_id)
+ )
+ verdicts.append(exc_info.value.non_retryable)
+
+ assert verdicts == [True, False]
+
def test_response_504_retries_without_sentinel(self, _patches):
# Regression: a genuine 504 *response* (tunnel gateway timeout,
# delivery unknown) used to be conflated with the read-timeout case
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index c75a596c1ef2..154c35f6ecc0 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -7,7 +7,7 @@ import dataclasses
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, Mock
@@ -25,7 +25,11 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from products.tasks.backend.logic.services.sandbox import Sandbox, SandboxConfig, SandboxStatus, SandboxTemplate
from products.tasks.backend.models import SandboxSnapshot
from products.tasks.backend.temporal.babysit_pr.snapshot import BabysitJournal
-from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_USER_SECONDS, WARM_IDLE_TIMEOUT
+from products.tasks.backend.temporal.constants import (
+ INACTIVITY_TIMEOUT_USER_SECONDS,
+ SANDBOX_TTL_SNAPSHOT_LEAD,
+ WARM_IDLE_TIMEOUT,
+)
from products.tasks.backend.temporal.process_task import workflow as process_task_workflow_module
from products.tasks.backend.temporal.process_task.activities import (
STEER_DECLINED_OUTCOME,
@@ -61,6 +65,7 @@ from products.tasks.backend.temporal.process_task.activities import (
track_workflow_event,
update_task_run_status,
)
+from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import CreateResumeSnapshotOutput
from products.tasks.backend.temporal.process_task.activities.emit_progress_activity import EmitProgressInput
from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import SendFollowupToSandboxInput
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
@@ -347,6 +352,408 @@ class TestProcessTaskWorkflow:
assert any("no longer exists" in cause or "not found" in cause for cause in causes), causes
+class TestSandboxDeadline:
+ """The provider kills a sandbox on a fixed clock. An interactive run has to snapshot
+ itself before that lands, because the teardown snapshot runs against a sandbox that is
+ already gone."""
+
+ def _workflow(
+ self,
+ *,
+ deadline: datetime | None,
+ mode: str = "interactive",
+ use_modal_resume_snapshots: bool = True,
+ ) -> ProcessTaskWorkflow:
+ wf = ProcessTaskWorkflow()
+ wf._context = _build_context(
+ github_integration_id=123,
+ state={"mode": mode},
+ use_modal_resume_snapshots=use_modal_resume_snapshots,
+ )
+ wf._sandbox_ttl_expires_at = deadline
+ return wf
+
+ def test_deadline_from_a_pre_rollout_history_leaves_the_timer_unscheduled(self):
+ wf = self._workflow(deadline=None)
+ created = CreateSandboxForRepositoryOutput(sandbox_id="sb-1", sandbox_url="https://s", connect_token=None)
+
+ wf._record_sandbox_deadline(created)
+
+ assert wf._sandbox_ttl_expires_at is None
+ assert wf._sandbox_deadline_snapshot_scheduled() is False
+
+ def test_a_replacement_sandbox_starts_its_clock_over(self, monkeypatch):
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+ wf = self._workflow(deadline=datetime(2026, 7, 16, 12, 0, tzinfo=UTC))
+ wf._sandbox_ttl_snapshot_taken = True
+
+ wf._record_sandbox_deadline(
+ CreateSandboxForRepositoryOutput(
+ sandbox_id="sb-2",
+ sandbox_url="https://s",
+ connect_token=None,
+ ttl_expires_at="2026-07-16T18:00:00+00:00",
+ )
+ )
+
+ assert wf._sandbox_ttl_expires_at == datetime(2026, 7, 16, 18, 0, tzinfo=UTC)
+ assert wf._sandbox_ttl_snapshot_taken is False
+ assert wf._sandbox_deadline_snapshot_scheduled() is True
+
+ @parameterized.expand(
+ [
+ ("already_snapshotted", {"snapshot_taken": True}, False),
+ ("non_interactive", {"mode": "one_off"}, False),
+ ("resume_snapshots_disabled", {"use_modal_resume_snapshots": False}, False),
+ ("interactive_with_snapshots", {}, True),
+ ]
+ )
+ def test_only_runs_with_something_to_restore_wait_on_the_deadline(self, _name, overrides, expected):
+ wf = self._workflow(
+ deadline=datetime(2026, 7, 16, 12, 0, tzinfo=UTC),
+ mode=overrides.get("mode", "interactive"),
+ use_modal_resume_snapshots=overrides.get("use_modal_resume_snapshots", True),
+ )
+ wf._sandbox_ttl_snapshot_taken = overrides.get("snapshot_taken", False)
+
+ assert wf._sandbox_deadline_snapshot_scheduled() is expected
+
+ async def test_timer_sleeps_until_the_lead_time_before_the_deadline(self, monkeypatch):
+ wf = self._workflow(deadline=datetime(2026, 7, 16, 12, 0, tzinfo=UTC))
+ sleep_mock = AsyncMock()
+ monkeypatch.setattr(
+ process_task_workflow_module.workflow, "now", Mock(return_value=datetime(2026, 7, 16, 9, 0, tzinfo=UTC))
+ )
+ monkeypatch.setattr(process_task_workflow_module.workflow, "sleep", sleep_mock)
+
+ event = await wf._wait_for_sandbox_deadline()
+
+ assert event == process_task_workflow_module.TaskEvent.SANDBOX_TTL_APPROACHING
+ expected = (timedelta(hours=3) - SANDBOX_TTL_SNAPSHOT_LEAD).total_seconds()
+ sleep_mock.assert_awaited_once_with(expected)
+
+ async def test_a_deadline_already_inside_the_lead_time_fires_without_sleeping(self, monkeypatch):
+ wf = self._workflow(deadline=datetime(2026, 7, 16, 12, 0, tzinfo=UTC))
+ sleep_mock = AsyncMock()
+ monkeypatch.setattr(
+ process_task_workflow_module.workflow, "now", Mock(return_value=datetime(2026, 7, 16, 11, 55, tzinfo=UTC))
+ )
+ monkeypatch.setattr(process_task_workflow_module.workflow, "sleep", sleep_mock)
+
+ event = await wf._wait_for_sandbox_deadline()
+
+ assert event == process_task_workflow_module.TaskEvent.SANDBOX_TTL_APPROACHING
+ sleep_mock.assert_not_awaited()
+
+
+class TestSandboxRotation:
+ """Rotation moves a run onto a replacement sandbox before the provider kills the one it has.
+ Anything that goes wrong has to leave the run on its current sandbox, which still has the
+ lead time left on its clock."""
+
+ def _workflow(self, monkeypatch, *, rotation_enabled: bool = True) -> ProcessTaskWorkflow:
+ wf = ProcessTaskWorkflow()
+ wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})
+ wf._context.sandbox_rotation_enabled = rotation_enabled
+ wf._sandbox_url = "https://old.example"
+ wf._sandbox_connect_token = "old-token"
+ wf._sandbox_jwt_kid = "kid-old"
+ wf._sandbox_id_for_cleanup = "sb-old"
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
+ return wf
+
+ def _relay(self, name: str) -> "asyncio.Task[None]":
+ return cast("asyncio.Task[None]", name)
+
+ def _snapshot(self, external_id: str | None = "snap-1") -> CreateResumeSnapshotOutput:
+ return CreateResumeSnapshotOutput(
+ external_id=external_id, snapshot_kind="directory", snapshot_mount_path="/mnt/work"
+ )
+
+ def _replacement(self, used_snapshot: bool = True) -> GetSandboxForRepositoryOutput:
+ return GetSandboxForRepositoryOutput(
+ sandbox_id="sb-new",
+ sandbox_url="https://new.example",
+ connect_token="new-token",
+ used_snapshot=used_snapshot,
+ should_create_snapshot=not used_snapshot,
+ )
+
+ @parameterized.expand(
+ [
+ ("idle_with_flag_on", {}, True),
+ ("flag_off", {"rotation_enabled": False}, False),
+ ("agent_mid_turn", {"agent_active": True}, False),
+ ("run_finishing", {"task_completed": True}, False),
+ ("followup_in_flight", {"followup_running": True}, False),
+ ("followup_finished", {"followup_running": False, "followup_present": True}, True),
+ ]
+ )
+ def test_only_an_idle_run_with_the_flag_on_may_rotate(self, _name, overrides, expected):
+ wf = ProcessTaskWorkflow()
+ wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})
+ wf._context.sandbox_rotation_enabled = overrides.get("rotation_enabled", True)
+ wf._agent_active = overrides.get("agent_active", False)
+ wf._task_completed = overrides.get("task_completed", False)
+ if overrides.get("followup_running") or overrides.get("followup_present"):
+ followup = Mock()
+ followup.done.return_value = not overrides.get("followup_running", False)
+ wf._active_followup_task = followup
+
+ assert (wf._sandbox_rotation_block_reason() is None) is expected
+
+ async def test_the_credential_refresh_loop_follows_the_run_to_the_new_sandbox(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", AsyncMock(return_value=self._replacement()))
+ monkeypatch.setattr(wf, "_start_agent_server", AsyncMock())
+ cancelled: list[object] = []
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock(side_effect=lambda task: cancelled.append(task)))
+ monkeypatch.setattr(wf, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ spawn_refresh = Mock(return_value=self._relay("refresh-new"))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", spawn_refresh)
+ refresh_old = self._relay("refresh-old")
+
+ await wf._rotate_sandbox_before_deadline("sb-old", None, refresh_old)
+
+ assert refresh_old in cancelled
+ spawn_refresh.assert_called_once_with("sb-new")
+
+ async def test_successful_rotation_repoints_the_run_and_drops_the_old_sandbox(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+ resume_flags_at_provision = {}
+
+ async def provision_replacement():
+ state = wf.context.state or {}
+ resume_flags_at_provision["value"] = (state.get("handoff_resumed"), state.get("handoff_resume_idle"))
+ return self._replacement()
+
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", provision_replacement)
+ monkeypatch.setattr(wf, "_start_agent_server", AsyncMock())
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ cleanup = AsyncMock()
+ monkeypatch.setattr(wf, "_cleanup_sandbox", cleanup)
+ relay_new = self._relay("relay-new")
+ refresh_new = self._relay("refresh-new")
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=relay_new))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=refresh_new))
+
+ rotation = await wf._rotate_sandbox_before_deadline(
+ "sb-old", self._relay("relay-old"), self._relay("refresh-old")
+ )
+
+ assert rotation.sandbox_id == "sb-new"
+ assert rotation.relay_task is relay_new
+ assert rotation.credential_refresh_task is refresh_new
+ assert (wf._sandbox_url, wf._sandbox_connect_token) == ("https://new.example", "new-token")
+ assert wf._sandbox_id_for_cleanup == "sb-new"
+ assert resume_flags_at_provision["value"] == (True, True)
+ cleanup.assert_awaited_once_with("sb-old", complete_stream=False)
+
+ async def test_the_replacement_is_built_from_the_snapshot_just_taken(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", AsyncMock(return_value=self._replacement()))
+ monkeypatch.setattr(wf, "_start_agent_server", AsyncMock())
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ monkeypatch.setattr(wf, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=None))
+
+ await wf._rotate_sandbox_before_deadline("sb-old", None, None)
+
+ state = wf.context.state or {}
+ assert state["snapshot_external_id"] == "snap-1"
+ assert state["snapshot_kind"] == "directory"
+ assert state["snapshot_mount_path"] == "/mnt/work"
+
+ async def test_routing_that_could_not_be_restored_is_reported_not_swallowed(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+
+ async def fail_after_creating() -> GetSandboxForRepositoryOutput:
+ wf._sandbox_id_for_cleanup = "sb-half-built"
+ raise RuntimeError("agent server never came up")
+
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", fail_after_creating)
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ monkeypatch.setattr(wf, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_restore_sandbox_connection_state", AsyncMock(return_value=False))
+
+ rotation = await wf._rotate_sandbox_before_deadline("sb-old", None, None)
+
+ assert rotation.sandbox_id is None
+ assert rotation.routing_restored is False
+
+ async def test_a_replacement_built_without_the_snapshot_does_not_replace_the_live_sandbox(self, monkeypatch):
+ # Provisioning reports success for a sandbox it had to build fresh, which holds the
+ # branch head rather than the run's working tree. Completing the rotation there would
+ # destroy the only copy of the agent's uncommitted work.
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+ monkeypatch.setattr(
+ wf, "_get_sandbox_for_repository", AsyncMock(return_value=self._replacement(used_snapshot=False))
+ )
+ monkeypatch.setattr(wf, "_start_agent_server", AsyncMock())
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ cleanup = AsyncMock()
+ monkeypatch.setattr(wf, "_cleanup_sandbox", cleanup)
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=None))
+ restore = AsyncMock(return_value=True)
+ monkeypatch.setattr(wf, "_restore_sandbox_connection_state", restore)
+ wf._sandbox_id_for_cleanup = "sb-new"
+
+ rotation = await wf._rotate_sandbox_before_deadline("sb-old", None, None)
+
+ assert rotation.sandbox_id is None
+ assert (wf._sandbox_url, wf._sandbox_connect_token) == ("https://old.example", "old-token")
+ assert wf._sandbox_id_for_cleanup == "sb-old"
+ cleanup.assert_awaited_once_with("sb-new", complete_stream=False)
+ restore.assert_awaited_once_with("sb-old", "https://old.example", "old-token", "kid-old")
+
+ async def test_initial_provisioning_remembers_the_signing_key_of_the_sandbox_it_created(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ wf._sandbox_jwt_kid = None
+ prepared = PrepareSandboxForRepositoryOutput(
+ sandbox_name="sandbox-name",
+ repository="posthog/posthog-js",
+ github_token="",
+ branch=None,
+ environment_variables={},
+ snapshot_id=None,
+ snapshot_external_id=None,
+ used_snapshot=True,
+ should_create_snapshot=False,
+ shallow_clone=False,
+ image_source="base_image",
+ image_source_label="published sandbox base image",
+ sandbox_creation_timeout_seconds=30 * 60,
+ )
+ created = CreateSandboxForRepositoryOutput(
+ sandbox_id="sb-provisioned",
+ sandbox_url="https://provisioned.example",
+ connect_token="provisioned-token",
+ used_snapshot=True,
+ jwt_kid="kid-provisioned",
+ )
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", AsyncMock(return_value=prepared))
+ monkeypatch.setattr(wf, "_run_sandbox_creation_activity", AsyncMock(return_value=created))
+ monkeypatch.setattr(wf, "_record_sandbox_deadline", Mock())
+ monkeypatch.setattr(wf, "_emit_progress", AsyncMock())
+
+ output = await wf._get_sandbox_for_repository()
+
+ assert output.jwt_kid == "kid-provisioned"
+ assert wf._sandbox_jwt_kid == "kid-provisioned"
+
+ @pytest.mark.parametrize(
+ "snapshot_invalidated, expected_saved",
+ [(False, True), (True, False)],
+ )
+ async def test_an_abandoned_rotation_reports_the_snapshot_it_already_took(
+ self, monkeypatch, snapshot_invalidated, expected_saved
+ ):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+
+ async def fail_after_creating() -> GetSandboxForRepositoryOutput:
+ wf._sandbox_id_for_cleanup = "sb-half-built"
+ wf._resume_snapshot_invalidated = snapshot_invalidated
+ raise RuntimeError("agent server never came up")
+
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", fail_after_creating)
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ monkeypatch.setattr(wf, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_restore_sandbox_connection_state", AsyncMock(return_value=True))
+
+ rotation = await wf._rotate_sandbox_before_deadline("sb-old", None, None)
+
+ assert rotation.sandbox_id is None
+ assert rotation.snapshot_saved is expected_saved
+
+ async def test_an_abandoned_rotation_puts_the_live_sandbox_back_on_the_clock_it_had(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ old_deadline = datetime(2026, 7, 16, 12, 0, tzinfo=UTC)
+ wf._sandbox_ttl_expires_at = old_deadline
+ wf._sandbox_ttl_snapshot_taken = True
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+
+ async def provision_replacement_then_fail() -> GetSandboxForRepositoryOutput:
+ wf._sandbox_id_for_cleanup = "sb-new"
+ wf._sandbox_jwt_kid = "kid-new"
+ wf._sandbox_ttl_expires_at = datetime(2026, 7, 16, 18, 0, tzinfo=UTC)
+ wf._sandbox_ttl_snapshot_taken = False
+ raise RuntimeError("agent server never came up")
+
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", provision_replacement_then_fail)
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ monkeypatch.setattr(wf, "_cleanup_sandbox", AsyncMock())
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=None))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=None))
+ restore = AsyncMock(return_value=True)
+ monkeypatch.setattr(wf, "_restore_sandbox_connection_state", restore)
+
+ await wf._rotate_sandbox_before_deadline("sb-old", None, None)
+
+ assert wf._sandbox_jwt_kid == "kid-old"
+ assert wf._sandbox_ttl_expires_at == old_deadline
+ assert wf._sandbox_ttl_snapshot_taken is True
+ restore.assert_awaited_once_with("sb-old", "https://old.example", "old-token", "kid-old")
+
+ async def test_a_snapshot_that_did_not_happen_leaves_the_run_where_it_is(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot(None)))
+ provision = AsyncMock()
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", provision)
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+
+ relay_old = self._relay("relay-old")
+ refresh_old = self._relay("refresh-old")
+ rotation = await wf._rotate_sandbox_before_deadline("sb-old", relay_old, refresh_old)
+
+ assert rotation.sandbox_id is None
+ assert rotation.relay_task is relay_old
+ assert rotation.credential_refresh_task is refresh_old
+ provision.assert_not_awaited()
+
+ async def test_a_failed_replacement_restores_the_old_sandbox_and_its_relay(self, monkeypatch):
+ wf = self._workflow(monkeypatch)
+ monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))
+
+ async def fail_after_creating() -> GetSandboxForRepositoryOutput:
+ wf._sandbox_id_for_cleanup = "sb-half-built"
+ raise RuntimeError("agent server never came up")
+
+ monkeypatch.setattr(wf, "_get_sandbox_for_repository", fail_after_creating)
+ monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())
+ cleanup = AsyncMock()
+ monkeypatch.setattr(wf, "_cleanup_sandbox", cleanup)
+ relay_restarted = self._relay("relay-restarted")
+ monkeypatch.setattr(wf, "_spawn_event_relay", Mock(return_value=relay_restarted))
+ monkeypatch.setattr(wf, "_spawn_credential_refresh", Mock(return_value=self._relay("refresh-restarted")))
+ restore = AsyncMock(return_value=True)
+ monkeypatch.setattr(wf, "_restore_sandbox_connection_state", restore)
+
+ rotation = await wf._rotate_sandbox_before_deadline(
+ "sb-old", self._relay("relay-old"), self._relay("refresh-old")
+ )
+
+ assert rotation.sandbox_id is None
+ assert rotation.relay_task is relay_restarted
+ assert rotation.routing_restored is True
+ assert wf._sandbox_id_for_cleanup == "sb-old"
+ assert (wf._sandbox_url, wf._sandbox_connect_token) == ("https://old.example", "old-token")
+ cleanup.assert_awaited_once_with("sb-half-built", complete_stream=False)
+ restore.assert_awaited_once_with("sb-old", "https://old.example", "old-token", "kid-old")
+
+
class TestProcessTaskFollowupDispatch:
async def test_declined_steers_requeue_in_arrival_order(self, monkeypatch):
workflow = ProcessTaskWorkflow()
@@ -2416,6 +2823,7 @@ class TestContinueAsNew:
wf._agent_active = False
wf._end_of_turn_received = True
wf._last_agent_heartbeat_at = datetime(2026, 7, 16, 10, 29, tzinfo=UTC)
+ wf._sandbox_ttl_expires_at = datetime(2026, 7, 16, 15, 0, tzinfo=UTC)
wf._slack_thread_context = {"channel": "C1"}
wf._posthog_mcp_scopes = "full"
@@ -2442,6 +2850,7 @@ class TestContinueAsNew:
assert restored._agent_active is False
assert restored._end_of_turn_received is True
assert restored._last_agent_heartbeat_at == datetime(2026, 7, 16, 10, 29, tzinfo=UTC)
+ assert restored._sandbox_ttl_expires_at == datetime(2026, 7, 16, 15, 0, tzinfo=UTC)
# The wall-clock cap anchors on the chain start, so the first execution seeds it from
# its own start_time and every later continuation carries that same value forward.
assert restored._chain_started_at == chain_start
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 9ce31c67c727..f25dcf8a90ef 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -390,6 +390,7 @@ class RunState(BaseModel, extra="allow"):
fast_mode: bool | None = None
resume_from_run_id: str | None = None
handoff_resumed: bool = False
+ handoff_resume_idle: bool = False
snapshot_external_id: str | None = None
snapshot_kind: str | None = None
snapshot_mount_path: str | None = None
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 5769d19eab6d..f8caceb6766c 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -44,7 +44,11 @@ from .activities.cleanup_sandbox import (
cleanup_sandbox,
complete_run_stream,
)
-from .activities.create_resume_snapshot import CreateResumeSnapshotInput, create_resume_snapshot
+from .activities.create_resume_snapshot import (
+ CreateResumeSnapshotInput,
+ CreateResumeSnapshotOutput,
+ create_resume_snapshot,
+)
from .activities.emit_progress_activity import EmitProgressInput, emit_progress_activity
from .activities.enforce_self_driving_quota import (
SELF_DRIVING_QUOTA_CANCELLED,
@@ -76,6 +80,7 @@ from .activities.provision_sandbox import (
InvalidateResumeSnapshotInput,
PrepareSandboxForRepositoryInput,
PrepareSandboxForRepositoryOutput,
+ RestoreSandboxConnectionStateInput,
checkout_branch_in_sandbox,
clone_repository_in_sandbox,
create_sandbox_for_repository,
@@ -83,6 +88,7 @@ from .activities.provision_sandbox import (
inject_fresh_tokens_on_resume,
invalidate_resume_snapshot,
prepare_sandbox_for_repository,
+ restore_sandbox_connection_state,
)
from .activities.read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logs
from .activities.record_peer_message_outcome import (
@@ -121,7 +127,7 @@ from .activities.start_agent_server import (
mark_repo_ready,
start_agent_server,
)
-from .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_event
+from .activities.track_workflow_event import SANDBOX_DEADLINE_EVENT, TrackWorkflowEventInput, track_workflow_event
from .activities.update_task_run_status import (
SANDBOX_GONE_STATE_KEY,
TIMED_OUT_WALL_CLOCK_STATE_KEY,
@@ -173,6 +179,7 @@ class ResumedSandboxState:
sandbox_url: str
connect_token: Optional[str]
ci_repetitions: int
+ jwt_kid: Optional[str] = None
pr_fingerprint: Optional[str]
pr_progress_emitted: bool
first_user_message_received: bool
@@ -189,6 +196,36 @@ class ResumedSandboxState:
agent_active: Optional[bool] = None
end_of_turn_received: Optional[bool] = None
last_agent_heartbeat_at: Optional[str] = None
+ sandbox_ttl_expires_at: Optional[str] = None
+ sandbox_ttl_snapshot_taken: bool = False
+
+
+@frozen
+class PreRotationSandbox:
+ sandbox_id: str
+ sandbox_url: str | None
+ connect_token: str | None
+ jwt_kid: str | None
+ ttl_expires_at: datetime | None = None
+ ttl_snapshot_taken: bool = False
+
+
+@frozen
+class SandboxRotation:
+ """Outcome of a rotation attempt: the sandbox the run is now on, and the background
+ tasks feeding it. ``sandbox_id`` is None when the run stayed where it was.
+
+ ``routing_restored`` is False when a failed rotation could not point the run's persisted
+ routing back at the sandbox still serving it, so follow-ups would address the replacement
+ that was torn down.
+ """
+
+ sandbox_id: str | None = None
+ relay_task: Optional["asyncio.Task[None]"] = None
+ credential_refresh_task: Optional["asyncio.Task[None]"] = None
+ routing_restored: bool = True
+ snapshot_saved: bool = False
+ reason: str = "none"
@dataclass
@@ -242,6 +279,7 @@ class TaskEvent(StrEnum):
CI_FOLLOW_UP = "ci_follow_up"
SANDBOX_GONE = "sandbox_gone"
QUOTA_RECHECK = "quota_recheck"
+ SANDBOX_TTL_APPROACHING = "sandbox_ttl_approaching"
class CIFollowUpDecision(StrEnum):
@@ -266,6 +304,7 @@ from products.tasks.backend.temporal.constants import ( # noqa: E402
MAX_CI_REPETITIONS,
PENDING_MESSAGE_FORWARD_TIMEOUT_SECONDS,
RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
+ SANDBOX_TTL_SNAPSHOT_LEAD,
SEND_STEER_SIGNAL,
STEERING_PROTOCOL_QUERY,
STEERING_PROTOCOL_VERSION,
@@ -397,6 +436,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# Captured once the agent server is up, for handing to a continue_as_new continuation.
self._sandbox_url: Optional[str] = None
self._sandbox_connect_token: Optional[str] = None
+ self._sandbox_jwt_kid: Optional[str] = None
+ self._resume_snapshot_invalidated = False
self._task_completed: bool = False
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
@@ -440,6 +481,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._babysit_journal: BabysitJournal = BabysitJournal()
self._pending_babysit: Optional[_BabysitDispatch] = None
self._ci_resume_snapshot_created: bool = False
+ self._sandbox_ttl_expires_at: Optional[datetime] = None
+ self._sandbox_ttl_snapshot_taken: bool = False
# Decided once at workflow start; gates the placeholder skip + relay spawn.
self._is_agent_design_enabled: bool = False
# Deadline-based so heartbeats waking the event loop don't keep resetting the timer.
@@ -643,6 +686,75 @@ class ProcessTaskWorkflow(PostHogWorkflow):
and workflow.patched(_PATCH_ID_SELF_DRIVING_QUOTA_KILL)
)
+ def _record_sandbox_deadline(self, created: CreateSandboxForRepositoryOutput) -> None:
+ """Remember when the provider will kill this sandbox, so the run can snapshot first.
+
+ A fresh sandbox is a fresh clock, so the previous one's snapshot state does not carry
+ over. Histories recorded before the activity reported a deadline decode ``None`` here,
+ which leaves the timer unscheduled and keeps their replays command-for-command
+ identical.
+ """
+ self._sandbox_ttl_snapshot_taken = False
+ self._sandbox_ttl_expires_at = (
+ datetime.fromisoformat(created.ttl_expires_at) if created.ttl_expires_at else None
+ )
+ if self._sandbox_ttl_expires_at is not None:
+ workflow.logger.info(
+ "sandbox_deadline_recorded",
+ extra={
+ "run_id": self.context.run_id,
+ "sandbox_id": created.sandbox_id,
+ "ttl_expires_at": created.ttl_expires_at,
+ },
+ )
+
+ def _sandbox_deadline_snapshot_scheduled(self) -> bool:
+ """Whether a pre-deadline snapshot is still worth waiting for.
+
+ Only interactive runs on resume snapshots: everything else has nothing to restore, so
+ the snapshot would cost provider time for a session no one can pick back up.
+ """
+ return (
+ self._sandbox_ttl_expires_at is not None
+ and not self._sandbox_ttl_snapshot_taken
+ and self._context is not None
+ and self._context.mode == "interactive"
+ and self._context.use_modal_resume_snapshots
+ )
+
+ def _sandbox_rotation_block_reason(self) -> str | None:
+ """Why this run may not move onto a replacement sandbox, or None when it may.
+
+ Only while nothing is in flight: rotation restores a filesystem snapshot, so a turn
+ underway would be cut off mid-thought with no way to resume it. A delivery that has
+ not yet produced an active-state signal counts as in flight too, which is why the
+ follow-up task is checked alongside the agent's own state.
+
+ The reason is what tells a rollout whether rotation is idle-gated out of the runs that
+ need it most, so it is a metric label rather than a log line.
+ """
+ if self._context is None or not self._context.sandbox_rotation_enabled:
+ return "flag_disabled"
+ if self._agent_active:
+ return "agent_active"
+ if self._active_followup_task is not None and not self._active_followup_task.done():
+ return "followup_in_flight"
+ if self._task_completed:
+ return "run_completed"
+ return None
+
+ async def _wait_for_sandbox_deadline(self) -> TaskEvent:
+ """Wake up shortly before the provider kills the sandbox.
+
+ Fires immediately when the lead time has already passed, which is the case a
+ continuation inherits, so a late-hydrated deadline still gets its snapshot.
+ """
+ assert self._sandbox_ttl_expires_at is not None
+ remaining = (self._sandbox_ttl_expires_at - SANDBOX_TTL_SNAPSHOT_LEAD) - workflow.now()
+ if remaining.total_seconds() > 0:
+ await workflow.sleep(remaining.total_seconds())
+ return TaskEvent.SANDBOX_TTL_APPROACHING
+
async def _wait_for_quota_recheck(self):
if self._self_driving_quota_next_check_at is None:
self._self_driving_quota_next_check_at = workflow.now() + SELF_DRIVING_QUOTA_RECHECK_INTERVAL
@@ -720,6 +832,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
max_run_duration = self.context.max_run_duration()
if max_run_duration is not None:
possible_events.append(asyncio.create_task(self._wait_for_max_run_duration(max_run_duration)))
+ if self._sandbox_deadline_snapshot_scheduled():
+ possible_events.append(asyncio.create_task(self._wait_for_sandbox_deadline()))
if ci_follow_up_scheduled:
possible_events.append(asyncio.create_task(self._wait_for_ci_follow_up()))
if not warm_idle and self._self_driving_quota_recheck_scheduled():
@@ -964,6 +1078,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._sandbox_id_for_cleanup = sandbox_id
sandbox_url = input.resumed_sandbox.sandbox_url
sandbox_connect_token = input.resumed_sandbox.connect_token
+ self._sandbox_jwt_kid = input.resumed_sandbox.jwt_kid
workflow.logger.info(
"process_task_resumed_after_continue_as_new",
extra={"run_id": run_id, "sandbox_id": sandbox_id},
@@ -971,16 +1086,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._sandbox_url = sandbox_url
self._sandbox_connect_token = sandbox_connect_token
- relay_task: asyncio.Task[None] | None = None
- if not self.context.sandbox_event_ingest_enabled:
- relay_task = asyncio.ensure_future(
- self._relay_sandbox_events(sandbox_url, sandbox_connect_token, sandbox_id=sandbox_id)
- )
- elif self._is_agent_design_enabled:
- # Sequenced ingest streams events straight to Redis, bypassing the SSE relay that
- # normally fans out the Slack agent-design signals. Tail that stream instead so
- # the per-turn Slack updates still fire.
- relay_task = asyncio.ensure_future(self._relay_agent_design_signals())
+ relay_task: asyncio.Task[None] | None = self._spawn_event_relay(
+ sandbox_url, sandbox_connect_token, sandbox_id
+ )
# Delivered concurrently with the main loop: an approval can arrive while
# the loop is parked inside a followup activity whose turn is blocked on
@@ -1069,6 +1177,88 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._last_active_time = workflow.now()
case _:
raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")
+ case TaskEvent.SANDBOX_TTL_APPROACHING:
+ self._sandbox_ttl_snapshot_taken = True
+ deadline_started_at = workflow.now()
+ workflow.logger.info(
+ "sandbox_deadline_snapshot_started",
+ extra={
+ "run_id": self.context.run_id,
+ "sandbox_id": sandbox_id,
+ "ttl_expires_at": (
+ self._sandbox_ttl_expires_at.isoformat() if self._sandbox_ttl_expires_at else None
+ ),
+ },
+ )
+ rotated_sandbox_id: str | None = None
+ routing_restored = True
+ rotation_snapshot_saved = False
+ rotation_reason: str | None = (
+ "no_sandbox" if not sandbox_id else self._sandbox_rotation_block_reason()
+ )
+ if rotation_reason is None:
+ rotation = await self._rotate_sandbox_before_deadline(
+ sandbox_id, relay_task, credential_refresh_task
+ )
+ rotated_sandbox_id = rotation.sandbox_id
+ relay_task = rotation.relay_task
+ credential_refresh_task = rotation.credential_refresh_task
+ routing_restored = rotation.routing_restored
+ rotation_snapshot_saved = rotation.snapshot_saved
+ rotation_reason = rotation.reason
+ if rotated_sandbox_id:
+ sandbox_id = rotated_sandbox_id
+ await self._emit_progress(
+ step="sandbox_deadline",
+ status="completed",
+ label="Moved to a fresh sandbox",
+ group="sandbox-deadline",
+ detail="This session reached its sandbox time limit and carried on in a new one.",
+ )
+ deadline_outcome = "rotated"
+ else:
+ saved = rotation_snapshot_saved or bool(
+ sandbox_id
+ and await self._create_resume_snapshot(
+ sandbox_id,
+ reason="ttl_expiry",
+ allow_pruning=False,
+ )
+ )
+ if not routing_restored:
+ detail = (
+ "This run can't take more messages: moving it to a fresh sandbox failed "
+ "part way. Start a new run to carry on."
+ if saved
+ else "This run can't take more messages, and the session could not be "
+ "saved. Copy anything you still need from it."
+ )
+ elif saved:
+ detail = (
+ "Sandboxes run for a fixed time and this one is near its limit. "
+ "The session has been saved, so start a new run to pick it up."
+ )
+ else:
+ detail = (
+ "Sandboxes run for a fixed time and this one is near its limit. "
+ "The session could not be saved, so copy anything you still need from it."
+ )
+ await self._emit_progress(
+ step="sandbox_deadline",
+ status="in_progress" if saved and routing_restored else "failed",
+ label="This sandbox stops soon",
+ group="sandbox-deadline",
+ detail=detail,
+ )
+ if not routing_restored:
+ deadline_outcome = "routing_lost"
+ else:
+ deadline_outcome = "snapshot_only" if saved else "snapshot_failed"
+ await self._report_sandbox_deadline_outcome(
+ outcome=deadline_outcome,
+ reason=rotation_reason,
+ duration=workflow.now() - deadline_started_at,
+ )
case TaskEvent.QUOTA_RECHECK:
self._self_driving_quota_next_check_at = workflow.now() + SELF_DRIVING_QUOTA_RECHECK_INTERVAL
try:
@@ -1471,6 +1661,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_id=sandbox_id,
sandbox_url=self._sandbox_url or "",
connect_token=self._sandbox_connect_token,
+ jwt_kid=self._sandbox_jwt_kid,
ci_repetitions=self._ci_repetitions,
pr_fingerprint=self._pr_fingerprint,
pr_unresolved_threads=self._pr_unresolved_threads,
@@ -1487,6 +1678,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
last_agent_heartbeat_at=(
self._last_agent_heartbeat_at.isoformat() if self._last_agent_heartbeat_at else None
),
+ sandbox_ttl_expires_at=(
+ self._sandbox_ttl_expires_at.isoformat() if self._sandbox_ttl_expires_at else None
+ ),
+ sandbox_ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,
),
)
@@ -1517,6 +1712,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._last_agent_heartbeat_at = (
datetime.fromisoformat(resumed.last_agent_heartbeat_at) if resumed.last_agent_heartbeat_at else None
)
+ self._sandbox_ttl_expires_at = (
+ datetime.fromisoformat(resumed.sandbox_ttl_expires_at) if resumed.sandbox_ttl_expires_at else None
+ )
+ self._sandbox_ttl_snapshot_taken = resumed.sandbox_ttl_snapshot_taken
async def _get_task_processing_context(self, input: ProcessTaskInput) -> TaskProcessingContext:
context = await workflow.execute_activity(
@@ -1537,6 +1736,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
created = await self._run_sandbox_creation_activity(prepared)
self._sandbox_id_for_cleanup = created.sandbox_id
+ self._sandbox_jwt_kid = created.jwt_kid
+ self._record_sandbox_deadline(created)
if (
self._task_completed
and prepared.sandbox_creation_cancellable
@@ -1600,6 +1801,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ self._resume_snapshot_invalidated = True
await self._cleanup_sandbox(created.sandbox_id)
self._sandbox_id_for_cleanup = None
fresh_image_source, fresh_image_source_label = get_fresh_image_source_for_context(self.context)
@@ -1624,6 +1826,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
created = await self._run_sandbox_creation_activity(prepared)
self._sandbox_id_for_cleanup = created.sandbox_id
+ self._sandbox_jwt_kid = created.jwt_kid
+ self._record_sandbox_deadline(created)
if (
self._task_completed
and prepared.sandbox_creation_cancellable
@@ -1797,6 +2001,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
connect_token=created.connect_token,
used_snapshot=used_snapshot,
should_create_snapshot=not used_snapshot,
+ jwt_kid=created.jwt_kid,
agent_server_launched=overlap,
boot_path=boot_path,
image_source=prepared.image_source,
@@ -2144,6 +2349,31 @@ class ProcessTaskWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=1),
)
+ async def _report_sandbox_deadline_outcome(self, *, outcome: str, reason: str | None, duration: timedelta) -> None:
+ """Report how a sandbox deadline resolved, for the rollout's metrics.
+
+ Best-effort: a run that survived its deadline must not fail because the report did.
+ """
+ try:
+ await self._track_workflow_event(
+ SANDBOX_DEADLINE_EVENT,
+ {
+ "run_id": self.context.run_id,
+ "task_id": self.context.task_id,
+ "team_id": self.context.team_id,
+ "origin_product": self.context.origin_product,
+ "outcome": outcome,
+ "reason": reason or "none",
+ "duration_seconds": duration.total_seconds(),
+ },
+ capture_analytics=False,
+ )
+ except Exception as e:
+ workflow.logger.warning(
+ "sandbox_deadline_report_failed",
+ extra={"run_id": self.context.run_id, "outcome": outcome, "error": str(e)},
+ )
+
async def _emit_progress(
self,
step: str,
@@ -2277,6 +2507,186 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._completion_timeout_marker = SANDBOX_GONE_STATE_KEY
self._task_completed = True
+ async def _rotate_sandbox_before_deadline(
+ self,
+ old_sandbox_id: str,
+ relay_task: asyncio.Task[None] | None,
+ credential_refresh_task: asyncio.Task[None] | None,
+ ) -> SandboxRotation:
+ """Move the run onto a replacement sandbox built from a snapshot of the current one.
+
+ Every failure leaves the run on the sandbox it already had, which still has the lead
+ time left on its clock — a better place to be than half-way onto a replacement.
+
+ Both background tasks are bound to one sandbox and have to move with it. The credential
+ refresh loop is the sharper of the two: left watching the old sandbox, it reads the
+ cleanup below as SANDBOX_GONE and ends a run that is now healthy on the replacement.
+
+ Clients never hold the sandbox URL — they read the run's Redis stream through Django and
+ send commands the same way — so the swap needs no client involvement beyond keeping that
+ stream fed.
+ """
+ self._resume_snapshot_invalidated = False
+ snapshot = await self._create_resume_snapshot_output(old_sandbox_id, reason="ttl_rotation", allow_pruning=False)
+ if snapshot is None or not snapshot.external_id:
+ return SandboxRotation(
+ relay_task=relay_task, credential_refresh_task=credential_refresh_task, reason="snapshot_missing"
+ )
+
+ self.context.state = {
+ **(self.context.state or {}),
+ "snapshot_external_id": snapshot.external_id,
+ "snapshot_kind": snapshot.snapshot_kind,
+ "snapshot_mount_path": snapshot.snapshot_mount_path,
+ "handoff_resumed": True,
+ "handoff_resume_idle": True,
+ }
+ live_sandbox = PreRotationSandbox(
+ sandbox_id=old_sandbox_id,
+ sandbox_url=self._sandbox_url,
+ connect_token=self._sandbox_connect_token,
+ jwt_kid=self._sandbox_jwt_kid,
+ ttl_expires_at=self._sandbox_ttl_expires_at,
+ ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,
+ )
+
+ if relay_task is not None:
+ await self._cancel_relay(relay_task)
+ relay_task = None
+ if credential_refresh_task is not None:
+ await self._cancel_relay(credential_refresh_task)
+ credential_refresh_task = None
+
+ try:
+ sandbox_output = await self._get_sandbox_for_repository()
+ await self._start_agent_server(sandbox_output)
+ except Exception as e:
+ workflow.logger.warning(
+ "sandbox_rotation_failed",
+ extra={
+ "run_id": self.context.run_id,
+ "sandbox_id": old_sandbox_id,
+ "error": str(e),
+ **self._activity_error_properties(e),
+ },
+ )
+ return await self._abandon_rotation(live_sandbox, reason="provision_failed")
+
+ if not sandbox_output.used_snapshot:
+ # Provisioning reports success for a replacement it had to build without the
+ # snapshot — a dead restore it fell back from, or a provider-side downgrade. That
+ # sandbox holds the branch head, not the run's working tree, so completing the
+ # rotation would destroy the only copy of the agent's uncommitted work and then
+ # tell the user the session carried over.
+ workflow.logger.warning(
+ "sandbox_rotation_abandoned_without_snapshot",
+ extra={
+ "run_id": self.context.run_id,
+ "sandbox_id": old_sandbox_id,
+ "replacement_sandbox_id": sandbox_output.sandbox_id,
+ },
+ )
+ return await self._abandon_rotation(live_sandbox, reason="snapshot_unused")
+
+ self._sandbox_url = sandbox_output.sandbox_url
+ self._sandbox_connect_token = sandbox_output.connect_token
+ self._sandbox_jwt_kid = sandbox_output.jwt_kid
+ self._sandbox_id_for_cleanup = sandbox_output.sandbox_id
+ relay_task = self._spawn_event_relay(
+ sandbox_output.sandbox_url, sandbox_output.connect_token, sandbox_output.sandbox_id
+ )
+ credential_refresh_task = self._spawn_credential_refresh(sandbox_output.sandbox_id)
+ await self._cleanup_sandbox(old_sandbox_id, complete_stream=False)
+ workflow.logger.info(
+ "sandbox_rotated",
+ extra={
+ "run_id": self.context.run_id,
+ "previous_sandbox_id": old_sandbox_id,
+ "sandbox_id": sandbox_output.sandbox_id,
+ "used_snapshot": sandbox_output.used_snapshot,
+ },
+ )
+ return SandboxRotation(
+ sandbox_id=sandbox_output.sandbox_id,
+ relay_task=relay_task,
+ credential_refresh_task=credential_refresh_task,
+ snapshot_saved=True,
+ )
+
+ async def _abandon_rotation(self, live: PreRotationSandbox, *, reason: str) -> SandboxRotation:
+ """Back out of a rotation and put the run back on the sandbox it already had.
+
+ Provisioning publishes the replacement's connection details as soon as that sandbox
+ exists, so backing out means tearing it down and pointing the run's persisted routing,
+ event relay and credential refresh loop at the original again.
+ """
+ abandoned = self._sandbox_id_for_cleanup
+ routing_restored = True
+ if abandoned and abandoned != live.sandbox_id:
+ await self._cleanup_sandbox(abandoned, complete_stream=False)
+ if live.sandbox_url:
+ routing_restored = await self._restore_sandbox_connection_state(
+ live.sandbox_id, live.sandbox_url, live.connect_token, live.jwt_kid
+ )
+ self._sandbox_id_for_cleanup = live.sandbox_id
+ self._sandbox_jwt_kid = live.jwt_kid
+ self._sandbox_ttl_expires_at = live.ttl_expires_at
+ self._sandbox_ttl_snapshot_taken = live.ttl_snapshot_taken
+ relay_task = (
+ self._spawn_event_relay(live.sandbox_url, live.connect_token, live.sandbox_id) if live.sandbox_url else None
+ )
+ return SandboxRotation(
+ relay_task=relay_task,
+ credential_refresh_task=self._spawn_credential_refresh(live.sandbox_id),
+ routing_restored=routing_restored,
+ snapshot_saved=not self._resume_snapshot_invalidated,
+ reason=reason,
+ )
+
+ def _spawn_credential_refresh(self, sandbox_id: str) -> asyncio.Task[None] | None:
+ if not self.context.has_github_credentials:
+ return None
+ return asyncio.ensure_future(self._run_credential_refresh_until_sandbox_gone(sandbox_id))
+
+ async def _restore_sandbox_connection_state(
+ self, sandbox_id: str, sandbox_url: str, connect_token: str | None, jwt_kid: str | None
+ ) -> bool:
+ try:
+ await workflow.execute_activity(
+ restore_sandbox_connection_state,
+ RestoreSandboxConnectionStateInput(
+ run_id=self.context.run_id,
+ sandbox_id=sandbox_id,
+ sandbox_url=sandbox_url,
+ connect_token=connect_token,
+ jwt_kid=jwt_kid,
+ ),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception as e:
+ workflow.logger.exception(
+ "restore_sandbox_connection_state_failed",
+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id, "error": str(e)},
+ )
+ return False
+ return True
+
+ def _spawn_event_relay(
+ self, sandbox_url: str, connect_token: str | None, sandbox_id: str | None
+ ) -> asyncio.Task[None] | None:
+ """Start whichever event pump this run needs, or None when the sandbox posts its own
+ events and nothing has to tail them.
+
+ Sequenced ingest streams events straight to Redis, bypassing the SSE relay that normally
+ fans out the Slack agent-design signals, so that case tails the Redis stream instead.
+ """
+ if not self.context.sandbox_event_ingest_enabled:
+ return asyncio.ensure_future(self._relay_sandbox_events(sandbox_url, connect_token, sandbox_id=sandbox_id))
+ if self._is_agent_design_enabled:
+ return asyncio.ensure_future(self._relay_agent_design_signals())
+ return None
+
async def _relay_sandbox_events(
self, sandbox_url: str, connect_token: str | None, sandbox_id: str | None = None
) -> None:
@@ -2384,7 +2794,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):
pass
async def _create_resume_snapshot(self, sandbox_id: str, *, reason: str, allow_pruning: bool) -> bool:
- """Create a snapshot for interactive sandbox resume."""
+ result = await self._create_resume_snapshot_output(sandbox_id, reason=reason, allow_pruning=allow_pruning)
+ return bool(result and result.external_id)
+
+ async def _create_resume_snapshot_output(
+ self, sandbox_id: str, *, reason: str, allow_pruning: bool
+ ) -> CreateResumeSnapshotOutput | None:
+ """Create a snapshot for interactive sandbox resume. None when the activity itself failed."""
try:
result = await workflow.execute_activity(
create_resume_snapshot,
@@ -2409,7 +2825,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"duration_ms": result.duration_ms,
},
)
- return True
+ return result
elif result.error:
workflow.logger.warning(
"resume_snapshot_skipped",
@@ -2422,7 +2838,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"error": result.error,
},
)
- return False
+ return result
except Exception as e:
workflow.logger.warning(
"resume_snapshot_failed_non_fatal",
@@ -2433,7 +2849,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
"error": str(e),
},
)
- return False
+ return None
+ return result
async def _trigger_snapshot_workflow(self) -> None:
github_integration_id = self.context.github_integration_id