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): preserve task state when checkpointing (#116932)

Alessandro Pogliaghi83fac0a87843
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index b990585b1e14..2b8e6cb1cc45 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -139,6 +139,14 @@ Codex's sessions and shell snapshots into that directory before starting a sessi
Authentication and platform configuration stay outside these mappings. Pi restores
its session history through the task-session API.
+The agent stores completed prompt acknowledgements in its persistent state directory,
+so a resumed server skips completed prompts even when clearing their API state failed.
+Creating a resume snapshot preserves pending user messages until delivery handles
+them. If capture exceeds the file limit, it reports failure and retains the previous
+checkpoint without pruning the live workspace. Directory names such as `.cache` or
+`.venv` do not establish that their contents can be rebuilt. The legacy
+`allow_pruning` activity field remains readable but no longer enables deletion.
+
## Running via the UI
This is very minimal at the moment, but the tasks page can be used to see what
diff --git a/packages/agent/packages/agent/src/server/agent-server.test.ts b/packages/agent/packages/agent/src/server/agent-server.test.ts
index 4eb1389681be..b949e160d0cd 100644
--- a/packages/agent/packages/agent/src/server/agent-server.test.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.test.ts
@@ -5273,65 +5273,91 @@ describe("AgentServer HTTP Mode", () => {
expect(result).toBeNull();
});
- it("removes pending prompt keys when clearing initial prompt state", async () => {
- const s = createServer();
- const updateTaskRun = vi
- .spyOn(
- (
- s as unknown as {
- posthogAPI: {
- updateTaskRun: (...args: unknown[]) => Promise<unknown>;
- };
- }
- ).posthogAPI,
- "updateTaskRun",
- )
- .mockResolvedValue({} as never);
- const run = {
- id: "test-run-id",
- task: "test-task-id",
- state: {
- sandbox_url: "https://sandbox.example.com",
- sandbox_connect_token: "token",
- pending_user_message: "read this",
- pending_user_artifact_ids: ["artifact-1"],
- pending_user_message_ts: "123.456",
- },
- } as unknown as TaskRun;
+ it.each([false, true])(
+ "acknowledges pending prompts across restarts (patch fails: %s)",
+ async (patchFails) => {
+ const agentStateDir = join(repo.path, ".posthog", "agent-state");
+ const s = createServer({ agentStateDir });
+ const updateTaskRun = vi
+ .spyOn(
+ (
+ s as unknown as {
+ posthogAPI: {
+ updateTaskRun: (...args: unknown[]) => Promise<unknown>;
+ };
+ }
+ ).posthogAPI,
+ "updateTaskRun",
+ )
+ .mockResolvedValue({} as never);
+ const run = {
+ id: "test-run-id",
+ task: "test-task-id",
+ state: {
+ sandbox_url: "https://sandbox.example.com",
+ sandbox_connect_token: "token",
+ pending_user_message: "read this",
+ pending_user_artifact_ids: ["artifact-1"],
+ pending_user_message_ts: "123.456",
+ },
+ } as unknown as TaskRun;
- const nextState = (
- s as unknown as TestableServer
- ).getClearedPendingUserState(run);
- expect(nextState).toEqual([
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_ts",
- ]);
+ const nextState = (
+ s as unknown as TestableServer
+ ).getClearedPendingUserState(run);
+ expect(nextState).toEqual([
+ "pending_user_message",
+ "pending_user_artifact_ids",
+ "pending_user_message_ts",
+ ]);
- await (s as unknown as TestableServer).clearPendingInitialPromptState(
- {
- run_id: "test-run-id",
- task_id: "test-task-id",
+ if (patchFails) updateTaskRun.mockRejectedValue(new Error("HTTP 503"));
+ await (s as unknown as TestableServer).clearPendingInitialPromptState(
+ {
+ run_id: "test-run-id",
+ task_id: "test-task-id",
+ team_id: 1,
+ user_id: 1,
+ distinct_id: "test-distinct-id",
+ mode: "interactive",
+ },
+ run,
+ );
+
+ expect(updateTaskRun).toHaveBeenCalledWith(
+ "test-task-id",
+ "test-run-id",
+ {
+ state_remove_keys: [
+ "pending_user_message",
+ "pending_user_artifact_ids",
+ "pending_user_message_ts",
+ ],
+ },
+ );
+ const restored = createServer({ agentStateDir });
+ const api = (restored as unknown as { posthogAPI: PostHogAPIClient })
+ .posthogAPI;
+ vi.spyOn(api, "getTaskRun").mockResolvedValue(run);
+ vi.spyOn(api, "updateTaskRun").mockResolvedValue(run);
+ const payload: JwtPayload = {
+ run_id: run.id,
+ task_id: run.task,
team_id: 1,
user_id: 1,
- distinct_id: "test-distinct-id",
+ distinct_id: "test-user",
mode: "interactive",
- },
- run,
- );
-
- expect(updateTaskRun).toHaveBeenCalledWith(
- "test-task-id",
- "test-run-id",
- {
- state_remove_keys: [
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_ts",
- ],
- },
- );
- });
+ };
+ const startup = restored as unknown as StartupTestServer;
+ expect(
+ (await startup.prepareInitialTaskMessage(payload, run)).action,
+ ).toBe("idle");
+ run.state.pending_user_message_ts = "123.457";
+ expect(
+ (await startup.prepareInitialTaskMessage(payload, run)).action,
+ ).toBe("initial");
+ },
+ );
});
describe("resume prompt display", () => {
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 5b63a332b01b..74a0c15194c5 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -3005,6 +3005,16 @@ export class AgentServer {
"Could not load task run to determine its initial prompt",
);
}
+ const acknowledgementPath = this.pendingPromptAcknowledgementPath(taskRun);
+ if (acknowledgementPath) {
+ try {
+ await access(acknowledgementPath);
+ await this.clearPendingInitialPromptState(payload, taskRun);
+ return { taskRun, action: "idle" };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ }
const taskRunState = taskRun.state;
const prewarmed = taskRunState.prewarmed === true;
const sameRunResume =
@@ -3778,6 +3788,30 @@ export class AgentServer {
return pendingKeys.length > 0 ? pendingKeys : null;
}
+ private pendingPromptAcknowledgementPath(
+ taskRun: TaskRun | null,
+ ): string | null {
+ if (
+ !this.config.agentStateDir ||
+ !taskRun ||
+ !this.getClearedPendingUserState(taskRun)
+ )
+ return null;
+ const state = taskRun.state;
+ const key = createHash("sha256")
+ .update(
+ JSON.stringify([
+ taskRun.id,
+ state.pending_user_message_id,
+ state.pending_user_message_ts,
+ state.pending_user_message,
+ state.pending_user_artifact_ids,
+ ]),
+ )
+ .digest("hex");
+ return join(this.config.agentStateDir, "prompt-acknowledgements", key);
+ }
+
private async clearPendingInitialPromptState(
payload: JwtPayload,
taskRun: TaskRun | null,
@@ -3787,6 +3821,12 @@ export class AgentServer {
return;
}
+ const acknowledgementPath = this.pendingPromptAcknowledgementPath(taskRun);
+ if (acknowledgementPath) {
+ await mkdir(dirname(acknowledgementPath), { recursive: true });
+ await writeFile(acknowledgementPath, "");
+ }
+
try {
await this.posthogAPI.updateTaskRun(payload.task_id, payload.run_id, {
state_remove_keys: stateRemoveKeys,
diff --git a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
index a7996c528232..fe6280f56994 100644
--- a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py
@@ -23,13 +23,6 @@ from products.tasks.backend.temporal.observability import emit_agent_log
logger = structlog.get_logger(__name__)
-PENDING_USER_STATE_KEYS = [
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_id",
- "pending_user_message_ts",
-]
-
@dataclass(frozen=True)
class CreateResumeSnapshotInput:
@@ -121,39 +114,10 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap
try:
external_id = sandbox.create_directory_snapshot(snapshot_mount_path)
except SnapshotFileLimitExceededError as e:
- if not input.allow_pruning:
- outcome = "file_limit_exceeded"
- duration_ms = int((time.perf_counter() - started_at) * 1000)
- logger.warning(
- "create_resume_snapshot_file_limit_exceeded",
- sandbox_id=input.sandbox_id,
- run_id=input.run_id,
- reason=input.reason,
- snapshot_kind=snapshot_kind,
- duration_ms=duration_ms,
- error=str(e),
- )
- increment_snapshot_create(snapshot_kind, outcome)
- record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)
- emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): file limit exceeded")
- return CreateResumeSnapshotOutput(
- external_id=None,
- snapshot_kind=snapshot_kind,
- error=str(e),
- duration_ms=duration_ms,
- )
-
- # Prune the reproducible trees (node_modules, virtualenvs, caches) in the live sandbox,
- # then let Temporal retry the whole activity: the next attempt snapshots the now-smaller
- # tree in a fresh 5-minute budget. Doing the prune here and re-raising a transient error —
- # rather than snapshotting again inline — keeps each attempt to a single snapshot, so the
- # activity's timeout can't pre-empt the recovery. If pruning does not bring the tree under
- # the cap, retries exhaust and both callers treat the failed snapshot as non-fatal (the run
- # starts fresh). The resume sandbox reinstalls the pruned trees, so this costs a reinstall.
- outcome = "file_limit_exceeded_pruned"
+ outcome = "file_limit_exceeded"
duration_ms = int((time.perf_counter() - started_at) * 1000)
logger.warning(
- "create_resume_snapshot_file_limit_exceeded_pruning",
+ "create_resume_snapshot_file_limit_exceeded",
sandbox_id=input.sandbox_id,
run_id=input.run_id,
reason=input.reason,
@@ -161,16 +125,14 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap
duration_ms=duration_ms,
error=str(e),
)
- sandbox.prune_snapshot_heavy_dirs(snapshot_mount_path)
increment_snapshot_create(snapshot_kind, outcome)
record_snapshot_create_latency_ms(snapshot_kind, outcome, duration_ms)
- # capture=False: the original SnapshotFileLimitExceededError already carried the signal;
- # this transient wrapper only drives the Temporal retry.
- raise SnapshotTimeoutError(
- f"Pruned workspace over Modal's file-count cap; retrying snapshot: {e}",
- {"sandbox_id": input.sandbox_id, "snapshot_mount_path": snapshot_mount_path},
- cause=e,
- capture=False,
+ emit_agent_log(input.run_id, "debug", f"Resume snapshot failed ({input.reason}): file limit exceeded")
+ return CreateResumeSnapshotOutput(
+ external_id=None,
+ snapshot_kind=snapshot_kind,
+ error=str(e),
+ duration_ms=duration_ms,
)
except SnapshotTimeoutError as e:
outcome = "transient_error"
@@ -236,7 +198,7 @@ def create_resume_snapshot(input: CreateResumeSnapshotInput) -> CreateResumeSnap
"snapshot_kind": snapshot_kind,
"snapshot_mount_path": snapshot_mount_path,
}
- TaskRun.update_state_atomic(input.run_id, updates=updates, remove_keys=PENDING_USER_STATE_KEYS)
+ TaskRun.update_state_atomic(input.run_id, updates=updates)
except Exception as e:
outcome = "persist_failed"
duration_ms = int((time.perf_counter() - started_at) * 1000)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py
index aaa2660385d0..4170dd0a33b9 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py
@@ -1,10 +1,12 @@
+from inspect import unwrap
+
import pytest
from asgiref.sync import async_to_sync
from products.tasks.backend.constants import DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH, SNAPSHOT_KIND_DIRECTORY
from products.tasks.backend.exceptions import SnapshotFileLimitExceededError, SnapshotTimeoutError
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.process_task.activities.create_resume_snapshot import (
CreateResumeSnapshotInput,
create_resume_snapshot,
@@ -12,10 +14,23 @@ from products.tasks.backend.temporal.process_task.activities.create_resume_snaps
@pytest.mark.django_db
-def test_create_directory_resume_snapshot_uses_tmp_mount_path(activity_environment, mocker) -> None:
+def test_create_directory_resume_snapshot_preserves_pending_delivery(activity_environment, mocker, team) -> None:
+ task = Task.objects.create(team=team, title="Checkpoint test")
+ run = TaskRun.objects.create(team=team, task=task, state={"snapshot_external_id": "im-previous"})
+ pending_state = {
+ "pending_user_message": "Run the tests",
+ "pending_user_artifact_ids": ["artifact-1"],
+ "pending_user_message_id": "message-1",
+ "pending_user_message_ts": "1.0",
+ }
+
+ def capture_snapshot(path: str) -> str:
+ TaskRun.update_state_atomic(str(run.id), updates=pending_state)
+ return "im-dir"
+
sandbox = mocker.Mock()
sandbox.is_running.return_value = True
- sandbox.create_directory_snapshot.return_value = "im-dir"
+ sandbox.create_directory_snapshot.side_effect = capture_snapshot
SandboxClass = mocker.Mock()
SandboxClass.get_by_id.return_value = sandbox
@@ -23,29 +38,20 @@ def test_create_directory_resume_snapshot_uses_tmp_mount_path(activity_environme
"products.tasks.backend.temporal.process_task.activities.create_resume_snapshot.get_sandbox_class",
return_value=SandboxClass,
)
- update_state = mocker.patch.object(TaskRun, "update_state_atomic")
-
- output = async_to_sync(activity_environment.run)(
- create_resume_snapshot,
- CreateResumeSnapshotInput(sandbox_id="sandbox-1", run_id="run-1", use_directory_snapshot=True),
+ output = activity_environment.run(
+ unwrap(create_resume_snapshot),
+ CreateResumeSnapshotInput(sandbox_id="sandbox-1", run_id=str(run.id), use_directory_snapshot=True),
)
sandbox.create_directory_snapshot.assert_called_once_with(DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH)
sandbox.create_snapshot.assert_not_called()
- update_state.assert_called_once_with(
- "run-1",
- updates={
- "snapshot_external_id": "im-dir",
- "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,
- "snapshot_mount_path": DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
- },
- remove_keys=[
- "pending_user_message",
- "pending_user_artifact_ids",
- "pending_user_message_id",
- "pending_user_message_ts",
- ],
- )
+ run.refresh_from_db()
+ assert run.state == {
+ **pending_state,
+ "snapshot_external_id": "im-dir",
+ "snapshot_kind": SNAPSHOT_KIND_DIRECTORY,
+ "snapshot_mount_path": DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
+ }
assert output.external_id == "im-dir"
assert output.snapshot_kind == SNAPSHOT_KIND_DIRECTORY
assert output.snapshot_mount_path == DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH
@@ -88,10 +94,15 @@ def _file_limit_error() -> SnapshotFileLimitExceededError:
@pytest.mark.django_db
-def test_directory_file_limit_does_not_prune_live_sandbox(activity_environment, mocker) -> None:
[email protected]("allow_pruning", [False, True])
+def test_directory_file_limit_preserves_state(activity_environment, mocker, tmp_path, allow_pruning: bool) -> None:
+ saved_file = tmp_path / ".cache" / "notes.txt"
+ saved_file.parent.mkdir()
+ saved_file.write_text("Uncommitted task notes")
sandbox = mocker.Mock()
sandbox.is_running.return_value = True
sandbox.create_directory_snapshot.side_effect = _file_limit_error()
+ sandbox.prune_snapshot_heavy_dirs.side_effect = lambda path: saved_file.unlink()
SandboxClass = mocker.Mock()
SandboxClass.get_by_id.return_value = sandbox
@@ -104,42 +115,11 @@ def test_directory_file_limit_does_not_prune_live_sandbox(activity_environment,
output = async_to_sync(activity_environment.run)(
create_resume_snapshot,
CreateResumeSnapshotInput(
- sandbox_id="sandbox-1",
- run_id="run-1",
- use_directory_snapshot=True,
- reason="ci_follow_up",
- allow_pruning=False,
+ sandbox_id="sandbox-1", run_id="run-1", use_directory_snapshot=True, allow_pruning=allow_pruning
),
)
assert output.external_id is None
assert output.error is not None
- sandbox.prune_snapshot_heavy_dirs.assert_not_called()
- update_state.assert_not_called()
-
-
-def test_directory_file_limit_prunes_and_retries_via_temporal(activity_environment, mocker) -> None:
- # A directory snapshot over the cap prunes the live sandbox and re-raises a transient error so
- # Temporal retries the whole activity on the shrunk tree — a single snapshot per attempt keeps
- # the recovery inside the activity's timeout budget.
- sandbox = mocker.Mock()
- sandbox.is_running.return_value = True
- sandbox.create_directory_snapshot.side_effect = _file_limit_error()
- SandboxClass = mocker.Mock()
- SandboxClass.get_by_id.return_value = sandbox
-
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.create_resume_snapshot.get_sandbox_class",
- return_value=SandboxClass,
- )
- update_state = mocker.patch.object(TaskRun, "update_state_atomic")
-
- with pytest.raises(SnapshotTimeoutError):
- async_to_sync(activity_environment.run)(
- create_resume_snapshot,
- CreateResumeSnapshotInput(sandbox_id="sandbox-1", run_id="run-1", use_directory_snapshot=True),
- )
-
- sandbox.prune_snapshot_heavy_dirs.assert_called_once_with(DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH)
+ assert saved_file.read_text() == "Uncommitted task notes"
update_state.assert_not_called()