:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): bound validation retries under memory pressure (#110164)
Alessandro Pogliaghib7861303defe
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 2ac5e7aa02d2..e704d920d7cb 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -329,6 +329,14 @@ cd services/mcp && cp .env.example .envThen fill in the secrets. `POSTHOG_UI_APPS_TOKEN` and `POSTHOG_ANALYTICS_API_KEY` are public PostHog `phc_*` project keys — for local dev you can paste the same key you use for analytics, or leave them as the placeholder (analytics calls will no-op). Restart the `mcp` phrocs process after changing `.env`.+### Memory pressure during Claude validation++The memory watchdog stops tool process trees before the sandbox reaches its memory limit. A process stop, including SIGKILL escalation, does not mean the task run died.++Cloud Claude sessions deliver each watchdog warning separately to subagents and their parent. Shell results with exit codes 137, 143, or 144 wait briefly for the watchdog's delayed record; an exit code alone is not treated as proof of an OOM.++Common build, test, and typecheck commands share a sandbox-wide lock, including commands started in the background. When another validation command holds the lock, the shell returns exit code 75 and asks the agent to wait. After the same validation command fails twice during observed watchdog interventions, the session rejects another unchanged attempt. Reduce the command's scope or concurrency, or report the validation limit. This guard is best-effort command recognition, not a resource limit for arbitrary shell programs.+### Local agent packagesCloud tasks use the published `@posthog/agent` package by default. Set `LOCAL_POSTHOG_CODE_MONOREPO_ROOT` only when you need to test local agent changes.diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.tsindex 6f0b2306912e..16459f67a960 100644--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts@@ -1,11 +1,15 @@import { appendFile, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import type { HookInput } from "@anthropic-ai/claude-agent-sdk";+import type {+ PostToolUseFailureHookInput,+ PostToolUseHookInput,+} from "@anthropic-ai/claude-agent-sdk";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { MemoryWatchdogKillReader } from "../../../server/memory-watchdog";import { Logger } from "../../../utils/logger";import { createMemoryKillNoticeHook } from "./memory-kill-hook";+import { VALIDATION_LOCK_PREFIX } from "./memory-validation";const GIB = 1024 ** 3;const STARTED_AT_SECONDS = 1_800_000_000;@@ -27,17 +31,18 @@ function shellInput(hookEventName: "PostToolUse" | "PostToolUseFailure",toolName = "Bash",error = "Exit code 137",-): HookInput {- return {+): PostToolUseHookInput | PostToolUseFailureHookInput {+ const input = {session_id: "s",transcript_path: "/tmp/t",cwd: "/tmp",- hook_event_name: hookEventName,tool_name: toolName,tool_input: { command: "pnpm test" },tool_use_id: "toolu_1",- ...(hookEventName === "PostToolUse" ? { tool_response: "" } : { error }),- } as unknown as HookInput;+ };+ return hookEventName === "PostToolUse"+ ? { ...input, hook_event_name: hookEventName, tool_response: "" }+ : { ...input, hook_event_name: hookEventName, error };}type HookOutput = {@@ -95,32 +100,134 @@ describe("createMemoryKillNoticeHook", () => {},);- it("waits for a kill record written after Bash exits with a signal code", async () => {- await writeFile(path, "");- const reader = new MemoryWatchdogKillReader(path);- const read = reader.readNewKills.bind(reader);- let reads = 0;- reader.readNewKills = async () => {- const kills = await read();- reads += 1;- if (reads === 1) {- await appendFile(path, `${killRecord(8, STARTED_AT_SECONDS + 5)}\n`);- }- return kills;- };+ it.each([137, 143, 144])(+ "waits for a kill record written after Bash exits with code %s",+ async (exitCode) => {+ await writeFile(path, "");+ const reader = new MemoryWatchdogKillReader(path);+ const read = reader.readNewKills.bind(reader);+ let reads = 0;+ reader.readNewKills = async () => {+ const kills = await read();+ reads += 1;+ if (reads === 1) {+ await appendFile(path, `${killRecord(8, STARTED_AT_SECONDS + 5)}\n`);+ }+ return kills;+ };+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ reader,+ startedAtMs: STARTED_AT_SECONDS * 1000,+ killRecordWaitMs: 60_000,+ killRecordPollMs: 1,+ });++ const result = (await hook(+ shellInput("PostToolUseFailure", "Bash", `Exit code ${exitCode}`),+ "toolu_1",+ { signal: new AbortController().signal },+ )) as HookOutput;++ expect(result.hookSpecificOutput?.additionalContext).toContain("(pid 8)");+ },+ );++ it("retains a kill for each worker and the parent after another shell reads it", async () => {+ await writeFile(path, `${killRecord(8, STARTED_AT_SECONDS + 5)}\n`);const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {- reader,+ reader: new MemoryWatchdogKillReader(path),startedAtMs: STARTED_AT_SECONDS * 1000,- killRecordWaitMs: 60_000,- killRecordPollMs: 1,+ killRecordWaitMs: 0,});-- const result = (await hook(- shellInput("PostToolUseFailure", "Bash", "Exit code 143"),- "toolu_1",- { signal: new AbortController().signal },- )) as HookOutput;-- expect(result.hookSpecificOutput?.additionalContext).toContain("(pid 8)");+ const opts = { signal: new AbortController().signal };+ for (const agentId of ["worker-a", "worker-b", undefined]) {+ const input = {+ ...shellInput("PostToolUse", agentId ? "Bash" : "Agent"),+ agent_id: agentId,+ };+ const output = (await hook(input, "toolu_1", opts)) as HookOutput;+ expect(output.hookSpecificOutput?.additionalContext).toContain("(pid 8)");+ expect(await hook(input, "toolu_2", opts)).toEqual({ continue: true });+ }});++ it.each(["pnpm test", "cd /tmp/project && pnpm test"])(+ "serializes %s and scopes retry limits to its directory",+ async (command) => {+ await writeFile(path, "");+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ reader: new MemoryWatchdogKillReader(path),+ startedAtMs: STARTED_AT_SECONDS * 1000,+ killRecordWaitMs: 0,+ });+ const opts = { signal: new AbortController().signal };+ const pre = {+ ...shellInput("PostToolUse"),+ hook_event_name: "PreToolUse" as const,+ tool_input: { command },+ };+ expect(await hook(pre, "toolu_1", opts)).toMatchObject({+ hookSpecificOutput: {+ updatedInput: { command: `${VALIDATION_LOCK_PREFIX}${command}` },+ },+ });+ for (const pid of [8, 9]) {+ await appendFile(+ path,+ `${killRecord(pid, STARTED_AT_SECONDS + pid)}\n`,+ );+ const failure = {+ ...shellInput("PostToolUseFailure", "Bash", "Exit code 144"),+ tool_input: pre.tool_input,+ };+ await hook(failure, `toolu_${pid}`, opts);+ if (pid === 8) {+ await hook(+ {+ ...failure,+ agent_id: "another-worker",+ },+ "toolu_worker",+ opts,+ );+ expect(await hook(pre, "toolu_retry", opts)).toMatchObject({+ hookSpecificOutput: {+ updatedInput: { command: `${VALIDATION_LOCK_PREFIX}${command}` },+ },+ });+ }+ }+ expect(await hook(pre, "toolu_3", opts)).toMatchObject({+ hookSpecificOutput: { permissionDecision: "deny" },+ });+ expect(+ await hook(+ { ...pre, tool_input: { command: `${command} tests/small.test.ts` } },+ "toolu_4",+ opts,+ ),+ ).toMatchObject({+ hookSpecificOutput: {+ updatedInput: {+ command: `${VALIDATION_LOCK_PREFIX}${command} tests/small.test.ts`,+ },+ },+ });+ for (const otherDirectory of [+ { ...pre, cwd: "/tmp/other-worktree" },+ {+ ...pre,+ tool_input: { command: "cd /tmp/other-project && pnpm test" },+ },+ ]) {+ expect(await hook(otherDirectory, "toolu_other", opts)).toMatchObject({+ hookSpecificOutput: {+ updatedInput: {+ command: `${VALIDATION_LOCK_PREFIX}${otherDirectory.tool_input.command}`,+ },+ },+ });+ }+ },+ );});diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.tsindex 3e49e8129213..d4b6fab38f08 100644--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts@@ -1,14 +1,19 @@import { setTimeout as sleep } from "node:timers/promises";-import type { HookCallback, HookInput } from "@anthropic-ai/claude-agent-sdk";+import type {+ HookCallback,+ HookInput,+ HookJSONOutput,+} from "@anthropic-ai/claude-agent-sdk";import type { ProcessKilledParams } from "../../../acp-extensions";import { MemoryWatchdogKillReader } from "../../../server/memory-watchdog";import type { Logger } from "../../../utils/logger";+import { serializeValidation, validationCommandKey } from "./memory-validation";const BYTES_PER_GIB = 1024 ** 3;// BashOutput and TaskOutput return the result of a background Bash command,// which the watchdog can stop after the Bash call itself has returned.const SHELL_RESULT_TOOLS = new Set(["Bash", "BashOutput", "TaskOutput"]);-const SIGNAL_EXIT_PATTERN = /exit[ _]?code"?\s*:?\s*(137|143)\b/i;+const SIGNAL_EXIT_PATTERN = /exit[ _]?code"?\s*:?\s*(137|143|144)\b/i;// The watchdog writes the kill record only after the process tree is gone// and memory is below the trigger. That takes up to two grace periods of// 2 seconds each, so the record can arrive after the shell has exited.@@ -30,9 +35,10 @@ export function formatMemoryKillNotice(kills: ProcessKilledParams[]): string {"The sandbox stopped a shell command because the sandbox was close to its memory limit:",...lines,"",- "The exit status of that command is from this stop, not from the command itself.",- "If you run the same command again without changes, the sandbox will stop it again.",+ "This notice describes memory pressure shared by every agent in the sandbox; it does not identify which tool call was stopped.",+ "Do not rerun a stopped validation command unchanged.","Run a smaller command instead: fewer test files, fewer parallel workers, or one package at a time.",+ "Coordinate with the parent and other agents: run only one memory-heavy build, test suite, or typecheck at a time across all worktrees. Do not start another copy in the background.",].join("\n");}@@ -65,28 +71,93 @@ export const createMemoryKillNoticeHook = (killRecordPollMs = KILL_RECORD_POLL_MS,}: MemoryKillNoticeHookOptions = {},): HookCallback => {+ const killsById = new Map<string, ProcessKilledParams>();+ const delivered = new Map<string, Set<string>>();+ const stoppedCommands = new Map<+ string,+ { failures: number; killIds: Set<string> }+ >();const readKills = async (): Promise<ProcessKilledParams[]> =>(await reader.readNewKills()).filter((kill) => Date.parse(kill.at) >= startedAtMs,);- return async (input: HookInput, _toolUseId, { signal }) => {+ return async (+ input: HookInput,+ toolUseId,+ { signal },+ ): Promise<HookJSONOutput> => {if (+ input.hook_event_name !== "PreToolUse" &&input.hook_event_name !== "PostToolUse" &&input.hook_event_name !== "PostToolUseFailure") {return { continue: true };}- if (!SHELL_RESULT_TOOLS.has(input.tool_name)) return { continue: true };+ if (+ !SHELL_RESULT_TOOLS.has(input.tool_name) &&+ input.tool_name !== "Agent"+ ) {+ return { continue: true };+ }++ const toolInput = input.tool_input as { command?: unknown } | undefined;+ const command =+ typeof toolInput?.command === "string" ? toolInput.command : undefined;+ const validation = command && validationCommandKey(command);+ const validationKey = validation && JSON.stringify([input.cwd, validation]);+ if (input.hook_event_name === "PreToolUse") {+ if (input.tool_name !== "Bash" || !validationKey || !command)+ return { continue: true };+ if ((stoppedCommands.get(validationKey)?.failures ?? 0) >= 2) {+ return {+ continue: true,+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason:+ "This validation command has failed repeatedly during watchdog memory interventions. Do not retry it unchanged. Reduce its scope or worker count, or report that validation could not complete within the sandbox memory limit.",+ },+ };+ }+ return {+ continue: true,+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ updatedInput: { ...toolInput, command: serializeValidation(command) },+ },+ };+ }++ const consumer = input.agent_id ?? input.session_id;+ const seen = delivered.get(consumer) ?? new Set<string>();+ delivered.set(consumer, seen);++ const pendingKills = async (): Promise<ProcessKilledParams[]> => {+ for (const kill of await readKills()) {+ killsById.set(`${kill.at}:${kill.pid}`, kill);+ }+ while (killsById.size > 100) {+ const oldest = killsById.keys().next().value;+ if (oldest === undefined) break;+ killsById.delete(oldest);+ for (const consumerSeen of delivered.values())+ consumerSeen.delete(oldest);+ }+ // Every worker needs the warning; a fast unrelated shell must not consume it.+ return [...killsById]+ .filter(([id]) => !seen.has(id))+ .map(([, kill]) => kill);+ };let kills: ProcessKilledParams[];try {- kills = await readKills();+ kills = await pendingKills();if (kills.length === 0 && endedBySignal(input)) {const deadline = Date.now() + killRecordWaitMs;while (kills.length === 0 && Date.now() < deadline && !signal.aborted) {await sleep(killRecordPollMs);- kills = await readKills();+ kills = await pendingKills();}}} catch (error) {@@ -97,6 +168,25 @@ export const createMemoryKillNoticeHook = (}if (kills.length === 0) return { continue: true };+ for (const kill of kills) seen.add(`${kill.at}:${kill.pid}`);+ if (validationKey && endedBySignal(input)) {+ const interventions = stoppedCommands.get(validationKey) ?? {+ failures: 0,+ killIds: new Set<string>(),+ };+ const ids = kills.map((kill) => `${kill.at}:${kill.pid}`);+ if (ids.some((id) => !interventions.killIds.has(id))) {+ interventions.failures += 1;+ for (const id of ids) interventions.killIds.add(id);+ }+ stoppedCommands.set(validationKey, interventions);+ }+ logger.info("Memory watchdog feedback delivered to hook", {+ agentId: input.agent_id ?? null,+ toolUseId,+ killCount: kills.length,+ });+return {continue: true,hookSpecificOutput: {diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.tsnew file mode 100644index 000000000000..f99eb9b1c8df--- /dev/null+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";+import { serializeValidation, validationCommandKey } from "./memory-validation";++describe("validationCommandKey", () => {+ it.each([+ [+ "pnpm --filter=frontend typescript:check 2>&1 | tail -8",+ "pnpm --filter=frontend typescript:check",+ ],+ [+ "cd /tmp/project && pnpm test src/small.test.ts",+ "cd /tmp/project && pnpm test src/small.test.ts",+ ],+ ["uv run pytest tests/unit", "uv run pytest tests/unit"],+ ["cargo test --jobs 1", "cargo test --jobs 1"],+ ["go build ./cmd/demo", "go build ./cmd/demo"],+ ["git status", undefined],+ ['echo "pnpm test"', undefined],+ ["cat test-output.txt", undefined],+ ])("recognizes validation scope in %s", (command, expected) => {+ expect(validationCommandKey(command)).toBe(expected);+ if (expected) {+ expect(validationCommandKey(serializeValidation(command))).toBe(expected);+ }+ });+});diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.tsnew file mode 100644index 000000000000..d46a83f79aa4--- /dev/null+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts@@ -0,0 +1,29 @@+const VALIDATION_COMMAND =+ /(?:^|[;&|()\n])\s*(?:(?:env|exec|time)\s+)?(?:(?:pnpm|npm|yarn|bun)\b[^;&|\n]*\b(?:test|build|typecheck|typescript:check)\b[^;&|\n]*|(?:uv\s+run\s+)?(?:pytest|jest|vitest|tsc|tsgo)\b[^;&|\n]*|(?:cargo|go)\s+(?:test|build|check)\b[^;&|\n]*)/;++export const VALIDATION_LOCK_PREFIX = [+ "exec {__posthog_validation_lock_fd}>/tmp/posthog-memory-validation.lock",+ 'if ! flock -n "$__posthog_validation_lock_fd"; then',+ ' printf "%s\\n" "Another build, test suite, or typecheck is running in this sandbox. Let it finish before starting more validation, including in other worktrees." >&2',+ " exit 75",+ "fi",+ "",+].join("\n");++export function validationCommandKey(command: string): string | undefined {+ const original = command.startsWith(VALIDATION_LOCK_PREFIX)+ ? command.slice(VALIDATION_LOCK_PREFIX.length)+ : command;+ const validation = VALIDATION_COMMAND.exec(original);+ if (!validation) return undefined;+ return (+ original.slice(0, validation.index) ++ validation[0].replace(/\s+\d*>{1,2}.*$/, "")+ ).trim();+}++export function serializeValidation(command: string): string {+ return command.startsWith(VALIDATION_LOCK_PREFIX)+ ? command+ : VALIDATION_LOCK_PREFIX + command;+}diff --git a/packages/agent/packages/agent/src/adapters/claude/session/options.test.ts b/packages/agent/packages/agent/src/adapters/claude/session/options.test.tsindex 91ab1988e782..4df50cb2681d 100644--- a/packages/agent/packages/agent/src/adapters/claude/session/options.test.ts+++ b/packages/agent/packages/agent/src/adapters/claude/session/options.test.ts@@ -5,6 +5,7 @@ import type { HookInput, Options } from "@anthropic-ai/claude-agent-sdk";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Logger } from "../../../utils/logger";import { SUBAGENT_REWRITES } from "../hooks";+import { VALIDATION_LOCK_PREFIX } from "./memory-validation";import {buildSessionOptions,buildSystemPrompt,@@ -253,6 +254,25 @@ describe("buildSessionOptions", () => {};};+ it("keeps the cloud validation lock when RTK rewriting is enabled", async () => {+ const options = buildSessionOptions({ ...makeParams(), cloudMode: true });+ const hooks = (options.hooks?.PreToolUse ?? []).flatMap(+ (entry) => entry.hooks ?? [],+ );+ const outputs = (await Promise.all(+ hooks.map((hook) =>+ hook(bashInput("pnpm test"), "toolu_test", {+ signal: new AbortController().signal,+ }),+ ),+ )) as PreToolUseOutput[];+ expect(+ outputs.flatMap(+ (output) => output.hookSpecificOutput?.updatedInput?.command ?? [],+ ),+ ).toEqual([`${VALIDATION_LOCK_PREFIX}pnpm test`]);+ });+it("registers the signed-commit guard before the rtk rewrite so the guard evaluates raw commands (cloud)", async () => {const options = buildSessionOptions({...makeParams(),diff --git a/packages/agent/packages/agent/src/adapters/claude/session/options.ts b/packages/agent/packages/agent/src/adapters/claude/session/options.tsindex 192fa2fe6085..bb14c8a9b8f3 100644--- a/packages/agent/packages/agent/src/adapters/claude/session/options.ts+++ b/packages/agent/packages/agent/src/adapters/claude/session/options.ts@@ -410,16 +410,24 @@ function buildHooks(if (budgetGuard) {preToolUseHooks.push(budgetGuard.preToolUseHook());}- // Registered last so the signed-commit guard evaluates the raw command first.- if (rtkPrefix) {- preToolUseHooks.push(createRtkRewriteHook(rtkPrefix, logger));- }+ const rtkHook = rtkPrefix+ ? createRtkRewriteHook(rtkPrefix, logger)+ : undefined;const postToolUseFailureHooks: HookCallback[] = [];if (cloudMode) {const memoryKillNoticeHook = createMemoryKillNoticeHook(logger);+ // Compose rewrites so RTK cannot replace the validation lock prefix.+ preToolUseHooks.push(async (input, toolUseId, options) => {+ const result = await memoryKillNoticeHook(input, toolUseId, options);+ if ("hookSpecificOutput" in result && result.hookSpecificOutput)+ return result;+ return rtkHook ? rtkHook(input, toolUseId, options) : result;+ });postToolUseHooks.push(memoryKillNoticeHook);postToolUseFailureHooks.push(memoryKillNoticeHook);+ } else if (rtkHook) {+ preToolUseHooks.push(rtkHook);}const taskHook = createTaskHook(taskState, onTaskStateChange);